Files
photoreport/docs/ARCHITECTURE.md
spark 737b6e472c
ci / rust (pull_request) Successful in 6m7s
ci / typescript (pull_request) Successful in 11m18s
feat(galleries): deliver a session as its own page on the site
A client gallery is its own module, apart from the shop and from file delivery.
It is built from an event's photographs and opens at /cliente/<slug>.
2026-11-12 00:02:00 +00:00

614 lines
54 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Architecture
Living plan (Portuguese, editable): https://claude.ai/code/artifact/f64515d2-9d1f-47d5-ade1-743511fb3da2
This file is the in-repo summary agents work from. Decisions dated 2026-10-11.
## Decisions
- One monorepo, one API, one PostgreSQL database, one account system, one UI for web and desktop.
- **Local-first:** every photographer-facing feature must work on the desktop without the network; the web/API
are the sync and multi-user glue. Offline work syncs when a link returns. Do not require uploading every frame
for decisions that can run on the machine (AGENTS.md §12). Prefer Rust (`engine/`) for heavy local work (§13).
- **App modules:** the top bar is a set of modules a person may or may not have. The organization list and each
membership are set on the web (Membros). `PHOTOREPORT_APP_MODULES` caps what a server may offer. See "App modules".
- Built greenfield on new containers and the `next` environment; old projects keep running until cutover.
Final domain: `app.photoreport.pt`. Data (accounts, galleries, sales, squads) is imported, not restarted.
- Desktop = Tauri around the same React SPA (replaces the Flutter Studio).
- Develop engine = LightCraft crates (`lightcraft-develop`, `lightcraft-pipeline`, `lightcraft-raw`,
`lightcraft-codecs`, `lightcraft-faces`), pinned, behind `engine/core`. Not `lightcraft-engine`/`catalog`
for the library: our catalog is the API. The desktop folder merge is the exception (`photo-merge`):
it runs LightCraft Photo Merge so a raw without its own matrices still gets colour tags in the DNG.
The browser engine leaves that feature off.
- Faces: `lightcraft-faces` (YuNet detection + AuraFace v1 recognition, SFace optional; pure Rust) in
`workers/faces`, a long-running process the background worker talks to over stdin/stdout. See "Faces" below.
Enabled for FPA (own photos, internal federation use for news and galleries); off by default elsewhere.
- Jersey numbers: PaddleOCR in `workers/ml`, matched against the squad. OpenAI fallback off by default.
- CPU: no practical limit; workers scale to whatever cores are needed. Speed first.
- Priority cameras: Canon EOS R1 and R3, then pro Canon, Sony and Nikon bodies used by photojournalists.
## Stack
Node 24 + TypeScript + Fastify · PostgreSQL 17 + pgvector · Prisma · queues as PostgreSQL tables
(`FOR UPDATE SKIP LOCKED`) · Socket.io fanned out with `LISTEN/NOTIFY` · sharp + ExifTool · local storage now,
Garage (S3-compatible) later · SFTPGo (tusd later) · React + Vite + Tailwind (`apps/app`) · Next.js
(`apps/site`) · Tauri 2 (`apps/desktop`) · Rust (`engine`, `workers/render`) · Python (`workers/ml`).
## Realtime edits (Revelar)
One engine everywhere: `engine/core` wraps the LightCraft develop crates (settings, commands, decode, render).
It runs natively in `workers/render` and in the browser as WASM (`engine/wasm`, about 2.5 MB, built into
`apps/app/public/engine/` and loaded by a Web Worker), so the desktop app (the web app in a Tauri shell) and the
browser show the same pixels.
- A window sends edit commands (never pixels) with `POST /v1/photos/:id/edits` (`{clientId, ops: [{opId,
command}]}`). The API checks them against the pinned control list (`controls.generated.json`), assigns the
per-photo `seq` under a row lock, stores them in `photo_edits` (a retried `opId` is stored once) and fans them
out as `photo.edited` on the library channel. Last writer wins per control.
- Each window replays the log with its own engine: confirmed settings plus its own unacknowledged edits on top,
so edits show at once and remote ones slot in underneath. A gap in `seq` (lost message, reconnect) fetches
`GET /v1/photos/:id/develop?since=<seq>`. Unsent edits stay in a per-photo outbox in local storage and are
retried with back-off, so editing offline works and survives a reload.
- Slider drags: the queued op is replaced until it is sent (about one op per 120 ms on the wire), one undo step
per drag. Undo/redo are new ops that put the previous values back.
- The worker keeps a settings snapshot per photo (`develop_snapshot`, `snapshot_seq`) and, two seconds after
edits stop, renders edited thumb and preview from the original (`photo.rendered` with new URLs; `source` stays
the unedited preview the editor renders on). Deliveries of edited photos are rendered by the engine from the
original at the delivery size, camera EXIF copied back, orientation reset, IPTC written as before.
- Measured: decode of a 24 MP JPEG to 2048 px about 0.5 s and a 1600 px render about 0.25 s in WASM (one
thread); a 4000 px delivery render about 2 s natively.
## Uploads and ingest
Camera -> SFTPGo (FTP/SFTP) into `<INGEST_ROOT>/<ftp login>/`. Each login is tied to one member of one
organization (`ftp_accounts`, managed by admins). The worker (`apps/api/src/worker.ts`) picks a file up once
its size and time stop changing, hashes it (duplicates are dropped), reads EXIF (capture time in Lisbon time
unless the camera wrote an offset; a per-login clock offset fixes drifting bodies), routes it to the event the
photographer is assigned to whose ingest window (default: 2 h before to 4 h after the start) holds the capture
time, or to the inbox, moves it into storage and makes a 480 px thumb and a 2048 px preview. Unreadable files
are kept and marked failed; non-JPEG and unknown logins are set aside in `_unsupported/` and `_unclaimed/`.
Measured locally: a dropped JPEG shows up in an open browser in about 2 s.
FTP packages (`ftp_plans`, the old app's "pacotes", Membros → Pacotes FTP): days a login lasts and upload quotas
in MB and files (0: none). Giving a login a plan sets its end date (now + days); "Renovar" adds another period
from the end date, or from now once ended; the end date can also be set by hand. The auth hook refuses an ended
login and hands SFTPGo `expiration_date`, `quota_size` and `quota_files`, which SFTPGo enforces as it counts uploads.
Local FTP (desktop app, `apps/desktop/src-tauri/src/ftp.rs`, libunftp): the camera sends to the photographer's own
computer on the same network (port 2121, passive 50000-50100, all IPv4 interfaces), with as many logins as there are
bodies, each switchable off. "Testar ligação" (`ftp_check`, run after every start) connects to each LAN address
like a camera and reads the greeting, and on macOS reads the application firewall (`socketfilterfw`: block all, or
PhotoReport blocked) to tell the photographer what to change. Another FTP server on the same port takes the
connections, so the panel says to close it.
Photos from the local FTP count as camera ingest (`source` DESKTOP), previews and full originals alike (the
resumable start says `desktop: true` for an original), so the event's autopilot edits them; only hand uploads are
left as sent. Faces and the autopilot work per event: photos with no event (the inbox) are analysed for faces but
not grouped or edited. The face worker also queues, every minute, photos left at "no analysis" in organizations
with biometrics on.
Uploads from the browser or desktop (`POST /v1/orgs/:orgId/uploads`, one photo per request) go through the
same pipeline; an upload can target an open event directly. Still to come: resumable uploads (tus, preview
first from the desktop), OCR and faces at ingest, and the final export
replaying the edit op log (phase 2). Files live on local disk behind `LocalStorage` (originals and
derivatives per organization); the API and the worker share that folder (Proxmox bind mount). Garage replaces
it when files must be served from more than one host.
## App modules
The workspace is a set of modules. A person sees one only when the organization has it and their membership includes it. Owners always have every module the organization has. An empty personal list follows the role: library and develop for a photographer or client; the areas that already existed for an ingester and above. Site galleries are not in that usual set. An admin turns that module on for the organization, then grants it per person, on the members page. The desktop keeps the last signed-in list and uses it offline.
`PHOTOREPORT_APP_MODULES` (comma-separated ids, unset = no cap) is the server ceiling. The web members page is how an admin sets the organization and each person.
`siteGallery` is its own module: a delivery into a gallery on a site (its address, cover and the people it is shared with). The sports shop stays in Vendas. File delivery stays in Entregar. Hiding Metadados does not block a caption edited from the library; those routes stay shared.
A client gallery (`site_galleries`) belongs to the organization. An editor sees every one; a photographer sees and fills only the ones they created, and only with photos they uploaded. A session on the gallery, when there is one, has to be an event assigned to them. Sets, the cover (moldura, clássica, ampla, simples, moderna), palette, grid and download rules live on the row. Publishing puts it at `/cliente/<slug>` on the events site. The address is unique. A password keeps the page locked; a PIN limits downloads. Shares are the people it was sent to (by mail when SMTP is set, otherwise the link is kept to copy). A gallery typed with no network waits on the computer and is created when the link returns. `/cliente/exemplo` is a built-in sample that does not need the API.
## Galleries and shop
- Sites: each domain (photoreport.pt, shootyourmove.com, ...) is a `sites` row: organization, skin
(`photoreport` editorial light, `shootyourmove` dark with red) and texts. `apps/site` (Next.js) is one build for
every domain; it asks the API with `x-site-domain` and proxies `/v1` so browsers stay on the site's origin.
- Galleries are made in the app (Vendas, or "Adicionar à galeria" on a library selection), usually from an
event with its picks. Public (listed), unlisted (link only) or private (link + password; the unlock returns a
token valid for a week, kept in a cookie). Photos on the sites are watermarked with the site's name (600 and
1600 px), made on first view from the edited preview and cached until the edit changes; URLs are signed.
- Site home: search (title, teams, competition, venue and the players named in the photos), sport shortcuts,
"Últimas do jogo" (the photos last added to public galleries) and "Mais vistas" (visits over 7 days, one per
browser session, in `gallery_views` per gallery and day). A photo opened in a gallery shows its delivered IPTC
caption and credit, when it was taken and its size, and has its own link (`?foto=<id>`, previewed with that photo).
- Live galleries (`live` PICKS or ALL, linked to an event): the gallery fills itself while the match is on, from
the event's picks or every ready photo that is not rejected. Photos it added leave again when they stop matching;
photos taken out by hand are kept as exclusions and never come back; photos added by hand stay. The sync runs when
someone looks (site or app, at most every 5 s per gallery); the site shows "Ao vivo", newest first, and refreshes
every 20 s (paused while a photo is open). A live gallery can be published empty, before kick-off.
- Proofing (ported from the old app's publicProofing): clients mark favourites and comment on photos. A visitor is
one browser (signed token in localStorage, sent as `x-proofing-visitor`); name and email are optional and asked
after the first heart. Comments show to others once the photographer approves them. In the app: who chose what,
the most chosen photos, CSV export, file names to copy, and "label in the catalogue" (a colour label on every
favourite, to filter, edit and deliver from the library).
- ZIP: an order's ready downloads in one archive (stored, not compressed; CRCs worked out first so every unzip
tool reads it; no ZIP64, so up to 4 GiB). Free-download galleries have "Descarregar todas": one free order with
every photo (up to 200) in the largest digital size, then the order page with the ZIP.
- Earnings (Vendas → Ganhos, `apps/api/src/shop/earnings.ts`): when an order is paid, each line owes its
photographer a share of its net (VAT-free) amount (the organization's percentage, or the member's own) and the
order owes its affiliate a commission on its net total. Earnings are written once (unique per line / per
order), held for the refund window (14 days by default), then paid out per person: a Stripe Connect transfer
from the organization's Stripe balance to the person's Express account (onboarding on Stripe's page; we keep
only the account id), or a bank transfer recorded by hand with its reference. Transfers are idempotent per
payout: refused ones release the earnings, unanswered ones stay pending and are retried. "Marcar reembolsada"
on an order cancels what it still owed; what was already paid out is settled by hand. Photographers see their
own sales, holds and payouts. Affiliates: links carry `?ref=CODE` (remembered 30 days by the site), unknown or
inactive codes are ignored.
- Notifications (the bell in the app, `apps/api/src/notifications`): a sale of your photos and what it earns
you, paid orders (admins), client comments waiting for approval (editors), payouts made to you, deliveries
that gave up (admins). Unread notices with the same key fold into one with a count (a burst of comments on
one gallery, failures on one target); read ones are dropped after 90 days. The app polls every minute and on
focus; each notice links to its page (`/shop?tab=earnings`, `/delivery`).
- Invoicing (`apps/api/src/invoicing`): with InvoiceXpress set up (Sites e pagamentos → Faturação: account, API
key sealed like the Stripe keys), every paid order gets a certified invoice-receipt: queued in `invoices` when the
order is paid, issued by the worker (create as draft with our id as `proprietary_uid`, finalize, email to the
buyer), retried with backoff (1 min to 12 h, six tries); rejected data (422) or a bad key fails at once and tells
the admins. Net unit prices per line, VAT as the account's taxes named `IVA<rate>`, reverse-charged orders at 0%
with the exemption code set in the settings (M40 by default) and the mention "IVA - autoliquidação". The invoice
number and link show on the order in the app and on the buyer's order page. Imported orders get none.
- Press accounts (Vendas → Imprensa, `apps/api/src/shop/press.ts`): a newspaper, agency or club gets an account
(email and a generated password, shown once). On the site, Imprensa signs it in (a signed token, 30 days, kept in
the browser); its orders skip the payment, use its billing details and discount, and are paid at once on account
(downloads render straight away, photographers' shares are recorded). After each month ends the worker queues
one invoice per account with everything it bought (InvoiceXpress `invoices`, due in 30 days, a line per item
with the order number); those orders get no invoice of their own. A closed account's token stops working.
- Download limits: each bought file can be downloaded `maxDownloads` times (organization setting, 20 by default,
0: no limit), copied onto the order when it is made so a later change never takes downloads away; press orders
have none. The order page shows what is left; the ZIP counts as one download of each file.
- Photo packages (`bundles`, Vendas → Produtos → Pacotes; the old storefront's "pacotes"): N photos, or the whole
gallery (0), of one digital product for one price, for one gallery or all of them. Buyers just fill the cart:
`applyBundles` (contracts) finds the cheapest mix of single photos and packages per product, and the whole
gallery when every ready photo is in the cart; the site prices the cart with it and the API charges with it, so
they agree. A package's price is spread over its photos, so order lines, VAT, shares and refunds work as before
(the line reads "<product> · <package>"); a press discount applies on top. The gallery page lists the packages
and has "Comprar todas" for the whole-gallery one. Orders take up to 1000 lines for that.
- Kiosk (Impressão → Quiosque; `/e/<slug>/quiosque?k=<secret>` on the events site): a tablet at the event shows
the photographer's photos big and the front camera as a photobooth (3-2-1, then the picture), takes the guest's
name and copies (1-5) and sends the print to the queue. Only the hash of the link's secret is kept; a new link
retires the old one. The tablet is shared and staffed, so the per-guest limit doesn't apply; on a paid event the
kiosk's prints wait for approval (paid at the counter) instead of going through Stripe. Full screen, screen kept
on, back to the start after a minute without a touch.
- Faces on edited photos: boxes are stored in the original frame; `GET /v1/photos/:id/faces` also gives each box in
the rendered preview's frame (`inPreview`, the crop and straighten of the snapshot it was rendered from; null when
cropped out), which is what the loupe draws (`apps/api/src/faces/frame.ts`).
- PATCH bodies are parsed with `patchOf(schema)` (contracts): zod's `.partial()` keeps defaults, which made a
title change turn a private gallery public; galleries, sites and print events use it.
- Products per organization: JPEG downloads (long edge, 0 = original) and prints (size, lead days); prices are
gross. Orders keep a copy of names and prices. VAT: seller's rate inside the price; EU businesses with a
VIES-valid number from another member state get reverse charge (net price). OSS for EU consumers is not applied.
- Payments: the organization's own Stripe account (keys sealed with AES-GCM), hosted Checkout with the methods
switched on in its dashboard (cards; Multibanco and MB WAY where Stripe offers them). Webhooks
(`/v1/public/stripe/:orgId/webhook`, signature checked over the raw body) mark orders paid, including late
Multibanco payments. Free-download galleries skip payment for digital files.
- Fulfilment: the worker renders each bought JPEG from the original with the photo's edit and full IPTC at the
product's size (never enlarged), then emails the buyer the order link (SMTP). Downloads are counted (20 max).
Prints are marked shipped in the app; the order closes when everything is done.
## On-site printing
- Print events (Impressão in the app) have a QR code to `events.photoreport.pt/e/<slug>` (apps/site). Guests send
a photo from the phone or pick one of the photographer's (a gallery linked to the event); each becomes a
print-ready JPEG at 300 dpi in the photo's orientation (cropped around what matters), with an optional border
and a band with the event's text. Optional approval per photo and a limit per guest (a random key per phone).
- Stations run `apps/print-agent` (CUPS) and pair with a one-time code (15 minutes) for a bearer token stored
hashed. Every 15 s they report their printers; they claim the oldest queued job for a printer that has the
job's paper loaded (operators tick sizes per printer), print with `lp`, and report the result (three tries,
then failed; reprint from the app). The app's queue and the guest's page update live.
## Faces
Only for organizations whose owner switched it on with a recorded legal basis (biometric data, GDPR art. 9).
Each photo that arrives is queued (`photos.faces_status`). Photographs that have never been read go first
(`photos.faces_pass` still 0): the last 30 days (when the photo was taken, or the game's date when the camera
wrote none), newest game first, and only then the older archive, also newest game first. A second reading, so the
season squad can name a photograph already analysed, waits until that unread queue is empty. It is queued thirty
thousand at a time per worker start (`photos.faces_pass`), newest first. A confirmed face keeps its group, and the new reading rejoins it when it is still the same person. The worker starts a few face processes and adds more while the CPU stays under
about 99%, stopping sooner when memory (the model) runs short. Asking to analyse one event still puts it first. A photo whose analysis failed is
queued again a few at a time, after it has been quiet for six hours, recent games first. Confirming a face
improves who that person is (their face is the mean of the faces confirmed, plus the official headshot): the
detector that finds a face in the photo is not retrained. The worker runs `workers/faces` on the original:
YuNet finds faces, each is aligned to the ArcFace template and embedded by AuraFace (512 numbers, Apache-2.0;
model files pinned and checked by SHA-256, `infra/faces/download-models.sh`). Faces of the same person within an
event are grouped (cosine to the group's mean, threshold per model). An editor names a group once (the
"Caras" view of the library, or a suggestion from people confirmed in earlier events), and every photo with a
face in it gets the name in Players, which goes to IPTC Title and Persons Shown; photos that arrive later and
join the group are named on arrival. Suggestions never name photos on their own. Groups can be merged or ignored
(public, staff). Measured locally on 2 cores: about 1 s per photo with AuraFace.
Shirt numbers come from our own model, because general OCR doesn't read shirts. Under each confirmed face two
crops become training samples, labelled with the squad's number: the chest (handball kits carry the front number
there) and waist to mid-thigh (football: Liga Portugal 2026/27 shirts have no chest number, the front number is on
one leg of the shorts, as a sample of 14 clubs showed). The worker reads both and keeps the more confident reading. People check these samples in
"Números das camisolas". `workers/ml/jersey` trains a ResNet18 on the checked samples (on a Mac with MPS) and
exports it to ONNX.
With `JERSEY_MODEL_DIR` set, the worker reads the number of every clear face through onnxruntime-node, on the
CPU. A group's number is the one more than half of its clear readings agree on; it is shown as `#10` on the
group.
Face and number are used together:
- **Face + number + kit colour** of that player's team is the strongest guess. **Face + number** is next.
A face that already matches is never replaced because a number was also read — that dropped players whose face
was right and whose shorts number was visible. The number only raises the score when it is the same player's.
- **Face sure, no number read:** the face's suggestion. Faces come from confirmed groups and from the official
headshots (Liga, UEFA, FPA licence photos) that squads bring as reference photos, so even a first match has faces to go by.
- **No sure face, clear number:** the squad player who wears it, but only if the kit colour matches a teammate already
trusted. The other team's kit never takes the name. Club crests are not a separate model: chest sponsors are not the
badge, and the shirt colour already separates two kits.
- Two face groups that do not look like the same person never both keep that name: the stronger guess wins.
- **Both teams have that number:** the kit colour decides. Each face keeps the median colour of the middle of its
chest; each team's colour is the median of its players already confirmed in the event, or suggested with face and
shirt agreeing (score 0.85 and up), goalkeepers left out — a goalkeeper's shirt is a third colour and never
teaches the team's kit, and it does not rule him out when it fails to match either outfield shirt.
Comparison is by hue first, so the same shirt in sun and in shade still matches; white and black still differ.
The group goes to the team whose colour is clearly closer, never when the two kits are alike, the group's
colour sits in between, or it is far from both (the goalkeeper, a referee).
Suggestions still never name anyone on their own.
A number holds within a season and competition, not for life (`apps/api/src/faces/numbers.ts`): a player may
wear another one five seasons later, in a cup with its own numbering, or for the national team. Wherever a
person's number is used (the comparisons above, the squad suggestion, the training samples' labels) it is the
number for that event's context:
- **Season:** the official match's, or the event's day (July to June). The squad read is that season's, so an
old game gets the number worn then, even for players who have since left.
- **A game whose two clubs are known** (teams already stored, or the home and away names matching one team of
that sport each): only that season's squad — players and coaches — and the referees of the fixture, when they
already have a face. A player who has since moved is included when that season's list has them (the same
federation id, or the same birth date and full name), with the shirt number of that season. A face none of
them explains stays unnamed. It is never someone who was not at either club that season.
A photograph of one team lined up (the faces across the frame, in one to three rows) is read as a set:
each clear shirt number belongs to one player of the squad the numbers fit, and that face is suggested
as that player. Confirming the photograph is what teaches the other photographs of the game.
A session, a training day or a studio day of a national team (FPA: SNAF, SNAM, M18, and the same team under
its long name) uses that team only: people already confirmed there this season, and the athletes the session
folders name. There is no match number. A gala or a press day names no team: the face alone, against everyone
of that sport, and only a clearly stronger match. The shirt, when it is read, stays with those two clubs.
Then what the shirts clearly read (three or more clear readings) in the person's confirmed photos of the same
season and competition.
- An editor of the folder can give a face another name. The list shows the official face, the club and the shirt
number.
- **Not linked (a cup, a friendly, a tournament):** those readings in that competition first, then the season's
squad.
- **National team** (a country on either side, or a seleção folder): club squads and club numbers never apply.
The women's senior team, the men's, and an age group are different lists. A photo is named from people already
confirmed on that same team this season, **and** from the national plantel linked on the event (`SNAM` /
`SNAF` / `SUI-M` / `M19`, …) when those `sports_players` have faces — FPA licence photos (CIPA), including athletes who
play abroad, or an EHF club-sheet headshot already stored for the same person. Without a plantel or prior
confirmations the roster stays open (null), not an empty list. The shirt number is the one read on that team's
games, and an older Portugal game with no team in the folder still shares what was read for Portugal that season.
- **The number typed on the person** has no season: used only in the current season and never for a national
team. Training samples never take the model's own readings as labels.
Next: back-of-shirt numbers. These are players with no face visible, and they need a box detector trained on
hand-drawn boxes.
## Sports data (squads, fixtures, player codes)
`apps/api/src/sports` rebuilds the old app's code-replacement system. The worker reads public federation data
every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisation:
- **Liga Portugal** (`ligaportugal.pt/api/v1`): Betclic, Meu Super and Allianz Cup stay on the six-hour refresh.
Gives teams, squads (numbers, positions, official headshots) and the season's fixtures. The calendar does not
name the ground: `team/info` does (the stadium). The town is that page's city when Liga fills it, otherwise the
town written in the club's own name or in a stadium that names it ("Municipal de Amarante", "Cidade de Coimbra").
A person's name in the stadium ("Dr. Machado de Matos") is not a town. Stadium and town are stored apart
(`venue` and `city`) on the club and on the match, and choosing the match fills both on the event. The same
split is what UEFA (`stadium.city`) and the EHF (`cityName`) already publish. Handball keeps the hall from the
agenda (`LOCAL`, the same line as Recinto on the match sheet). The town is the home club's `CLUBE_LOCALIDADE`
(`getClube`: Oriental → Lisboa, Albicastrense → Castelo Branco). The federation's own card is not a club, so a
seleção does not take Lisboa from F.A.P. A club that leaves the locality blank stays without a city. On start the worker reads
every season the federation still lists, under the name that league had that year (Liga NOS, Liga Sagres, LigaPro),
so a past season keeps the squad and the shirt numbers of that year. When that read finishes, the newest
photographs already analysed are queued again for faces (thirty thousand per start). The archive's people list
is everyone; a season narrows it to the people in that season's photographs.
- **FPA** (`ws.fpa.pt` agenda): every national handball competition (PO01, PO09, PO20...), with teams and
fixtures. Squads of the senior national leagues and cups (PO01, PO01A, PO09, PO09A, PO20, PO23) come from the
match reports (`si.fpa.pt` "Boletim do Jogo", windows-1252 HTML): each player with shirt number and licence
number (CIPA), and the bench officials by their card letter (Oficial A-F, kept as the "number" so the shirt-number
reader can name them; their CIPA comes from the match page's team panes, as the report gives their coaching grade
there). Referees and table officials come with full name and CIPA too, and are kept as one more FPA "team"
(`ARBITRAGEM`), so the names the match page gives before a game find their licence, photo and full name. A team without a squad starts from its club's last three reports (club page → season and
level ids → `getJogosClubeEpocaEscalao`), eight teams per refresh; after that each report of a game played is read
once (reports read before licence numbers were kept are read again, 40 per refresh). Referees and table officials
come from the report, or from the match page (named some days before) for games with an event; both become people.
Licence photos come from the club register (`ws.fpa.pt` `getCipClubeEpoca/{club}/{epoch}`: every associate the
federation lists for that club and season — athletes, coaches, officials, referees — with `CIP_NUMERO` and
`URL_FOTO`), so face search covers the whole FPA register, not only people named on a match sheet. A few clubs
per refresh; again after a week. Event sync still fills gaps via `portal.fpa.pt/associado/<CIPA>/` when a
boletim names someone the register has not yet brought. With biometrics on, photos become reference faces.
Names are first + last name ("Rui Lopes"), the full name kept beside it.
The sports worker (`SportsWorker`, about every 10 minutes, and national sheets at least hourly) writes
fixtures into `sports_fixtures` before anyone opens the form. Choosing a game reads that row: teams, venue,
kick-off and, once the sheet is in, the plantel. Men's EHF Euro Cup matches come from the same pass.
Each FPA refresh also upserts senior national sides (`SNAM`, `SNAF`, `SUI-M`, …) and the under-19 men's
sides (`M19`, `ESP-M19`), and merges the Men's EHF EURO Cup match sheets from `www.eurohandball.com`
(`GetStandingMatches` / `GetMatchDetails` — same shape as club sheets, with shirt numbers and `res.ehf.eu`
headshots for the nominated 16). Portuguese CIPAs from the FPA call-up stay as `externalId` when the name
matches; photo/number come from the sheet. Youth camps (sub-17, sub-19, sub-20, men or women) come from
recent posts on `portal.fpa.pt`: the call-up PDF (CIPA, no shirt number from the list order) and the
"Jogos Particulares" calendar. A sheet with a real squad replaces that age group; a post the site does not
return leaves the plantel we already have. The November 2026 M19 list and the Spain name list are only the
seed when that team is still empty. Those friendlies are fixtures (`m19-por-esp-20261105`,
`m19-esp-por-20261107`) so picking the game links that plantel, not the senior one. A folder or title that
says sub-19 / M19 (not "Encontro Nacional") is that age group. Cloud delivery for these games is the
destination "Cloud M19" (`/FPA/Fotos/{season}/Seleções Nacionais/M19/…`), created from the organisation's
existing FPA Nextcloud account and never sent on arrival. FPA licence or an older EHF club photo fills
gaps. People and reference faces are created when the event syncs those teams (`POST …/squads/sync`), not on
every sports refresh. Example match: Portugal–Switzerland `202811130101002`.
- **FPF** (`resultados.fpf.pt`, HTML): competitions are added by link. It gives teams and fixtures, and squads
from each match sheet, read from 1 h before to 2 h after kick-off.
- **EHF** (the JSON `ehfcl`, `ehfel` and `ehfec.eurohandball.com` read; not a documented API): men's and women's
Champions League, European League and European Cup. Fixtures with venue, and squads from the match sheet once
it is published: the nominated players (number, position, photo) and the bench staff (letters A, B, …; the sheet
does not say which letter is the coach). A gallery filed under an EHF competition is matched to that game.
Beach handball stays a folder. Asked sparingly and cached.
- **UEFA** (`match.uefa.com/v5`, the JSON uefa.com itself reads; not a documented API): Champions League, Europa
League, Conference League, Women's Champions League and Futsal Champions League. Fixtures with venue and the
referee team; squads (numbers, positions, headshots, coaches) built from the match sheets of matches already
played, and the match's own sheet from 1 h before kick-off. On an event, the referee team on the pitch
(referee, assistants, fourth official) becomes people of club "Arbitragem". Asked sparingly and cached: if it
changes, events still work with names typed by hand.
What organisations do with it:
- **Code list:** generated codes go into the organisation's code list. They live in a block at the top, and the
editor's own lines keep priority. The block is regenerated when squads change. Code = team prefix + number,
with the same prefixes and templates as the old app.
- **Events from fixtures:** an event created from a fixture keeps `fixtureId` and both teams.
- **Generic events** (press conferences, galas, presentations; "Evento genérico" in the form): `home` holds the
name and `away` is empty. Nothing is guessed for the caption: the default IPTC template (`GENERAL_TEMPLATE`)
has no caption, headline or event, and the form's "Legenda" fills caption and headline when typed. `{event}` is
the name alone, and a match template left on such an event drops the dangling "x".
- **Agenda:** each person can connect their own calendar by its secret iCal address (Google, iCloud, Outlook;
`webcal://` is read as https). It is sealed with the secret box in `user_preferences.calendar_url`, fetched only
from public https hosts (private, loopback and link-local addresses refused, redirects checked again, 5 MB, 10 s)
and cached 5 minutes. For a generic event the form lists the day's entries; picking one fills name, venue, city
and time and suggests a caption ("Title, Venue, City.") to edit. Repeating entries show their first date only.
- **People from squads:** one person per human. A later season at another club updates the club and the shirt
number; an older season does not. The number shown on a photo is still that season's. With biometrics on, the
Liga headshot becomes the reference photo, and number suggestions for faces use the event's squads.
## Working without a network (desktop app)
A match does not stop when the venue's internet does. The desktop app keeps working and catches up on its own:
- **Opens offline.** The interface is on disk (`apps/desktop/src-tauri/src/ui.rs`); the person last signed in carries
on (`auth.tsx`), the session is checked again when the server answers.
- **Library and Revelar from cache** (`apps/app/src/offline/cache.ts`, IndexedDB): events, each folder's photos, the
edit state of photos opened in Revelar, thumbnails and previews already seen.
- **Photos arriving offline show at once** (`offline/local.ts`): the local FTP feed makes a preview here and files the
photo in the event of its capture time (the same rule as the server), with id `local:<sha256>`. It can be culled,
named and edited before it is uploaded; the server's copy replaces it when the upload is done, keeping what was done.
- **Changes wait, in order** (`offline/queue.ts`, localStorage): culling, players, IPTC and "send to" made without a
network are kept and sent when the server answers (every 10 s and on `online`); changes to a photo not uploaded yet
wait for it. Develop edits use the per-photo outbox (`develop/session.ts`) and follow the photo to its server id.
- **Uploads wait instead of failing**: the queue pauses on a network error and resumes when the connection is back.
- The autopilot runs on the server when the photo arrives, and never over a person's edit (made offline first).
## Library realtime
Socket.io on the API (`/v1/realtime`, WebSocket only, access token in the handshake, one room per
organization). Every message goes through PostgreSQL `LISTEN/NOTIFY` (`photoreport_realtime`): the worker and
every API process publish, every API process delivers to its own sockets. No Redis/Valkey and no sticky
sessions needed. Messages: `photo.added`, `photo.updated` (culling, players), `delivery.updated`.
## Client delivery (Nextcloud, SFTP, FTP, Dropbox, ZeroZero, a folder on a computer)
PhotoReport storage is the source of truth; Nextcloud receives organised copies. Any client organization can have one or
more destinations on any Nextcloud instance, each with its own folder and file-name templates (variables
from `packages/metadata`). Default delivery: final edited JPEG, 4000 px long edge, maximum quality.
Implemented (`apps/api/src/delivery`): editors send picks to a target; each photo becomes a queue item with
its `{n}` fixed at that moment (capture order, never reused). The worker renders it (oriented, 4000 px,
JPEG 100 4:4:4, camera EXIF and ICC kept, IPTC written to IIM and XMP with ExifTool), creates the folders
(WebDAV MKCOL) and uploads (PUT), up to 4 at a time, retrying network and server errors with back-off
(5 attempts); authentication and template errors fail at once. App passwords are stored encrypted
(AES-256-GCM, `DELIVERY_SECRET_KEY`). Editors can create a read-only public link to an event folder (OCS).
Large files may later need WebDAV chunked upload.
The same queue also delivers to SFTP, FTP/FTPS and Dropbox (`delivery/transports.ts`):
- **SFTP** (A Bola: `transfer.ringier.ch`, folder `/{event}/`, originals at full size). Takes a password or a
private key. The host key is remembered on the first connection and checked on every one after; a changed
key fails the delivery until an admin resets it.
- **FTP:** `ftps://` for explicit TLS.
- **Dropbox:** app key plus refresh token, or a long-lived access token.
- **A folder on a computer** (`LOCAL`): the worker renders the file as for any destination and keeps it (status
`WAITING`, `<org>/deliveries/<item>.jpg`); the desktop app of that computer (its id is the target's user) takes it
(`/deliveries/local/claim`, `/local-file`, `/local-result`, every 10 s while open) and saves it under the folder,
with the templates' subfolders and name. It only writes inside folders chosen there with the system's folder
picker (`src-tauri/src/deliver.rs`), never a path a page passes. For testing a destination's rules, or keeping
the finished files to choose from later.
- **A local copy of any other export** (`local_folder`, not on a LOCAL target): the FTP, SFTP, Nextcloud, Dropbox
or ZeroZero send is unchanged. With the option on, the same file (that destination's size, name and IPTC) is also
saved by the desktop app under the chosen folder, in `{iptcdate} - {event} - {destination}`
(`/Users/cyclop/Desktop/2026/20261018 - Águas Santas Milaneza x Sporting CP - Record/`). The subfolder template is
editable; `{destination}` is the destination's name. A hidden LOCAL target holds the copies and is not listed.
- **Originals** (`delivery_targets.originals`, any kind): the original as it arrived, byte for byte in its image
(no resizing, no recompression, the camera's EXIF and profile kept), with the IPTC written by exiftool and the
name from the templates, like Photo Mechanic's Live Ingest destination (`{iptcdate} - {event}`,
`PS_{event}_{timesort}`). With **every arrival** (`on_arrival`), each photo that is ready in an event (FTP, the
desktop app, uploads; not the archive's) is queued there on its own (`IngestService.arrivals` →
`DeliveryService.queueArrival`). Together on a `LOCAL` destination: one's own backup of the originals in a
folder on the computer (where e.g. Amazon Photos backs it up).
- **Edited again after delivery** (`delivery_items.delivered_seq`, `replaces_path`): a delivered photo whose edits
change later (a crop put right after the autopilot sent it) is sent again to every destination it went to, once
its edits have paused for a minute (`DeliveryService.queueEdited`, checked every half minute with the queue). The
same item goes again with the same number, so the same name: a file is replaced; on ZeroZero (which keeps every
upload) the new image goes up and the previous one is taken back (`DELETE /api/images/<id>`). Originals' backups
carry no edits and are not sent again. Deliveries made before this count as showing the photo as it is.
- **The central FTP as a relay** (`arrival_logins`, `untouched`): an every-arrival `LOCAL` destination can take only
some FTP logins' photos, and with `untouched` the original goes byte for byte as the camera sent it (no metadata
written, the camera's name with `{originalName}`), into the folder a local Photo Mechanic Live Ingest watches. The
photo still enters PhotoReport as any FTP arrival (event, IPTC, deliveries); the photographer's computer gets it as
if the camera had sent to the FTP there.
- **Importing destinations** (desktop, "Importar…" in Destinos): Photo Mechanic's upload accounts
(`fileupload/templates/builtin/<kind>-conn.yml`) and templates (`fileupload/snapshot/builtin/<kind>/*.snap`), and
FileZilla's `sitemanager.xml`, read by the desktop app from their fixed places. The desktop takes the saved
passwords out of those texts and hands them over separately when they are readable (plain, or base64 that decodes
to text; FileZilla's `encoding="crypt"` and binary Photo Mechanic blobs are not); `library/importSources.ts` turns
the rest into destinations (server, user, folder, size, quality, rename), and an encrypted password is typed by
the person.
- **Originals still on the photographer's computer** (the desktop's local FTP sends a 2048 px preview unless told
to send originals): a delivery never renders that preview. It asks the desktop app for the original
(`original.requested`) and waits, re-asking every minute, up to 72 h, without counting attempts. The desktop
sends the file it recorded for that fingerprint; if another app (Photo Mechanic) has written captions into it
since, it goes to `POST /v1/photos/:id/original`, accepted when it has the photo's pixel size; the photo keeps its
fingerprint and library metadata.
- **ZeroZero** (`fotos.zerozero.pt`, `delivery/zerozero.ts`): the photographer's zerozero.pt account. The server
signs in through zerozero.pt's OAuth (`/api/auth/login` → `oauth.php` → `ax_login.php` → `/api/auth/callback`,
cookies kept in a small jar), and uploads with tus to `/api/upload?match_id=<game>` with the file name and the
author (`artist`: the photographer's name from the IPTC creator). The "folder" is the game: chosen for the
event by pasting the game's link (kept in `events.zerozero_game_id`), or found among the desk's upcoming games
by both teams and kick-off within 3 hours. The delivered item's remote path is `<game>/<image id>`
(`DELETE /api/images/<id>` takes it back).
Each target also has Photo Mechanic's uploader output options: fit-in-box size, JPEG quality, output
sharpening, ppi, keep or drop the camera EXIF, and conversion to sRGB. Targets can be duplicated (same server and
credentials, another name and folder).
**Cull marks on delivery.** A pick (⚑), reject (✕), stars and colour label are written into the delivered JPEG
for Lightroom Classic ≥ 13.2 Attribute filters: `XMP-xmpDM:Pick` (1 / 0 / −1) + `Good`, `XMP-xmp:Rating`,
`XMP-xmp:Label`, plus digiKam `PickLabel` and IPTC Urgency for Photo Mechanic. When the desktop app is open it
watches local delivery folders; a Reject written back by Lightroom (XMP auto-write) sets the photo to REJECT
and retracts any delivery of that file. A colour Photo Mechanic paints on a local original, or on a delivered
file, is copied back (`photomechanic:ColorClass`: 1 red, 3 yellow, 4 green, 5 blue, 7 purple).
**Colour ↔ destination.** A delivery target may own one library colour. Painting that colour queues the photo
only there; enqueue skips `color_mismatch` otherwise. The library colour is how you see what went where.
**Autopilot exports.** An ordered list of destinations (`deliverTargetIds`) takes rank 1…N of each burst (one
file per destination). Melhores keeps a 5 s gap only within the same destination. Local FTP logins may map to
an org member so a second photographer on this Mac is attributed correctly.
**Photo Mechanic compatibility (templates and IPTC).** Every template (IPTC pad, folders, file names, rename on
arrival) takes every variable of Photo Mechanic's list, under its names and short names, in any case
(`packages/metadata/src/pmvars.ts`), and its modifiers: substrings `{var:index,count}` (negative index from the
end, negative count trims the end), `lc`/`UC`/`PC`, and `tr:find/repl` (`{caption:0:lc:tr: /_}`). So a Cofina path
such as `/fotografia/{iptcyear4}.{iptcmonth0}.{iptcday0} {event}` or Live Ingest's `{iptcdate} - {event}` /
`PS_{event}_{timesort}` work as typed there. As in Photo Mechanic, the IPTC variables (`{event}`, `{caption}`,
`{headline}`, `{city}`...) are the photo's IPTC: in folders and names, the pad applied to it; inside the pad, the
IPTC the file arrived with. `{event}`, `{city}` and `{location}` fall back to the event's ("Home x Away", its city,
its venue); `{date}` and the IPTC dates are the capture's (the event's day without a capture time). Camera
variables come from the photo's columns plus `photos.exif` (exposure compensation, flash, metering, program, white
balance, 35 mm focal length, lens range, firmware, owner, artist, GPS), read at ingest; photos from before are read
from the file at delivery. Variables PhotoReport has no data for (Getty fields, Nikon Picture Control, ICC
primaries, client/user extras, shutter count) exist and are empty, as in Photo Mechanic. The IPTC pad has every
Photo Mechanic field, written to the same IIM and XMP tags (contact info, state, country and code, location taken,
instructions, transmission reference, category, urgency, edit status, genre, scene, subject code, usage terms,
copyright URL, image supplier, model release), and the same fields are read from incoming files. PhotoReport's own
variables (`{home}`, `{away}`, `{competition}`, `{season}`, `{round}`, `{players}`, `{photographer}`, `{n}`...)
stay.
Rename on arrival (Live Ingest "Rename as"): photos arriving by FTP or the desktop app get a name from a
template. The template is the organisation's, or the FTP login's own (`""` keeps camera names). Names are made
unique within the event (`_2`), and are redone when the photo moves to another event (a template that uses the
event waits for one). The camera name is kept in `originalName`; deliveries use the new name as
`{originalName}`.
Files with the same name are replaced (as in Photo Mechanic). Public links exist only for Nextcloud and
Dropbox. The old app also mirrored raw uploads to Dropbox/FTP; here every delivery is the edited, captioned
JPEG.
| Instance | Client | Folders today | Files |
| --- | --- | --- | --- |
| cloud.photoreport.pt | FPA | `/FPA/Fotos/2026_2027/Competições Nacionais/PO01 - Campeonato Betclic/20260923 - VSC x AAAS/` | `PS_<Home> x <Away>_<n>.jpg` |
| liga.photoreport.pt | Liga Portugal | `/LPBetclic 25-26/Jornada 1/1. Casa Pia x Sporting/`; institutional events at root | camera name (`JMA27728.jpg`) |
Archive import: folder names changed across seasons (`LPbwin - 22-23`, `LPBetclic 2023-24`,
`LPBetclic - 24-25`, `LPBetclic 25-26`), so the importer proposes a folder -> competition/match mapping that
an editor confirms before import.
## Editor scope
JPEG first: most event and match photographers shoot JPEG for speed, so JPEG must be perfect before RAW.
Default editor modules: Crop (with straighten and aspect presets) and Basic (white balance, exposure,
contrast, highlights, shadows, whites, blacks, texture, clarity, dehaze, vibrance, saturation). Every other
LightCraft module (curves, colour mixer, grading, masks, detail, optics...) is available but off by default;
each user chooses which panels to show, and the choice syncs across their devices.
The crop tool behaves like Lightroom's: the photo turns under an upright crop (the engine renders the whole frame
unturned and the loupe shows the angle), corners and edges resize (Shift keeps the shape, Alt about the centre),
inside moves, outside rotates, Ctrl/Cmd + drag draws a line to level along, X swaps portrait/landscape, A locks the
aspect, O / Shift+O the guides, Enter done, Esc cancel, Ctrl/Cmd+Alt+R reset. Its geometry is a port of
`lightcraft-geom` (`crop.rs`, `crop_drag.rs`) in `apps/app/src/develop/crop.ts`, so a drag needs no engine round
trip; the stored crop stays LightCraft's (`crop.set`: rect in the straightened frame, angle, aspect).
## RAW support (secondary; LightCraft rev pinned in Cargo.toml, checked 2026-10-11)
- Canon EOS R1, R3 (CR3): unverified; lossless and single-tile C-RAW decode, other CRX variants fall back to
the embedded preview. No measured Canon colour calibration yet.
- Nikon Z 9, Z 8: NEF decodes except High Efficiency (HE / HE*), which is preview-only.
- Sony A9 / A9 II / A9 III: verified.
Action (low priority): collect real files from each body, add them to our reference set, contribute samples upstream.
## Status
Phase 0 code is in place and verified: accounts, organizations and roles, web login (httpOnly refresh cookie,
rotation with reuse detection), desktop login through the browser (device authorization) with the keychain,
synced editor-panel preferences, deploy receiver and script. Remaining for phase 0: create the `next`
containers and webhooks (docs/DEPLOY.md), and macOS/Windows runners for desktop installers.
Phase 1 so far (verified end to end locally: FTP drop -> live grid -> keyboard culling -> players by code ->
IPTC preview -> delivery into the FPA folder layout): events with agenda and IPTC template, FTP ingest and
routing, previews, the library (Lightroom-style grid and loupe, P/X/U, stars, colour labels, filters, live
updates), code replacements, IPTC with the fields of the current Photo Mechanic pad (`packages/metadata`),
Nextcloud delivery queue and share links, the per-event IPTC pad (same fields and order as Photo Mechanic),
and admin screens for delivery targets (FPA and Liga presets) and FTP logins, uploads from the browser
(drag and drop or Importar, 4 in parallel with progress, same pipeline as FTP), and the IPTC already in
incoming files (XMP first; IIM written by Lightroom/Photo Mechanic on the Mac without a charset flag is read as
Mac Roman), shown next to ours. SFTPGo authenticates cameras against the API (external auth hook; passwords made in the app). Browser and desktop uploads go in 4 MB chunks and resume after a dropped connection or a reload. Still open in phase 1: a real match
run on the `next` containers (the phase gate).
## Phases (gate to pass)
0. Foundation: monorepo, CI, `next` containers, accounts, organizations, tokens (login on web and desktop).
1. Ingest + library: SFTPGo/tus, routing, previews, IPTC, code replacements, culling, Nextcloud delivery
(a real match arrives captioned and delivered with no manual step).
2. Synced editor (done: WASM and native engine, op log, live sync, offline outbox, render worker, edited
deliveries, crop with aspect presets and straighten, Basic and optional modules, copy/paste settings).
3. Galleries and sales (done: both storefront skins, public/unlisted/private galleries, watermarks, cart,
Stripe Checkout and webhooks, VIES reverse charge, rendered downloads with IPTC, order emails, print
fulfilment, admin in the app, live galleries, client proofing, ZIP downloads, photographer shares and affiliates with payouts
(Stripe Connect or bank), import of the old storefront (galleries, paid orders, affiliates),
invoices through InvoiceXpress, press accounts on credit with a monthly invoice, photo packages, download
limits, FTP packages with quotas).
4. Events and printing (done: QR guest page, print layout with band and border, approval and limits, queue
in the app, print agent with CUPS and pairing, paper per printer, paid prints through Stripe, kiosk mode on a
tablet with photobooth capture, Windows agent (spooler through PowerShell). Open: the Windows agent on real
hardware, a real event printed).
5. Player identification: faces (done: detect, group, confirm, propagate, suggest across events), jersey
numbers with squads, global search (parity with old projects validated), search by photo (done: in the
library, a photo's face against every event's face groups and the named people, `POST
/v1/orgs/:orgId/faces/lookup`; on the sites, "Encontra-te" finds a visitor's face in one gallery, `POST
/v1/public/galleries/:slug/find`; in the archive, editors on the cloud with the option on search the whole
archive they can see, `POST /v1/archive/:source/find`). Only with biometrics on; the search photo is read in
memory and never kept. On phones, "Tirar foto" uses the front camera in the page (`getUserMedia` → JPEG),
not `<input capture>` (iOS often hands HEIC the API cannot read). Gallery picks still convert to JPEG in
the browser before upload. The API runs its own face engine for this, started on the first search and stopped
after 10 idle minutes.
6. Cutover: final import, redirects, old projects read-only, then switched off.
## Deploy
Push to `main` -> Gitea webhook per container -> pull, build, migrate, reload, health check, auto-rollback.
Details: `docs/DEPLOY.md`.
## Infrastructure (`next`)
| Container | Services | Domain |
| --- | --- | --- |
| pr-api | `apps/api` + Socket.io (2 instances) | api.next.photoreport.pt |
| pr-ingest | SFTPGo + `photoreport-worker` (ingest + delivery) | ftp.next.photoreport.pt (DNS-only) |
| pr-app | `apps/app` static | app.next.photoreport.pt |
| pr-site | `apps/site` | next.photoreport.pt + brand domains |
| pr-db | PostgreSQL 17 + pgvector, pgBackRest | internal |
| pr-storage | `/srv/photoreport-data` bind mount shared by pr-api and pr-ingest (Garage later) | internal |
| pr-workers | `workers/media` + `workers/render` | internal |
| pr-ml | `workers/ml` | internal |