Ports the parts of #92 not covered by #93 and #94: - coalesce permanent index failures into a single aggregated warn (noteIndexFailure / flushIndexFailures), flushed on each worker poll and on stop; failures with attempts left and no-video sources log at info - classify sharp metadata errors and ingest failures on damaged images as corrupt_source - count corrupt_source / no_video_stream as failedCorrupt in the cloud counts, shown in the Arquivo page with PT-PT error labels - import the sharp Metadata type explicitly (TS2503) - unit tests for the aggregation, transient statuses and the 502 retry Co-authored-by: José Alves <[email protected]>
252 lines
21 KiB
Markdown
252 lines
21 KiB
Markdown
# Archive (Arquivo)
|
|
|
|
Photos that live on a Nextcloud (the FPA archive on cloud.photoreport.pt, the Liga's cloud) indexed into the
|
|
library: search by game, team and player, faces, galleries. The originals stay on the cloud; the library keeps a
|
|
2048 px preview (with the file's metadata) and a link back.
|
|
|
|
## Connecting a cloud
|
|
|
|
App → Arquivo → "Ligar uma cloud": name, Nextcloud address, folder (from the account's root, e.g. `/FPA/Fotos`).
|
|
The API starts Nextcloud's **login flow v2** (`POST {base}/index.php/login/v2`); the person opens the returned
|
|
page, signs in to the cloud and authorises. The app polls `GET /v1/cloud-sources/:id`, which polls the cloud; the
|
|
app password it receives is sealed with `DELIVERY_SECRET_KEY` (`cloud_sources.secret_enc`). The account password
|
|
never reaches PhotoReport. A revoked app password puts the source back to LOGIN ("Autorizar de novo").
|
|
|
|
## Walking and indexing (worker)
|
|
|
|
- `ArchiveWorker` (apps/api/src/archive/service.ts) walks each source every 6 h (or on "Analisar agora"):
|
|
WebDAV `PROPFIND depth 1` per folder, with Nextcloud's `oc:fileid` and etags. A folder whose etag has not
|
|
changed is not read again (etags change up the tree), so a re-walk of an unchanged archive is one request.
|
|
- Folders are keyed by file id (renames and moves keep their match). Images (`.jpg`) become `cloud_files`
|
|
(PENDING); removed ones and removed sub-folders are dropped (the photos stay in the library).
|
|
- Indexing (as many at once as the container's CPUs and memory allow, fewer while live work keeps it busy; see
|
|
`lib/capacity.ts`), newest season first: download to a temp file, sha256, 2048 px
|
|
preview with metadata, then the normal ingest as source `CLOUD` (`originalStored = false`, no autopilot, no
|
|
rename). The same picture already in the library is linked, not duplicated. Faces run as for any photo.
|
|
- Each claim is shared between the clouds with pending images, so a big newer archive (Liga) never starves
|
|
another (FPA); inside a cloud, newest season first.
|
|
- WebDAV through Nextcloud's PHP is the slow part of a big first import (the CPUs sit idle). With the cloud's
|
|
data folder mounted read-only on the worker, `ARCHIVE_LOCAL_DIRS` reads the files from disk instead:
|
|
`https://cloud.photoreport.pt/FPA=/mnt/nextcloud/<owner>/files/FPA` (comma-separated; the folder as the
|
|
connected account sees it = where it is on disk). A file not there, or of another size than the walk saw, is
|
|
downloaded as before; deliveries and the 100% view read from the mount too.
|
|
- The editor's 100% view (`GET /v1/photos/:id/original`) and deliveries read the original from the cloud.
|
|
|
|
## Which folders are on the site
|
|
|
|
App → Arquivo → "Pastas no site", above the galleries. Every folder starts on the site. Unchecking one hides that
|
|
folder and everything inside it, including folders the next scan finds there. Checking it again publishes them.
|
|
The public site only lists photos whose folder is still published.
|
|
|
|
## Matching galleries to games
|
|
|
|
`archive/match.ts` reads the place and name of each folder with images:
|
|
|
|
- FPA: `…/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC` → season, competition code, day, teams.
|
|
- Liga: `/LPBetclic 26-27/Jornada 5/03. Sporting CP x SC Braga` → competition, season, matchday, teams.
|
|
|
|
- Competition codes however written: `PO01`, `PO-09`, `PO_09`, `PO01_2024_25`, `PO01 - Campeonato Betclic`,
|
|
`Andebol 1`; matchdays in the name (`1ª J - FCG x VFC`, `J12 - GAIA x ALA`).
|
|
- A game's parts (`1P`, `2P`, `Aquecimento`, `7M`, `02 - Primeira Parte`, `Intervalo`, `Cerimónia`, `Analog/05510`,
|
|
a photographer's `M4 - ICONSPORT`) are the game: one event, the part shown as the gallery's section.
|
|
- A dated session (`20241118 - Sessão`, `20241229 - Estudio`): its folders are athletes (`7 - Bebiana Sabino`,
|
|
`Diogo Rema`, `tec - Renata Pereira`). One event for the session; the athlete's name goes on the photos'
|
|
players (search by player, "Atletas" on the viewer).
|
|
- National teams: codes and English names become countries in Portuguese (`SWE x POR` → Suécia x Portugal) under a
|
|
national team's folder or with Portugal on one side (so `MAR x SCP` stays Marítimo). On the teams list a country
|
|
is a seleção, apart from the clubs.
|
|
- The Betclic sigla list is one club: `SLB` and SL Benfica, `AAAS` and Águas Santas, `FCP` and `FC Porto / Sofarma`.
|
|
A code that is a club there stays the club when the letters are also a country (`BEL` Belenenses, `MAR` Marítimo).
|
|
A youth side (`SL Benfica B`, `SL BENFICA 'A'`) stays its own side.
|
|
- Not a game (a training, a day of an event): one event per occasion, named with the folder above when its own
|
|
name says little (`Encontro Nacional sub-14 - Externo · Dia 2`). A dated folder with one name
|
|
(`20241105 - Treino`) is never read as a club; `A - B` is two teams only after a date or a game's number.
|
|
|
|
Teams match by abbreviation, slug, name or close name (`sameTeam`); a game not found among the fixtures is named
|
|
with the clubs' names when its initials name exactly one known club (`SLB` → SL Benfica). Every walk reads the
|
|
galleries matched by name again (`rematch`) and puts right what is now understood better. One fixture found → the
|
|
game's **archived** event (the archive's own, with both squads: archived events stay out of the day's list and never
|
|
catch FTP photos).
|
|
|
|
The archive never adds to an event of the library (one photographed live), not even for the same official game:
|
|
a wrong match must never put photos in an event someone is working on. Safeguards, because a wrong game is worse
|
|
than none:
|
|
|
|
- Only a dated folder, or one placed in its competition, season and matchday (`LPBetclic 26-27/Jornada 5`), is
|
|
matched to an official game; a season, month or matchday alone is not (one club's month folder only when that
|
|
month's game against the club above is the only one).
|
|
- A reserve, youth or women's side in the name or the path (`B`, `Sub-23`, `Feminino`, `Juniores`, `Revelação`)
|
|
never matches the first team's game.
|
|
- Name events join only other archive events of the same day (never by the folder's date in the cloud, never an
|
|
official game's).
|
|
- Never a day still to come: fixtures not yet played are never candidates; a folder date in the future is read the
|
|
other way when that makes sense (`23.09.28` → 28 Sep 2023) or ignored; a name event is never dated ahead.
|
|
- The photos' own day (`captureDay`: the Lisbon day of the camera time of most indexed photos, 3+ and 60%+) dates a
|
|
folder whose name has no day, both to find its game and to date its event. A date in the folder's name always
|
|
wins over the cameras (their clocks can be wrong).
|
|
- Every walk, and on the worker's start for all clouds (`verifyAll`), each FIXTURE gallery is checked: an event
|
|
still to come, or (the folder's name giving no day) another day than its photos were taken, takes it off that
|
|
game for good, to an event of the photos' own day.
|
|
- Before a photo of a FIXTURE folder is added, its capture day is checked against the game: more than 36 h apart
|
|
and the folder is taken off the game for good (`fixture_rejected`), its photos moving to an event of its own.
|
|
- On start, the worker takes out of live events every folder put there before (`leaveLiveEvents`): their photos
|
|
move to the archive's own events, faces found again there; photos that were already in the live event (the same
|
|
picture sent live) stay, and so do folders placed there by hand. Otherwise an event from the name (NAME) or named after the folder (FOLDER).
|
|
|
|
- Both teams must be recognised: a game with one side guessed (a nickname, a sponsor's name) is not matched. A first
|
|
team is never its B side ("SL Benfica" is not "SL Benfica B").
|
|
- Legends', veterans', charity, exhibition and tribute games, galas (`isExhibition`: "Liga Portugal Legends 2025-26")
|
|
are games in no championship: never an official fixture; the tournament's folder is the event's competition.
|
|
- Every check (on start, then every six hours, and after a season's calendar is read) makes every match but a manual
|
|
one again with today's rules: a folder that no longer fits its official game moves to the right one or to an event
|
|
of its own; a NAME event keeps its folder but takes the better names ("01.23 Leixões SC" → "Leixões SC", known
|
|
teams by their official name). One folder failing never stops the rest.
|
|
|
|
**Teams in the viewer.** The worker stores each game's sides (`archive_team_sides`) and rewrites them only when a
|
|
gallery is matched again, a club's names are joined, or a known team's name changes. The directory and the team
|
|
filter read that table: each team once, without the date or number a folder put before it (`teamLabel`), and as the
|
|
known team when exactly one fits (`canonicalTeam`: "SCP", "Sporting", "06_Sporting CP" → Sporting CP). Filtering by
|
|
it finds the galleries under every name it was written as. A viewer only gets the teams of the folders they can see.
|
|
|
|
**Faces keep to the sport.** A person known from a squad has that team's sport; a face is never suggested as someone
|
|
of another sport than the event's (its own, its official game's, or its cloud's: Liga football, FPA handball).
|
|
Suggestions made before that are taken away on the worker's start (`dropCrossSportSuggestions`); names confirmed by
|
|
a person stay.
|
|
|
|
**Games and events are kept apart.** A game (FIXTURE/MANUAL: official; NAME: known only by its folder) is matched
|
|
on competition, season, matchday, day and teams; an event (FOLDER: a gala, a session, a presentation, a training)
|
|
is never given a game and reads no shirt numbers (`numberContext` is null for an event without an away side): its
|
|
people are known by their face only. Arquivo → galleries: "Jogos oficiais", "Jogos por confirmar" (NAME), "Eventos"
|
|
(FOLDER), "Todas"; "Escolher jogo" picks the official game and moves the photos.
|
|
|
|
**Past seasons' calendars.** The live refresh only keeps the current season. When the archive meets a folder of
|
|
another season it reads that season's calendar once: Liga Portugal's month by month (`importLigaSeason`, awaited),
|
|
the FPA's national games club by club (`importFpaSeason`: the portal's `getJogosClubeEpocaEscalao` for every level of
|
|
each club, starting from today's agenda and following every club met, regional associations' games left out). The
|
|
FPA's is slow on purpose (one portal page at a time), so it runs in the background, one season at a time, in the
|
|
worker only; when it brings games, every gallery is matched again (`verifyAll`). A season counts as read with 300+
|
|
played games.
|
|
|
|
## Viewers (site)
|
|
|
|
- Each archive wears its owner's template (`cloud_sources.look`): `liga` (Liga Portugal) or `fpa` (Federação de
|
|
Andebol); none is PhotoReport's. Set from the source's name or folder when connected, changed in the app (Arquivo
|
|
→ "Aspeto do site"). One set of screens for all: a template is only tokens (colours, display type, radius) under
|
|
`[data-look]` in `apps/site/src/app/arquivo/[id]/archive.css`, plus the owner's logo (`arquivo/[id]/logos/`,
|
|
given by the owners for this use). A new client is a new token block and logo, never new markup.
|
|
- Layout: a two-bar header (logo; sections) on desktop and tablet, a bottom bar on phones (under 640 px); the
|
|
galleries open on the latest game; games show both teams; people have a club list (a sidebar from 1024 px,
|
|
pills below). Answers are kept for the page's life and read again behind; galleries load ahead on hover.
|
|
|
|
`https://events.photoreport.pt/arquivo/<source id>` (any site domain works; `VITE_ARCHIVE_URL` in the app sets
|
|
the link it shows). The viewer signs in with **their own** account on that cloud (login flow v2 again). The API
|
|
reads what is shared with them (OCS `shared_with_me`, user and group shares) and stores that grant
|
|
(`archive_grants`: sees everything, or the shared folder ids). The session (`Authorization: Archive <token>`)
|
|
carries the grant id, not the folder list; pages read the database.
|
|
|
|
- **"Manter sessão iniciada"** (the default): the app password is kept on the grant, sealed with
|
|
`DELIVERY_SECRET_KEY` (`secret_enc`), and the token is kept in the browser's localStorage, so closing the browser
|
|
does not sign out. The session slides: it ends after 30 days without use. What is shared is read again from the
|
|
cloud when the last reading (`checked_at`) is over 10 minutes old (one reading at a time per grant): a share taken
|
|
away there is gone here. The app password refused by the cloud (revoked, account removed) ends the session; the
|
|
cloud unreachable, the last reading holds for one hour, then the viewer signs in again. Never more than the cloud
|
|
says.
|
|
- Not kept: the app password is revoked at once (as before), the token lives in sessionStorage and the grant ends
|
|
after 12 hours.
|
|
- "Sair" (`POST /v1/archive/logout`) deletes the grant and revokes the kept app password; expired grants have
|
|
theirs revoked at the next sign-in. Everything below a shared folder is visible. The account that indexes the source,
|
|
or a share of its root or a folder above it, sees all of it.
|
|
|
|
A gallery, a person and a face each have a URL (`/arquivo/<source>/g/<folder>`, `/p/<person>`, `/f/<face>`), so a
|
|
link survives refresh. A gallery page is 48 thumbs; the faces of a photo load when that photo is opened. The row
|
|
of faces is the people named in that folder. "Pessoas do jogo" lists everyone named in the game (every part
|
|
the viewer may see); choosing one shows their photos in this part, or all of their photos. People, similar faces and the player directory join
|
|
`cloud_files` for the source (and the viewer's folders when they do not see everything) instead of loading every
|
|
photo id. Normal viewers never see the cloud named: the full-size originals (`cloudUrl` on a gallery and its
|
|
photos) are given only to those who edit that folder on the cloud, as a small link.
|
|
|
|
### Videos
|
|
|
|
Videos in a gallery folder (`.mp4 .m4v .mov .mts .m2ts .mkv .avi .webm`) are walked like the photos, by file id and
|
|
etag, into `cloud_videos`; a folder with videos only is a gallery too (`cloud_folders.video_count`, matched to its game
|
|
or event the same way). The original stays on the cloud. The worker (`claimVideos` / `indexVideo`, at most
|
|
`ARCHIVE_VIDEO_CONCURRENCY` at a time, default 1, beside the photos) reads it from the mount or downloads it and makes
|
|
with ffmpeg (`archive/video.ts`): a web copy every browser plays (H.264 + AAC MP4, short side at most 1080 px, upright,
|
|
`+faststart`), a 1280 px poster and a 480 px thumbnail, kept in `<org>/videos/<video id>/`. A changed video is made
|
|
again; one gone from the cloud (or its folder, or the cloud disconnected) loses its files too.
|
|
|
|
Viewers: a gallery's first page carries its videos (`videos`, `videoTotal`), each with signed links like the photos'
|
|
(`/v1/files/videos/:id/web|poster|thumb|download`, given only in a gallery the viewer may see). The web copy answers
|
|
`Range` requests, so playback starts at once and can jump anywhere. The grid shows them above the photos with their
|
|
length; the player opens like the large photo, with "Descarregar" (the web copy) for everyone and the original's link
|
|
on the cloud only for those who edit that folder. A gallery of videos only takes its first video's frame as cover.
|
|
**Faces in videos** (organizations with face recognition on, like the photos): once a video's web copy is made its
|
|
`faces_status` is PENDING, and the face worker (one video at a time, in one of the engine's places beside the photos,
|
|
so a steady flow of photos never keeps it waiting; with a single place, only when no photo is waiting) takes `ARCHIVE_VIDEO_FACE_FPS`
|
|
frames a second (default 5) out of the web copy with ffmpeg and analyses each with the same engine and filters as a
|
|
photo (size, focus, sharpness). The same face in consecutive frames (alike, and about where it was; missed for up to
|
|
1.5 s) is one appearance (`video_faces`: start, end, its clearest frame kept beside the web copy, the mean of its sharp
|
|
embeddings). Appearances go into the event's face groups by `groupEvent`, the photos' own step, so suggestions,
|
|
confirming, "não é", false positives, recognition off and merging are the photos'. "Rever rostos" shows a group's
|
|
video appearances beside its photos' faces (the frame, signed: `/v1/files/video-faces/:id`); a group with videos can
|
|
be changed only by a viewer who edits every folder its photos and videos are in. The gallery's videos carry who
|
|
appears and when (`people`, with each moment), and a person's page lists the videos they are in: the player jumps to
|
|
each moment. A folder moved to another event has its videos' faces looked for again there. The app's archive counts
|
|
show how many videos are waiting for their faces (`videoFacesPending`), done and failed.
|
|
|
|
**Damaged sources and hub noise (BIT-31658):** a source with no video stream is `no_video_stream` (#90); damaged
|
|
files (`moov atom not found`, JPEG `premature end`, a mislabelled `.jpg`) are `corrupt_source` (#93, #94), both
|
|
`FAILED` with no retry and logged at info. The Arquivo UI counts them as `failedCorrupt` ("ficheiro corrompido na
|
|
cloud"). Other failures that exhaust the attempt budget are coalesced into **one** error-hub warn per burst
|
|
(`noteIndexFailure` / `flushIndexFailures`), not one ticket per photo; a failure with attempts left is info.
|
|
|
|
### Downloads
|
|
|
|
Every viewer downloads at web size: 2048 px on the long side, with the photo's metadata (credits, caption, names);
|
|
the grid shows 480 px thumbs. One photo from the large view, a selection (up to 100) or a whole gallery (up to
|
|
1000) as a ZIP. `POST /v1/archive/:source/downloads` (`{photoIds}` or `{folderId}`, checked against what the viewer
|
|
may see) answers a link, `/v1/archive/dl?t=<ticket>`, signed (HMAC with `JWT_SECRET`) and valid 10 minutes; the
|
|
browser follows it. Photos kept at full size are made 2048 px on the way out.
|
|
|
|
### Own address
|
|
|
|
An archive can have its own host (`cloud_sources.hostname`, app → Arquivo → "Endereço próprio"), e.g.
|
|
`arquivo.ligaportugal.pt`: the site's middleware asks the API (`GET /v1/archive/host?host=`, kept 5 minutes) and
|
|
serves that archive at the root (`/g/…`, `/p/…`, `/f/…`); links stay at the root. The host's DNS points at the
|
|
proxy, which sends it to the site like the other domains (Nginx Proxy Manager: a Proxy Host with its certificate,
|
|
`docs/DEPLOY.md`). With Caddy instead, on-demand TLS can ask the same endpoint (`?domain=`, 200 only for an
|
|
archive's host; `infra/proxy/Caddyfile.example`). A host can be one archive's or one public site's, never both.
|
|
|
|
### People and faces (viewers too)
|
|
|
|
`archive/people.ts`: "Pessoas" lists who appears in the viewer's galleries (named face groups, or suggested), with
|
|
their reference photo or sharpest face, by club. A person's page has every photo of them the viewer may see:
|
|
Identificado (named), Provável (suggested for that face group), Parecido (an unnamed face group whose centroid is
|
|
like theirs, with how alike). Every face in a photo is boxed and clickable: "more of this face" compares its group's
|
|
centroid with the face groups of the visible galleries (per-event groups, so a few thousand centroids, never every
|
|
face). Nothing outside the folders shared with the viewer is compared or shown.
|
|
|
|
### Disk
|
|
|
|
Each archive photo keeps about 1.6 MB on the server (the 2048 px preview with its metadata, the preview shown and
|
|
the thumbnail). The Arquivo page shows the disk's free space and what the photos still to index will take; the
|
|
worker stops indexing while less than `ARCHIVE_MIN_FREE_GB` (default 25) is free and resumes by itself.
|
|
|
|
### Face review (viewers who edit on the cloud)
|
|
|
|
Rights come from the cloud, never from PhotoReport: a share's `permissions` with update (2) or create (4) makes its
|
|
folder, and those below, editable for that viewer (`archive_grant_folders.can_edit`); the indexing account, or a
|
|
share of the root with edit rights, edits everything (`archive_grants.edits_all`). They are read with the other
|
|
shares, at sign-in and every 10 minutes for a kept session.
|
|
|
|
- "Rever rostos" (`/v1/archive/:source/review`) lists face groups (one person in one event) in the viewer's
|
|
editable folders: Por confirmar, Sem nome, Confirmados, Não é, Falsos positivos; and who has suggestions waiting.
|
|
- On a group (`POST …/review/groups/:id`): confirm the suggestion or name it as someone (`faces.confirm`), "não é"
|
|
(`face_group_rejections`: never suggested as that person again; the next best guess takes its place), false
|
|
positive (`ignored_at`), undo. A group is changed only when every photo of it is in folders the viewer edits.
|
|
The large view offers the same on each face.
|
|
- On a person (edits everything only): turn recognition off (`people.recognition_off_at`: centroid and reference
|
|
photo dropped, every suggestion taken back, never suggested again; optionally the names already given removed;
|
|
still named by hand), on again, take back all open suggestions, drop a wrong reference photo.
|
|
- Every action goes to `archive_face_actions`, shown as the person's history.
|