From 8a8218c6b32ebe0e3bcedb416fcdf14b53113f5f Mon Sep 17 00:00:00 2001 From: spark Date: Sun, 18 Oct 2026 23:41:43 +0000 Subject: [PATCH 1/5] Make CI green: pgvector in the test database, two stale test expectations, and rustfmt. - CI's Postgres is pgvector/pgvector:pg16: the face migrations create the vector extension. - Delivery's "best of the event" answers `rest` too (since the best frames / the rest split). - A batch cull answers `{ updated }`; `changed` and `resent` belong to the IPTC save. - workers/faces/src/main.rs through rustfmt. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1 --- .gitea/workflows/ci.yml | 3 ++- apps/api/test/delivery.test.ts | 2 +- apps/api/test/library.test.ts | 2 +- workers/faces/src/main.rs | 42 ++++++++++++++++++++++++++++------ 4 files changed, 39 insertions(+), 10 deletions(-) diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 4798dd4..408996f 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -9,7 +9,8 @@ jobs: runs-on: ubuntu-latest services: postgres: - image: postgres:16 + # Faces need pgvector (the migrations create the extension). + image: pgvector/pgvector:pg16 env: POSTGRES_USER: photoreport POSTGRES_PASSWORD: photoreport diff --git a/apps/api/test/delivery.test.ts b/apps/api/test/delivery.test.ts index 9bb1f6f..9c5b7bc 100644 --- a/apps/api/test/delivery.test.ts +++ b/apps/api/test/delivery.test.ts @@ -530,7 +530,7 @@ describe("delivery", () => { // Only the best: without the autopilot, the photographer's stars decide. await ctx.db.photo.update({ where: { id: b }, data: { rating: 3 } }); const best = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/best`, headers: bearer(token), payload: { targetId, eventId: event.id, count: 1, dryRun: true } }); - expect(best.json()).toEqual({ chosen: [b], queued: [], skipped: [] }); + expect(best.json()).toEqual({ chosen: [b], rest: [], queued: [], skipped: [] }); const res = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a, b] } }); expect(res.statusCode).toBe(202); zz.logins = 0; diff --git a/apps/api/test/library.test.ts b/apps/api/test/library.test.ts index 7862c16..24af581 100644 --- a/apps/api/test/library.test.ts +++ b/apps/api/test/library.test.ts @@ -306,7 +306,7 @@ describe("library", () => { headers: bearer(admin), payload: { ids, patch: { flag: "PICK", rating: 4, players: ["Miguel Silva (VSC)"] } }, }); - expect(patch.json()).toEqual({ updated: 2, changed: 2, resent: 0 }); + expect(patch.json()).toEqual({ updated: 2 }); expect(broadcaster.sent[0]?.message).toEqual({ type: "photo.updated", ids, patch: { flag: "PICK", rating: 4, players: ["Miguel Silva (VSC)"] } }); const picks = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?flag=PICK&minRating=4`, headers: bearer(admin) }); diff --git a/workers/faces/src/main.rs b/workers/faces/src/main.rs index 96165f6..a80fdce 100644 --- a/workers/faces/src/main.rs +++ b/workers/faces/src/main.rs @@ -22,8 +22,16 @@ struct Request { #[derive(Serialize)] #[serde(untagged)] enum Response { - Ok { id: String, width: usize, height: usize, faces: Vec }, - Err { id: String, error: String }, + Ok { + id: String, + width: usize, + height: usize, + faces: Vec, + }, + Err { + id: String, + error: String, + }, } fn main() { @@ -35,7 +43,12 @@ fn main() { match arg.as_str() { "--models" => models_dir = args.next().unwrap_or_default(), "--embedder" => embedder = args.next().unwrap_or_default(), - "--min-score" => min_score = args.next().and_then(|v| v.parse().ok()).unwrap_or(min_score), + "--min-score" => { + min_score = args + .next() + .and_then(|v| v.parse().ok()) + .unwrap_or(min_score) + } _ => {} } } @@ -48,7 +61,11 @@ fn main() { }; let stdout = std::io::stdout(); let mut out = stdout.lock(); - let _ = writeln!(out, "{}", serde_json::json!({ "ready": true, "embedder": embedder, "dim": models.dim() })); + let _ = writeln!( + out, + "{}", + serde_json::json!({ "ready": true, "embedder": embedder, "dim": models.dim() }) + ); let _ = out.flush(); for line in std::io::stdin().lock().lines() { let Ok(line) = line else { break }; @@ -57,12 +74,23 @@ fn main() { } let response = match serde_json::from_str::(&line) { Ok(req) => match models.analyse(Path::new(&req.path)) { - Ok(read) => Response::Ok { id: req.id, width: read.width, height: read.height, faces: read.faces }, + Ok(read) => Response::Ok { + id: req.id, + width: read.width, + height: read.height, + faces: read.faces, + }, Err(error) => Response::Err { id: req.id, error }, }, - Err(e) => Response::Err { id: String::new(), error: format!("bad request: {e}") }, + Err(e) => Response::Err { + id: String::new(), + error: format!("bad request: {e}"), + }, }; - if serde_json::to_writer(&mut out, &response).is_err() || writeln!(out).is_err() || out.flush().is_err() { + if serde_json::to_writer(&mut out, &response).is_err() + || writeln!(out).is_err() + || out.flush().is_err() + { break; } } -- 2.47.3 From 3a0d3877f3cabebfb631ec142f72e6c6a86a7c8a Mon Sep 17 00:00:00 2001 From: spark Date: Sun, 18 Oct 2026 23:46:58 +0000 Subject: [PATCH 2/5] Docs: an archive's own address behind Nginx Proxy Manager. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1 --- docs/DEPLOY.md | 4 ++++ docs/archive.md | 5 +++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md index 37815a5..7f30ebc 100644 --- a/docs/DEPLOY.md +++ b/docs/DEPLOY.md @@ -82,6 +82,10 @@ Gitea -> webhook -> the container pulls and redeploys itself. No manual `scp`/`r Stripe secret key and webhook secret; in Stripe add the shown endpoint for `checkout.session.completed`, `checkout.session.async_payment_succeeded`, `checkout.session.async_payment_failed` and `checkout.session.expired`. Set `SMTP_URL` on the worker for order emails. + An archive's own address (app -> Arquivo -> "Endereço próprio", e.g. `ligaportugal.photoreport.pt`) is one + more host on the same port 3100: in Nginx Proxy Manager a Proxy Host for it, forwarded like + `events.next.photoreport.pt` (Host passed as is), with its Let's Encrypt certificate. With a wildcard + certificate (DNS challenge) one Proxy Host for `*.photoreport.pt` covers every archive under that domain. 11. SFTPGo (pr-ingest): no users in SFTPGo itself. Set `data_provider.external_auth_hook` to `http:///v1/sftpgo/auth?key=` and `external_auth_scope` to 1 (passwords), with the same diff --git a/docs/archive.md b/docs/archive.md index b31bd2b..3f6f8a7 100644 --- a/docs/archive.md +++ b/docs/archive.md @@ -166,8 +166,9 @@ browser follows it. Photos kept at full size are made 2048 px on the way out. 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; Caddy gets its certificate on demand, after asking 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. +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) -- 2.47.3 From 9123d979180a3eb5d78521f118da8bbbebb5b33e Mon Sep 17 00:00:00 2001 From: spark Date: Sun, 18 Oct 2026 23:55:41 +0000 Subject: [PATCH 3/5] Archive teams: one reading of each folder team name per source, warmed after a start. canonicalTeam compares a name with every known team; the Liga archive (thousands of games, every Liga team) spent minutes per request, blocking the API, and the proxy gave up: "Equipas" never loaded. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1 --- apps/api/src/archive/viewer.ts | 46 +++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/apps/api/src/archive/viewer.ts b/apps/api/src/archive/viewer.ts index e288650..cdedd58 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -381,17 +381,40 @@ export async function registerArchiveViewerRoutes( * 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. */ + /** + * Each source's folder team names and the known team they are (`canonicalTeam` compares a name with every known + * team: thousands of games times every team blocked the API for minutes). One answer per name, kept for a while, + * shared by every viewer of the source. + */ + const canonicalNames = new Map; names: Map }>(); + const CANONICAL_TTL_MS = 6 * 3600_000; const teamGroups = async (sourceId: string, games: Iterable<{ home: string; away: string }>): Promise; 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 } }); + let memo = canonicalNames.get(sourceId); + if (!memo || Date.now() - memo.at > CANONICAL_TTL_MS) { + const known = (async () => { + const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { look: true, baseUrl: true } }); + const liga = source?.look === "liga" || /liga/i.test(source?.baseUrl ?? ""); + return db.sportsTeam.findMany({ where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } }, select: { name: true, abbreviation: true, slug: true } }); + })(); + known.catch(() => canonicalNames.delete(sourceId)); + memo = { at: Date.now(), known, names: new Map() }; + canonicalNames.set(sourceId, memo); + } + const known = await memo.known; const out = new Map; galleries: number }>(); const byKey = new Map(); const fold = (x: string) => x.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim(); + let fresh = 0; for (const g of games) for (const raw of [g.home, g.away]) { if (!raw) continue; - const name = canonicalTeam(raw, known); + let name = memo.names.get(raw); + if (name === undefined) { + name = canonicalTeam(raw, known); + memo.names.set(raw, name); + // Let other requests in between the new names (the first reading of a big archive). + if (++fresh % 25 === 0) await new Promise((r) => setImmediate(r)); + } const key = fold(name); const label = byKey.get(key) ?? name; byKey.set(key, label); @@ -403,6 +426,21 @@ export async function registerArchiveViewerRoutes( return out; }; + // The team names of every archive read once in the background after a start, so the first viewer of "Equipas" + // does not wait for them (and the proxy does not give up first). + const warmTeams = async () => { + const sources = await db.cloudSource.findMany({ where: { secretEnc: { not: null } }, select: { id: true } }); + for (const s of sources) { + const rows = await db.cloudFolder.findMany({ where: { sourceId: s.id, matchedBy: { not: "FOLDER" } }, select: { event: { select: { home: true, away: true } } } }); + await teamGroups(s.id, rows.flatMap((r) => (r.event ? [r.event] : []))); + } + }; + if (!process.env.VITEST) { + app.addHook("onReady", async () => { + setTimeout(() => void warmTeams().catch((err: Error) => app.log.warn({ err }, "archive teams warm-up failed")), 5_000).unref(); + }); + } + /** 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); -- 2.47.3 From 02a1440d6695c8b85eb6dd9bb49c17f89a75c183 Mon Sep 17 00:00:00 2001 From: spark Date: Mon, 19 Oct 2026 00:03:10 +0000 Subject: [PATCH 4/5] Rename an archive in the app; a cloud that does not answer the sign-in is said in 15 s. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1 --- apps/api/src/archive/nextcloud.ts | 3 ++- apps/app/src/i18n.ts | 2 ++ apps/app/src/pages/ArchivePage.tsx | 26 +++++++++++++++++++ .../site/src/app/arquivo/[id]/ArchiveView.tsx | 2 +- 4 files changed, 31 insertions(+), 2 deletions(-) diff --git a/apps/api/src/archive/nextcloud.ts b/apps/api/src/archive/nextcloud.ts index c074371..769984b 100644 --- a/apps/api/src/archive/nextcloud.ts +++ b/apps/api/src/archive/nextcloud.ts @@ -46,7 +46,8 @@ const encodePath = (p: string) => p.split("/").map(encodeURIComponent).join("/") export async function startLogin(baseUrl: string, fetchImpl: typeof fetch = fetch, appName = "PhotoReport Arquivo"): Promise { let res: Response; try { - res = await fetchImpl(`${cleanBase(baseUrl)}/index.php/login/v2`, { method: "POST", headers: { "user-agent": appName, accept: "application/json" } }); + // A cloud that does not answer is said at once, not after the proxy gives up. + res = await fetchImpl(`${cleanBase(baseUrl)}/index.php/login/v2`, { method: "POST", headers: { "user-agent": appName, accept: "application/json" }, signal: AbortSignal.timeout(15_000) }); } catch (err) { throw new NextcloudError(`network error: ${(err as Error).message}`, 0); } diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index c6de03f..92e0a9b 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -457,6 +457,8 @@ export const t = { hostnamePlaceholder: "arquivo.ligaportugal.pt", hostnameHelp: "Opcional. Aponta esse endereço (DNS, CNAME) para o mesmo servidor do arquivo: o arquivo abre na raiz e o certificado é pedido sozinho.", hostnameSave: "Guardar", + rename: "Nome do arquivo", + renameHelp: "Aparece aqui e no título do site de consulta.", resume: "Retomar", remove: "Desligar", removeConfirm: "Desligar esta cloud? As fotos já indexadas ficam na biblioteca.", diff --git a/apps/app/src/pages/ArchivePage.tsx b/apps/app/src/pages/ArchivePage.tsx index f36cf78..0236064 100644 --- a/apps/app/src/pages/ArchivePage.tsx +++ b/apps/app/src/pages/ArchivePage.tsx @@ -121,6 +121,8 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove const viewerUrl = source.hostname ? `https://${source.hostname}` : `${VIEWER_BASE.replace(/\/+$/, "")}/arquivo/${source.id}`; const [hostname, setHostname] = useState(source.hostname ?? ""); useEffect(() => setHostname(source.hostname ?? ""), [source.hostname]); + const [name, setName] = useState(source.name); + useEffect(() => setName(source.name), [source.name]); const run = (fn: () => Promise) => { setBusy(true); @@ -212,6 +214,30 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove )} + {isAdmin && ( +
{ + e.preventDefault(); + if (name.trim()) void run(() => api.updateCloudSource(source.id, { name: name.trim() })); + }} + > + {A.rename}: + setName(e.target.value)} + maxLength={80} + disabled={busy} + className="h-6 min-w-[220px] border border-black bg-cell px-2 text-[11px] text-ink" + /> + {name.trim() && name.trim() !== source.name && ( + + )} + {A.renameHelp} +
+ )} {isAdmin && (
{ win?.close(); - setError("Não foi possível iniciar a entrada. Tenta daqui a pouco."); + setError("O serviço de entrada não está a responder. Tenta daqui a pouco."); }, ) .finally(() => setBusy(false)); -- 2.47.3 From fa14bf91f5c4b7751c45c77452d7f502e4b98353 Mon Sep 17 00:00:00 2001 From: spark Date: Mon, 19 Oct 2026 00:07:43 +0000 Subject: [PATCH 5/5] Faces worker: collapse the embedding check (clippy). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1 --- workers/faces/src/lib.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/workers/faces/src/lib.rs b/workers/faces/src/lib.rs index 2176b66..a3a5c7e 100644 --- a/workers/faces/src/lib.rs +++ b/workers/faces/src/lib.rs @@ -205,10 +205,11 @@ impl Engine { want: usize, embed: &mut dyn FnMut(&[u8]) -> Option>, ) -> Option> { - if let Some(vector) = embed(crop) { - if vector.len() == want && vector.iter().all(|value| value.is_finite()) { - return Some(vector); - } + if let Some(vector) = embed(crop) + && vector.len() == want + && vector.iter().all(|value| value.is_finite()) + { + return Some(vector); } self.models.embedder.embed(crop).ok() } -- 2.47.3