From edd3216330b5933e317dded2e0fb10cf242e2baa Mon Sep 17 00:00:00 2001 From: spark Date: Sun, 18 Oct 2026 22:33:37 +0000 Subject: [PATCH 1/6] Keep archive viewers signed in, and read their shares from the cloud again. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closing the browser signed a viewer out: the session lived in sessionStorage and the grant ended after 12 hours. "Manter sessão iniciada" (on by default) now keeps the token in localStorage and the viewer's app password, sealed, on the grant. The session lasts while it is used at least once a month, and what is shared is read from the cloud again when the last reading is over 10 minutes old, so a share taken away there is gone here too. A refused app password ends the session; an unreachable cloud keeps the last reading for one hour, never longer. "Sair" revokes the kept app password. Unticked, sign-in works as before (revoked at once, 12 hours). Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1 --- .../migration.sql | 4 + apps/api/prisma/schema.prisma | 7 + apps/api/src/archive/viewer.ts | 153 +++++++++++++++--- apps/api/test/archive.test.ts | 30 +++- .../site/src/app/arquivo/[id]/ArchiveView.tsx | 76 ++++++--- apps/site/src/app/globals.css | 13 ++ docs/archive.md | 19 ++- 7 files changed, 249 insertions(+), 53 deletions(-) create mode 100644 apps/api/prisma/migrations/20261018220000_archive_long_session/migration.sql diff --git a/apps/api/prisma/migrations/20261018220000_archive_long_session/migration.sql b/apps/api/prisma/migrations/20261018220000_archive_long_session/migration.sql new file mode 100644 index 0000000..e0e4757 --- /dev/null +++ b/apps/api/prisma/migrations/20261018220000_archive_long_session/migration.sql @@ -0,0 +1,4 @@ +-- Archive viewers can stay signed in: the grant keeps their sealed app password and when the shares were last read. +ALTER TABLE "archive_grants" ADD COLUMN "secret_enc" TEXT; +ALTER TABLE "archive_grants" ADD COLUMN "remember" BOOLEAN NOT NULL DEFAULT false; +ALTER TABLE "archive_grants" ADD COLUMN "checked_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 2afce18..3d61ef7 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -1700,6 +1700,13 @@ model ArchiveGrant { sourceId String @map("source_id") @db.Uuid viewerName String @map("viewer_name") seesAll Boolean @default(false) @map("sees_all") + /// Sealed app password of the viewer's own cloud account ("Manter sessão"): what is shared with them is read + /// again with it, so the archive never shows more than the cloud does. Null: not kept (revoked at sign-in). + secretEnc String? @map("secret_enc") + /// Kept signed in: the session slides by REMEMBER_IDLE while used; otherwise it ends after SHORT_IDLE. + remember Boolean @default(false) + /// Last time the shares were read from the cloud. + checkedAt DateTime @default(now()) @map("checked_at") expiresAt DateTime @map("expires_at") createdAt DateTime @default(now()) @map("created_at") diff --git a/apps/api/src/archive/viewer.ts b/apps/api/src/archive/viewer.ts index 5283889..b142693 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -16,10 +16,24 @@ import type { ArchiveService } from "./service.js"; /** * The archive for people outside the organization (the federation, the clubs, the press): they sign in with * their own account on that cloud (Nextcloud's login flow), and see the galleries in the folders shared with - * them there, nothing else. Their app password is used once, to read what is shared with them, and revoked. + * them there, nothing else. + * + * "Manter sessão" (the default) keeps their app password, sealed, on the grant: the session then lasts while it + * is used at least once a month, and what is shared with them is read from the cloud again every few minutes, + * so a share taken away there is gone here too. Without it the app password is used once and revoked, and the + * session ends after a working day. */ -const VIEWER_TTL_SEC = 12 * 3600; +const REMEMBER_IDLE_SEC = 30 * 24 * 3600; +const SHORT_IDLE_SEC = 12 * 3600; +/** The token's own limit; the grant (idle time, shares, sign-out) ends a session sooner. */ +const VIEWER_TTL_SEC = 180 * 24 * 3600; const LOGIN_TTL_MS = 20 * 60_000; +/** How old the last reading of a remembered viewer's shares may be before it is read again. */ +const RECHECK_MS = 10 * 60_000; +/** While the cloud cannot be reached, the last reading holds this long; then the viewer signs in again. */ +const UNREACHABLE_GRACE_MS = 60 * 60_000; +/** A remembered session's end moves forward at most this often (one write, not one per request). */ +const SLIDE_STEP_MS = 6 * 3600_000; export interface Viewer { /** Source id. */ @@ -68,7 +82,7 @@ const GalleryQuery = z.object({ player: z.string().trim().max(120).optional(), person: z.uuid().optional(), }); -const Poll = z.object({ state: z.string().min(10).max(4000) }); +const Poll = z.object({ state: z.string().min(10).max(4000), remember: z.boolean().default(true) }); const ListQuery = z.object({ q: z.string().trim().max(120).optional(), team: z.string().trim().max(120).optional(), @@ -88,6 +102,84 @@ export async function registerArchiveViewerRoutes( return deps.secrets; }; + /** What a cloud account sees of a source: everything (it indexes it, or a share of its root or above), or folders. */ + const readShares = async ( + source: { id: string; baseUrl: string; username: string; secretEnc: string | null; rootPath: string }, + viewer: CloudClient, + me: { id: string }, + ): Promise<{ all: boolean; folders: string[] }> => { + if (me.id === source.username) return { all: true, folders: [] }; + const shared = new Set(await viewer.sharedWithMe()); + const above = await ancestorsOf(deps.archive.client(source), source.rootPath); + if (above.some((id) => shared.has(id))) return { all: true, folders: [] }; + if (!shared.size) return { all: false, folders: [] }; + const rows = await db.cloudFolder.findMany({ where: { sourceId: source.id, fileId: { in: [...shared] } }, select: { id: true } }); + return { all: false, folders: rows.map((r) => r.id) }; + }; + + /** Drops a grant, revoking its app password on the cloud when one was kept. */ + const endGrant = async (grant: { id: string; sourceId: string; secretEnc: string | null }) => { + await db.archiveGrant.deleteMany({ where: { id: grant.id } }); + if (!grant.secretEnc || !deps.secrets) return; + const source = await db.cloudSource.findUnique({ where: { id: grant.sourceId }, select: { baseUrl: true } }); + if (!source) return; + try { + const auth = JSON.parse(deps.secrets.open(grant.secretEnc)) as { u: string; p: string }; + await new CloudClient({ baseUrl: source.baseUrl, username: auth.u, password: auth.p }, fetchImpl).revoke(); + } catch { + /* already gone on the cloud */ + } + }; + + /** One reading of a grant's shares at a time, however many pages ask at once. */ + const rechecks = new Map>(); + + /** + * Reads again what is shared with a remembered viewer. The app password refused (revoked, account gone): + * the session ends. The cloud unreachable: the last reading holds for UNREACHABLE_GRACE_MS, then it ends too; + * never more than the cloud said. + */ + const recheck = (grant: { id: string; sourceId: string; secretEnc: string; checkedAt: Date; seesAll: boolean; folders: { folderId: string }[] }) => { + const running = rechecks.get(grant.id); + if (running) return running; + const work = (async () => { + const source = await db.cloudSource.findUnique({ where: { id: grant.sourceId } }); + if (!source || !source.secretEnc) { + await endGrant(grant); + throw unauthorized("archive_login_required"); + } + let auth: { u: string; p: string }; + try { + auth = JSON.parse(box().open(grant.secretEnc)) as { u: string; p: string }; + } catch { + await endGrant({ ...grant, secretEnc: null }); + throw unauthorized("archive_login_required"); + } + const client = new CloudClient({ baseUrl: source.baseUrl, username: auth.u, password: auth.p }, fetchImpl); + try { + const me = await client.whoami(); + const read = await readShares(source, client, me); + await db.$transaction([ + db.archiveGrantFolder.deleteMany({ where: { grantId: grant.id } }), + ...(read.all || !read.folders.length ? [] : [db.archiveGrantFolder.createMany({ data: read.folders.map((folderId) => ({ grantId: grant.id, folderId })) })]), + db.archiveGrant.update({ where: { id: grant.id }, data: { seesAll: read.all, checkedAt: new Date() } }), + ]); + return { seesAll: read.all, folders: read.folders }; + } catch (err) { + const status = err instanceof NextcloudError ? err.status : 0; + if (status === 401 || status === 403) { + await db.archiveGrant.deleteMany({ where: { id: grant.id } }); + throw unauthorized("archive_login_required"); + } + if (err instanceof AppError) throw err; + if (Date.now() - grant.checkedAt.getTime() > UNREACHABLE_GRACE_MS) throw unauthorized("archive_cloud_unreachable"); + return { seesAll: grant.seesAll, folders: grant.folders.map((f) => f.folderId) }; + } + })().finally(() => rechecks.delete(grant.id)); + rechecks.set(grant.id, work); + return work; + }; + const viewerOf = (req: FastifyRequest, sourceId?: string): Viewer => { const header = req.headers.authorization; const token = header?.startsWith("Archive ") ? header.slice(8) : undefined; @@ -105,9 +197,17 @@ export async function registerArchiveViewerRoutes( let roots = v.f ?? []; if (v.g) { const grant = await db.archiveGrant.findUnique({ where: { id: v.g }, include: { folders: { select: { folderId: true } } } }); - if (!grant || grant.sourceId !== v.s || grant.expiresAt.getTime() <= Date.now()) throw unauthorized("archive_login_required"); + const now = Date.now(); + if (!grant || grant.sourceId !== v.s || grant.expiresAt.getTime() <= now) throw unauthorized("archive_login_required"); all = grant.seesAll; roots = grant.folders.map((f) => f.folderId); + if (grant.secretEnc && now - grant.checkedAt.getTime() > RECHECK_MS) { + const read = await recheck({ ...grant, secretEnc: grant.secretEnc }); + all = read.seesAll; + roots = read.folders; + } + if (grant.remember && grant.expiresAt.getTime() < now + REMEMBER_IDLE_SEC * 1000 - SLIDE_STEP_MS) + await db.archiveGrant.updateMany({ where: { id: grant.id }, data: { expiresAt: new Date(now + REMEMBER_IDLE_SEC * 1000) } }); } if (all) return "all"; if (!roots.length) return []; @@ -156,7 +256,7 @@ export async function registerArchiveViewerRoutes( /** 202 while the viewer has not authorised; then their archive session and name. */ app.post("/v1/archive/login/poll", { config: { rateLimit: { max: 200, timeWindow: "10 minutes" } } }, async (req, reply) => { - const { state } = Poll.parse(req.body); + const { state, remember } = Poll.parse(req.body); let s: { s: string; endpoint: string; token: string; exp: number }; try { s = JSON.parse(box().open(state)) as typeof s; @@ -171,41 +271,48 @@ export async function registerArchiveViewerRoutes( }); if (!done) return reply.code(202).send({ pending: true }); const viewer = new CloudClient({ baseUrl: source.baseUrl, username: done.loginName, password: done.appPassword }, fetchImpl); + let kept = false; try { const me = await viewer.whoami(); - let all = me.id === source.username; - let folders: string[] = []; - if (!all) { - const shared = new Set(await viewer.sharedWithMe()); - // A share of the indexed folder or of one above it opens everything. - const owner = deps.archive.client(source); - const above = await ancestorsOf(owner, source.rootPath); - all = above.some((id) => shared.has(id)); - if (!all && shared.size) { - const rows = await db.cloudFolder.findMany({ where: { sourceId: source.id, fileId: { in: [...shared] } }, select: { id: true } }); - folders = rows.map((r) => r.id); - } - } - await db.archiveGrant.deleteMany({ where: { sourceId: source.id, expiresAt: { lt: new Date() } } }); + const { all, folders } = await readShares(source, viewer, me); + // Sessions that ran out: their kept app passwords are revoked on the cloud too. + const stale = await db.archiveGrant.findMany({ where: { expiresAt: { lt: new Date() } }, select: { id: true, sourceId: true, secretEnc: true }, take: 50 }); + for (const g of stale) await endGrant(g); const grant = await db.archiveGrant.create({ data: { sourceId: source.id, viewerName: me.displayName, seesAll: all, - expiresAt: new Date(Date.now() + VIEWER_TTL_SEC * 1000), + remember, + secretEnc: remember ? box().seal(JSON.stringify({ u: done.loginName, p: done.appPassword })) : null, + checkedAt: new Date(), + expiresAt: new Date(Date.now() + (remember ? REMEMBER_IDLE_SEC : SHORT_IDLE_SEC) * 1000), ...(!all && folders.length ? { folders: { create: folders.map((folderId) => ({ folderId })) } } : {}), }, }); - return { token: tokens.sign({ s: source.id, n: me.displayName, g: grant.id }), viewer: { name: me.displayName, all, folders: folders.length } }; + kept = remember; + return { token: tokens.sign({ s: source.id, n: me.displayName, g: grant.id }), viewer: { name: me.displayName, all, folders: folders.length }, remember }; } catch (err) { if (err instanceof NextcloudError) throw new AppError(502, "cloud_error", err.message); throw err; } finally { - // Only needed to read the shares: never kept. - await viewer.revoke(); + // Not remembered (or the sign-in failed): only needed to read the shares, never kept. + if (!kept) await viewer.revoke(); } }); + /** Signs out: the grant goes and, when it was kept, the app password is revoked on the cloud. */ + app.post("/v1/archive/logout", async (req, reply) => { + const header = req.headers.authorization; + const token = header?.startsWith("Archive ") ? header.slice(8) : undefined; + const v = token ? tokens.verify(token) : null; + if (v?.g) { + const grant = await db.archiveGrant.findUnique({ where: { id: v.g }, select: { id: true, sourceId: true, secretEnc: true } }); + if (grant && grant.sourceId === v.s) await endGrant(grant); + } + return reply.code(204).send(); + }); + /** * The teams of the viewer's games under one name each: without the date or number a folder put before it ("01.23 * Leixões SC"), and the known team's official name when exactly one fits ("SCP", "Sporting" → "Sporting CP"). diff --git a/apps/api/test/archive.test.ts b/apps/api/test/archive.test.ts index a96fc68..7558d14 100644 --- a/apps/api/test/archive.test.ts +++ b/apps/api/test/archive.test.ts @@ -588,7 +588,7 @@ describe("archive from a Nextcloud", () => { // A club account: the PO01 folder is shared with its group. cloud.viewers.set("abc", { password: "abc-pass", shared: [cloud.idOf("/FPA/Fotos/2025_2026/Competições Nacionais/PO01")] }); cloud.viewers.set("ninguem", { password: "n-pass", shared: [] }); - const signIn = async (who: string) => { + const signIn = async (who: string, remember?: boolean) => { cloud.loginAs = who; cloud.authorised = false; let res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}` }); @@ -599,7 +599,7 @@ describe("archive from a Nextcloud", () => { res = await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state } }); expect(res.statusCode).toBe(202); cloud.authorised = true; - res = await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state } }); + res = await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state, ...(remember === false && { remember }) } }); expect(res.statusCode).toBe(200); return res.json() as { token: string; viewer: { name: string; all: boolean } }; }; @@ -611,7 +611,8 @@ describe("archive from a Nextcloud", () => { const club = await signIn("abc"); expect(club.viewer).toEqual({ name: "ABC", all: false, folders: 1 }); - expect(cloud.revoked).toContain("abc"); + // Kept signed in (the default): the app password stays, to read the shares again later. + expect(cloud.revoked).not.toContain("abc"); const seen = await galleries(club.token); expect(seen.map((g) => g.title)).toEqual(["Sporting CP x ABC de Braga"]); expect(seen[0]!.cover).toMatch(/^\/v1\/files\/photos\//); @@ -622,7 +623,9 @@ describe("archive from a Nextcloud", () => { res = await ctx.app.inject({ method: "GET", url: `/v1/archive/galleries/${gala.id}`, headers: { authorization: `Archive ${club.token}` } }); expect(res.statusCode).toBe(404); - const nobody = await signIn("ninguem"); + // Not kept signed in: the app password is used once and revoked. + const nobody = await signIn("ninguem", false); + expect(cloud.revoked).toContain("ninguem"); expect(await galleries(nobody.token)).toEqual([]); // The account that indexes the archive sees all of it. @@ -633,6 +636,25 @@ describe("archive from a Nextcloud", () => { // A forged or foreign token is refused. res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/galleries`, headers: { authorization: `Archive ${club.token.slice(0, -2)}xx` } }); expect(res.statusCode).toBe(401); + + // A share taken away on the cloud is gone here at the next reading of the shares. + const club2 = await signIn("abc"); + expect((await galleries(club2.token)).length).toBe(1); + cloud.viewers.get("abc")!.shared = []; + await ctx.db.archiveGrant.updateMany({ data: { checkedAt: new Date(Date.now() - 15 * 60_000) } }); + expect(await galleries(club2.token)).toEqual([]); + // Its app password refused by the cloud (revoked there): signed out. + cloud.viewers.get("abc")!.password = "changed"; + await ctx.db.archiveGrant.updateMany({ data: { checkedAt: new Date(Date.now() - 15 * 60_000) } }); + res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/galleries`, headers: { authorization: `Archive ${club2.token}` } }); + expect(res.statusCode).toBe(401); + + // Signing out revokes the kept app password and ends the session. + res = await ctx.app.inject({ method: "POST", url: "/v1/archive/logout", headers: { authorization: `Archive ${owner.token}` } }); + expect(res.statusCode).toBe(204); + expect(cloud.revoked).toContain("peter"); + res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/galleries`, headers: { authorization: `Archive ${owner.token}` } }); + expect(res.statusCode).toBe(401); }); it("finds people by face within what each viewer may see", async () => { diff --git a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx index c720863..c31077d 100644 --- a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx +++ b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx @@ -104,19 +104,29 @@ const storageKey = (id: string) => `arquivo_${id}`; /** Whose archive it is, in the band on top, when it wears its owner's look. */ const OWNER: Record<"liga" | "fpa", string> = { liga: "Liga Portugal", fpa: "Federação de Andebol de Portugal" }; +/** + * The session: in localStorage when kept signed in (survives closing the browser), else in sessionStorage + * (gone with the tab). Either may throw in a private window; the session then lasts as long as the page. + */ const read = (k: string) => { - try { - return window.sessionStorage.getItem(k); - } catch { - return null; + for (const store of ["localStorage", "sessionStorage"] as const) { + try { + const v = window[store].getItem(k); + if (v !== null) return v; + } catch { + /* not available */ + } } + return null; }; -const write = (k: string, v: string | null) => { - try { - if (v === null) window.sessionStorage.removeItem(k); - else window.sessionStorage.setItem(k, v); - } catch { - /* private window: the session lasts as long as the page */ +const write = (k: string, v: string | null, keep = false) => { + for (const store of ["localStorage", "sessionStorage"] as const) { + try { + if (v === null || (store === "localStorage") !== keep) window[store].removeItem(k); + else window[store].setItem(k, v); + } catch { + /* not available */ + } } }; @@ -140,7 +150,17 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } setReady(true); }, [info.id]); + /** Ends the session here and on the server (which revokes the app password kept on the cloud). */ const signOut = useCallback(() => { + const t = read(storageKey(info.id)); + if (t) void fetch("/v1/archive/logout", { method: "POST", headers: { authorization: `Archive ${t}` }, keepalive: true }).catch(() => undefined); + write(storageKey(info.id), null); + write(`${storageKey(info.id)}_name`, null); + setToken(null); + }, [info.id]); + + /** The server ended the session (idle, a share or the app password taken away on the cloud). */ + const expired = useCallback(() => { write(storageKey(info.id), null); write(`${storageKey(info.id)}_name`, null); setToken(null); @@ -184,13 +204,13 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } )} {token ? ( - + ) : ( { - write(storageKey(info.id), t); - write(`${storageKey(info.id)}_name`, name); + onDone={(t, name, keep) => { + write(storageKey(info.id), t, keep); + write(`${storageKey(info.id)}_name`, name, keep); setViewer(name); setToken(t); }} @@ -201,8 +221,9 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } ); } -function SignIn({ info, onDone }: { info: ArchiveInfo; onDone: (token: string, name: string) => void }) { +function SignIn({ info, onDone }: { info: ArchiveInfo; onDone: (token: string, name: string, keep: boolean) => void }) { const [state, setState] = useState(null); + const [keep, setKeep] = useState(true); const [loginUrl, setLoginUrl] = useState(null); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); @@ -211,11 +232,11 @@ function SignIn({ info, onDone }: { info: ArchiveInfo; onDone: (token: string, n if (!state) return; let live = true; const timer = setInterval(() => { - call<{ pending?: boolean; token?: string; viewer?: { name: string } }>("/v1/archive/login/poll", null, { method: "POST", body: JSON.stringify({ state }) }).then( + call<{ pending?: boolean; token?: string; viewer?: { name: string } }>("/v1/archive/login/poll", null, { method: "POST", body: JSON.stringify({ state, remember: keep }) }).then( ({ status, body }) => { if (!live || status === 202 || !body.token) return; clearInterval(timer); - onDone(body.token, body.viewer?.name ?? ""); + onDone(body.token, body.viewer?.name ?? "", keep); }, () => { if (!live) return; @@ -229,7 +250,7 @@ function SignIn({ info, onDone }: { info: ArchiveInfo; onDone: (token: string, n live = false; clearInterval(timer); }; - }, [state, onDone]); + }, [state, onDone, keep]); const start = () => { setBusy(true); @@ -264,12 +285,23 @@ function SignIn({ info, onDone }: { info: ArchiveInfo; onDone: (token: string, n )} ) : ( - + <> + + + )} {error &&

{error}

} -

A tua palavra-passe é escrita apenas na página da cloud. O acesso dado ao PhotoReport serve só para saber o que está partilhado contigo e é revogado de imediato.

+

+ A tua palavra-passe é escrita apenas na página da cloud.{" "} + {keep + ? `Com a sessão mantida, o PhotoReport guarda (cifrado) o acesso que deres para voltar a ler, de poucos em poucos minutos, o que está partilhado contigo: se te tirarem uma partilha em ${info.cloud}, deixa de aparecer aqui. A sessão dura enquanto a usares pelo menos uma vez por mês; "Sair" revoga o acesso.` + : "Sem manter sessão, o acesso serve só para saber o que está partilhado contigo, é revogado de imediato e a sessão acaba ao fechar o separador."} +

); } diff --git a/apps/site/src/app/globals.css b/apps/site/src/app/globals.css index f4b6b53..4d5562c 100644 --- a/apps/site/src/app/globals.css +++ b/apps/site/src/app/globals.css @@ -777,6 +777,19 @@ button.chip { padding: 32px 0 64px; justify-items: start; } +.keep-signed { + display: inline-flex; + align-items: center; + gap: 10px; + min-height: 44px; + cursor: pointer; +} +.keep-signed input { + width: 20px; + height: 20px; + margin: 0; + accent-color: currentColor; +} .archive-card { display: block; align-self: start; diff --git a/docs/archive.md b/docs/archive.md index e90ac41..1d5a425 100644 --- a/docs/archive.md +++ b/docs/archive.md @@ -124,10 +124,21 @@ played games. `https://events.photoreport.pt/arquivo/` (any site domain works; `VITE_ARCHIVE_URL` in the app sets the link it shows). The viewer signs in with **their own** account on that cloud (login flow v2 again). The API -reads what is shared with them (OCS `shared_with_me`, user and group shares), revokes that app password at once, -and stores that grant (`archive_grants`: sees everything, or the shared folder ids). The 12 h session -(`Authorization: Archive `) carries the grant id, not the folder list; later pages read the database and -do not call the cloud again. Everything below a shared folder is visible. The account that indexes the source, +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 `) +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//g/`, `/p/`, `/f/`), so a -- 2.47.3 From 738823e7c3b654425adf146866432e4a6059eff9 Mon Sep 17 00:00:00 2001 From: spark Date: Sun, 18 Oct 2026 22:43:27 +0000 Subject: [PATCH 2/6] Give the archive its owners' templates, a phone and tablet layout, and quicker lists. One set of screens; FPA and Liga Portugal differ only in tokens (colours, display type, radius) and their logo, in archive.css under `data-look`. Two-bar header with the sections, a bottom bar on phones; galleries open on the latest game, cards show the two teams; a game's page shows the match, the people of the game and the photos; people with a club list (a sidebar on desktop, pills on smaller screens); teams as cards. Speed: answers are kept for the page's life and read again behind; galleries load ahead on hover; faces and reference photos are lazy instead of CSS backgrounds (all fetched at once before); the next and previous photos preload in the large view. The directory sends the teams at once and the players apart, both kept five minutes per source and per set of visible folders. Galleries carry a preview-size cover, and a gallery its two teams. The archive's styles move out of the site's globals.css into the archive's own stylesheet. Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1 --- apps/api/src/archive/viewer.ts | 62 +- .../site/src/app/arquivo/[id]/ArchiveView.tsx | 1157 ++--------- apps/site/src/app/arquivo/[id]/Browse.tsx | 412 ++++ apps/site/src/app/arquivo/[id]/Gallery.tsx | 255 +++ apps/site/src/app/arquivo/[id]/Lightbox.tsx | 164 ++ apps/site/src/app/arquivo/[id]/PhotosOf.tsx | 198 ++ apps/site/src/app/arquivo/[id]/api.ts | 219 +++ apps/site/src/app/arquivo/[id]/archive.css | 1703 +++++++++++++++++ apps/site/src/app/arquivo/[id]/frame.tsx | 10 +- apps/site/src/app/arquivo/[id]/layout.tsx | 5 +- apps/site/src/app/arquivo/[id]/logos/fpa.png | Bin 0 -> 44354 bytes apps/site/src/app/arquivo/[id]/logos/liga.png | Bin 0 -> 18384 bytes apps/site/src/app/arquivo/[id]/page.tsx | 8 +- apps/site/src/app/arquivo/[id]/parts.tsx | 103 + apps/site/src/app/globals.css | 582 ------ 15 files changed, 3319 insertions(+), 1559 deletions(-) create mode 100644 apps/site/src/app/arquivo/[id]/Browse.tsx create mode 100644 apps/site/src/app/arquivo/[id]/Gallery.tsx create mode 100644 apps/site/src/app/arquivo/[id]/Lightbox.tsx create mode 100644 apps/site/src/app/arquivo/[id]/PhotosOf.tsx create mode 100644 apps/site/src/app/arquivo/[id]/api.ts create mode 100644 apps/site/src/app/arquivo/[id]/archive.css create mode 100644 apps/site/src/app/arquivo/[id]/logos/fpa.png create mode 100644 apps/site/src/app/arquivo/[id]/logos/liga.png create mode 100644 apps/site/src/app/arquivo/[id]/parts.tsx diff --git a/apps/api/src/archive/viewer.ts b/apps/api/src/archive/viewer.ts index b142693..e13e2f7 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -131,6 +131,24 @@ export async function registerArchiveViewerRoutes( } }; + /** + * The heavy lists (teams, players), kept a few minutes per source and per set of folders the viewer may see: two + * viewers with the same shares share them, and nobody gets a list built for wider access than theirs. + */ + const lists = new Map }>(); + const LIST_TTL_MS = 5 * 60_000; + const remembered = (sourceId: string, kind: string, visible: string[] | "all", build: () => Promise): Promise => { + const scope = visible === "all" ? "all" : createHmac("sha1", "scope").update([...visible].sort().join(",")).digest("base64url"); + const key = `${sourceId}:${kind}:${scope}`; + const hit = lists.get(key); + if (hit && Date.now() - hit.at < LIST_TTL_MS) return hit.value as Promise; + const value = build(); + lists.set(key, { at: Date.now(), value }); + value.catch(() => lists.delete(key)); + if (lists.size > 500) for (const [k, v] of lists) if (Date.now() - v.at >= LIST_TTL_MS) lists.delete(k); + return value; + }; + /** One reading of a grant's shares at a time, however many pages ask at once. */ const rechecks = new Map>(); @@ -382,21 +400,38 @@ export async function registerArchiveViewerRoutes( startsAt: f.event?.startsAt ?? null, photoCount: f.photoCount, cover: cover.has(f.id) ? signer.url(cover.get(f.id)!, "thumb") : null, + coverLarge: cover.has(f.id) ? signer.url(cover.get(f.id)!, "preview") : null, })), }; }); - /** The teams and players in the viewer's galleries (for the directory and the search). */ + /** + * The teams in the viewer's games (for the directory and the search). Quick: folders and their events. The + * players named on photos are a scan of the photos, so they come apart (`/directory/players`) and the page shows + * the teams without waiting for them. + */ app.get("/v1/archive/:sourceId/directory", async (req) => { const { sourceId } = SourceParams.parse(req.params); const v = viewerOf(req, sourceId); const visible = await visibleFolders(v); - const folders = await db.cloudFolder.findMany({ where: folderWhere(v, visible), select: { eventId: true, matchedBy: true, event: { select: { id: true, home: true, away: true } } } }); - // Teams of games only (a session or a day of an event is named in "home" too), each game counted once. - const games = new Map(); - for (const f of folders) if (f.event && f.matchedBy !== "FOLDER") games.set(f.event.id, f.event); - const teams = new Map([...(await teamGroups(sourceId, games.values()))].map(([name, g]) => [name, g.galleries])); - const players = + const teams = await remembered(sourceId, "teams", visible, async () => { + const folders = await db.cloudFolder.findMany({ where: { ...folderWhere(v, visible), matchedBy: { not: "FOLDER" } }, select: { event: { select: { id: true, home: true, away: true } } } }); + // Teams of games only (a session or a day of an event is named in "home" too), each game counted once. + const games = new Map(); + for (const f of folders) if (f.event) games.set(f.event.id, f.event); + return [...(await teamGroups(sourceId, games.values()))] + .map(([name, g]) => ({ name, galleries: g.galleries })) + .sort((a, b) => b.galleries - a.galleries || a.name.localeCompare(b.name)); + }); + return { teams }; + }); + + /** The players named on the viewer's photos (a session's folder per athlete, the editors' tags). */ + app.get("/v1/archive/:sourceId/directory/players", async (req) => { + const { sourceId } = SourceParams.parse(req.params); + const v = viewerOf(req, sourceId); + const visible = await visibleFolders(v); + const players = await remembered(sourceId, "players", visible, async () => visible === "all" || visible.length ? await db.$queryRaw<{ name: string; photos: bigint; club: string | null }[]>` SELECT p.name, count(*) AS photos, max(pe.club) AS club @@ -405,11 +440,9 @@ export async function registerArchiveViewerRoutes( LEFT JOIN people pe ON pe.name = p.name AND pe.organization_id = (SELECT organization_id FROM cloud_sources WHERE id = ${sourceId}::uuid) WHERE p.name <> '' GROUP BY p.name ORDER BY count(*) DESC, p.name LIMIT 2000` - : []; - return { - teams: [...teams].map(([name, galleries]) => ({ name, galleries })).sort((a, b) => b.galleries - a.galleries || a.name.localeCompare(b.name)), - players: players.map((p) => ({ name: p.name, club: p.club, photos: Number(p.photos) })), - }; + : [], + ); + return { players: players.map((p) => ({ name: p.name, club: p.club, photos: Number(p.photos) })) }; }); /** One page of a gallery (the viewer must see its folder). Faces are not in the page; a photo asks for its own. */ @@ -487,6 +520,11 @@ export async function registerArchiveViewerRoutes( id: folder.id, title: folder.event ? eventName(folder.event) : folder.path.split("/").pop(), section: describeFolder(folder.path).section, + /** A game's two sides (an event has no away side). */ + home: folder.event && folder.matchedBy !== "FOLDER" ? folder.event.home : null, + away: folder.event && folder.matchedBy !== "FOLDER" ? folder.event.away || null : null, + homeShort: folder.event?.homeShort ?? null, + awayShort: folder.event?.awayShort ?? null, competition: folder.event?.competition ?? null, startsAt: folder.event?.startsAt ?? null, /** The folder on the cloud (opens for those it is shared with). */ diff --git a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx index c31077d..cb1bba6 100644 --- a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx +++ b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx @@ -1,232 +1,194 @@ "use client"; -import { useCallback, useEffect, useMemo, useState } from "react"; +import { useCallback, useEffect, useState } from "react"; import { useRouter } from "next/navigation"; +import { call, readStored, storageKey, writeStored } from "./api"; +import { Browse, type Tab } from "./Browse"; +import { Gallery } from "./Gallery"; +import { Icon } from "./parts"; +import fpaLogo from "./logos/fpa.png"; +import ligaLogo from "./logos/liga.png"; +import { PhotosOf } from "./PhotosOf"; import type { ArchiveInfo } from "./page"; -interface GalleryCard { - id: string; - title: string; - /** The part of the game or session: "1P", "Aquecimento", an athlete's name. */ - section?: string | null; - home: string | null; - away: string | null; - competition: string | null; - startsAt: string | null; - photoCount: number; - cover: string | null; -} +/** Where the viewer is: one of the lists, in a gallery, on a person's photos, or on "more of this face". */ +export type View = { kind: "browse"; tab?: Tab } | { kind: "gallery"; id: string } | { kind: "person"; id: string } | { kind: "face"; id: string }; -interface Box { - x0: number; - y0: number; - x1: number; - y1: number; -} - -type Level = "confirmed" | "probable" | "similar"; - -interface PhotoFace { - id: string; - box: Box | null; - person: { id: string; name: string } | null; - level: "confirmed" | "probable" | null; -} - -interface ArchivePhoto { - id: string; - name: string; - width: number | null; - height: number | null; - players: string[]; - thumb: string; - preview: string; - cloudUrl?: string; - faces?: PhotoFace[]; - /** Person and face searches: how sure, the face found, and its gallery. */ - level?: Level; - score?: number | null; - face?: Box | null; - gallery?: { id: string; title: string; startsAt: string | null; competition: string | null } | null; -} - -interface PersonCard { - id: string; - name: string; - club: string | null; - number: string | null; - photos: number; - probable: number; - reference: string | null; - face: { src: string; box: Box | null; aspect: number } | null; -} - -interface GalleryPerson { - id: string; - name: string; - count: number; - face: { src: string; box: Box | null; aspect: number } | null; -} - -/** Someone named in the game, including parts of it other than the folder on screen. */ -interface GamePerson { - id: string; - name: string; - club: string | null; - number: string | null; - here: number; - inGame: number; -} - -interface GalleryDetail { - id: string; - title: string; - section?: string | null; - competition: string | null; - startsAt: string | null; - cloudUrl: string; - total?: number; - people?: GalleryPerson[]; - /** People named anywhere in this game. */ - roster?: GamePerson[]; - photos: ArchivePhoto[]; -} - -interface Directory { - teams: { name: string; galleries: number }[]; - /** Named on the photos (a session's folder per athlete, the editors' tags). */ - players?: { name: string; club: string | null; photos: number }[]; -} - -const PAGE = 48; -const day = new Intl.DateTimeFormat("pt-PT", { timeZone: "Europe/Lisbon", day: "numeric", month: "long", year: "numeric" }); -const storageKey = (id: string) => `arquivo_${id}`; - -/** Whose archive it is, in the band on top, when it wears its owner's look. */ -const OWNER: Record<"liga" | "fpa", string> = { liga: "Liga Portugal", fpa: "Federação de Andebol de Portugal" }; -/** - * The session: in localStorage when kept signed in (survives closing the browser), else in sessionStorage - * (gone with the tab). Either may throw in a private window; the session then lasts as long as the page. - */ -const read = (k: string) => { - for (const store of ["localStorage", "sessionStorage"] as const) { - try { - const v = window[store].getItem(k); - if (v !== null) return v; - } catch { - /* not available */ - } - } - return null; -}; -const write = (k: string, v: string | null, keep = false) => { - for (const store of ["localStorage", "sessionStorage"] as const) { - try { - if (v === null || (store === "localStorage") !== keep) window[store].removeItem(k); - else window[store].setItem(k, v); - } catch { - /* not available */ - } - } +/** Each owner's template: its name and logo. Colours and type are in archive.css (`data-look`). */ +const TEMPLATE: Record<"liga" | "fpa", { owner: string; logo: string }> = { + liga: { owner: "Liga Portugal", logo: ligaLogo.src }, + fpa: { owner: "Federação de Andebol de Portugal", logo: fpaLogo.src }, }; -class Unauthorised extends Error {} - -async function call(path: string, token: string | null, init: RequestInit = {}): Promise<{ status: number; body: T }> { - const res = await fetch(path, { ...init, headers: { ...(token && { authorization: `Archive ${token}` }), ...(init.body ? { "content-type": "application/json" } : {}), ...(init.headers ?? {}) } }); - if (res.status === 401) throw new Unauthorised(); - if (!res.ok) throw new Error(`${res.status}`); - return { status: res.status, body: (await res.json()) as T }; -} +const TABS: [Tab, string, "galleries" | "people" | "teams"][] = [ + ["galleries", "Galerias", "galleries"], + ["people", "Pessoas", "people"], + ["teams", "Equipas", "teams"], +]; +const TAB_PARAM: Record = { galleries: "", people: "pessoas", teams: "equipas" }; export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View }) { + const router = useRouter(); const [token, setToken] = useState(null); const [viewer, setViewer] = useState(null); const [ready, setReady] = useState(false); + const view: View = start ?? { kind: "browse" }; + const [tab, setTab] = useState(view.kind === "browse" ? (view.tab ?? "galleries") : "galleries"); + const template = info.look ? TEMPLATE[info.look] : null; + const base = `/arquivo/${info.id}`; useEffect(() => { - setToken(read(storageKey(info.id))); - setViewer(read(`${storageKey(info.id)}_name`)); + setToken(readStored(storageKey(info.id))); + setViewer(readStored(`${storageKey(info.id)}_name`)); setReady(true); }, [info.id]); /** Ends the session here and on the server (which revokes the app password kept on the cloud). */ const signOut = useCallback(() => { - const t = read(storageKey(info.id)); + const t = readStored(storageKey(info.id)); if (t) void fetch("/v1/archive/logout", { method: "POST", headers: { authorization: `Archive ${t}` }, keepalive: true }).catch(() => undefined); - write(storageKey(info.id), null); - write(`${storageKey(info.id)}_name`, null); + writeStored(storageKey(info.id), null); + writeStored(`${storageKey(info.id)}_name`, null); setToken(null); }, [info.id]); /** The server ended the session (idle, a share or the app password taken away on the cloud). */ const expired = useCallback(() => { - write(storageKey(info.id), null); - write(`${storageKey(info.id)}_name`, null); + writeStored(storageKey(info.id), null); + writeStored(`${storageKey(info.id)}_name`, null); setToken(null); }, [info.id]); - const owner = info.look ? OWNER[info.look] : null; - const session = token && ( - - {viewer ? {`Sessão de ${viewer} · `} : ""} - - + const go = useCallback( + (v: View) => { + const href = + v.kind === "browse" + ? `${base}${v.tab && TAB_PARAM[v.tab] ? `?t=${TAB_PARAM[v.tab]}` : ""}` + : v.kind === "gallery" + ? `${base}/g/${v.id}` + : v.kind === "person" + ? `${base}/p/${v.id}` + : `${base}/f/${v.id}`; + router.push(href); + window.scrollTo({ top: 0 }); + }, + [base, router], ); - if (!ready) + + /** A tab of the lists: in place when they are on screen (no reload), else back to them. */ + const openTab = useCallback( + (t: Tab) => { + if (view.kind !== "browse") return go({ kind: "browse", tab: t }); + setTab(t); + window.history.replaceState(null, "", `${base}${TAB_PARAM[t] ? `?t=${TAB_PARAM[t]}` : ""}`); + window.scrollTo({ top: 0 }); + }, + [view.kind, go, base], + ); + + const current: Tab | null = view.kind === "browse" ? tab : view.kind === "person" || view.kind === "face" ? "people" : "galleries"; + + const brand = ( + (e.preventDefault(), openTab("galleries"))}> + {template ? {template.owner} : {info.organization}} + Arquivo + + ); + + if (!ready) return
; + + if (!token) return ( -
- -
- ); - return ( - <> - {owner && ( -
-
- {owner} - {session} -
-
- )} -
- {owner ? ( -
-

Arquivo fotográfico

-
- ) : ( -
- Arquivo · {info.organization} -

{info.name}

- {session} -
- )} - {token ? ( - - ) : ( +
{ - write(storageKey(info.id), t, keep); - write(`${storageKey(info.id)}_name`, name, keep); + writeStored(storageKey(info.id), t, keep); + writeStored(`${storageKey(info.id)}_name`, name, keep); setViewer(name); setToken(t); }} /> - )} -
- +
+ ); + + return ( +
+
+
+ {brand} + + + +
+ +
+ +
+ {view.kind === "gallery" ? ( + go({ kind: "browse" })} onExpired={expired} onFace={(id) => go({ kind: "face", id })} onPerson={(id) => go({ kind: "person", id })} /> + ) : view.kind === "person" || view.kind === "face" ? ( + (window.history.length > 1 ? router.back() : go({ kind: "browse", tab: "people" }))} + onExpired={expired} + onFace={(id) => go({ kind: "face", id })} + onPerson={(id) => go({ kind: "person", id })} + onGallery={(id) => go({ kind: "gallery", id })} + /> + ) : ( + go({ kind: "gallery", id })} onPerson={(id) => go({ kind: "person", id })} /> + )} +
+ + +
); } -function SignIn({ info, onDone }: { info: ArchiveInfo; onDone: (token: string, name: string, keep: boolean) => void }) { +function SignIn({ info, logo, owner, onDone }: { info: ArchiveInfo; logo: string | null; owner: string; onDone: (token: string, name: string, keep: boolean) => void }) { const [state, setState] = useState(null); - const [keep, setKeep] = useState(true); const [loginUrl, setLoginUrl] = useState(null); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); + const [keep, setKeep] = useState(true); useEffect(() => { if (!state) return; @@ -257,777 +219,72 @@ function SignIn({ info, onDone }: { info: ArchiveInfo; onDone: (token: string, n setError(null); // The window opens on the click (browsers block it later); the address follows. const win = window.open("about:blank", "_blank"); - call<{ loginUrl: string; state: string }>(`/v1/archive/${info.id}/login`, null, { method: "POST" }).then( - ({ body }) => { - setLoginUrl(body.loginUrl); - setState(body.state); - if (win) win.location.href = body.loginUrl; - }, - () => { - win?.close(); - setError("Não foi possível falar com a cloud. Tenta daqui a pouco."); - }, - ).finally(() => setBusy(false)); + call<{ loginUrl: string; state: string }>(`/v1/archive/${info.id}/login`, null, { method: "POST" }) + .then( + ({ body }) => { + setLoginUrl(body.loginUrl); + setState(body.state); + if (win) win.location.href = body.loginUrl; + }, + () => { + win?.close(); + setError("Não foi possível falar com a cloud. Tenta daqui a pouco."); + }, + ) + .finally(() => setBusy(false)); }; return ( -
-

- As fotografias deste arquivo estão em {info.cloud}. Entra com a tua conta dessa cloud: vês as galerias das pastas que estão partilhadas contigo. -

- {state ? ( -
- A aguardar a autorização em {info.cloud}…{" "} - {loginUrl && ( - - Abrir a página de autorização - +
+
+
+ {logo ? {owner} : {owner}} +
+ Arquivo fotográfico +

Todas as fotos, num só sítio

+

+ As fotografias estão em {info.cloud}. Entra com a tua conta dessa cloud: vês aqui exatamente o que podes ver lá, nem mais nem menos. +

+
+ {state ? ( +

+ A aguardar a autorização em {info.cloud}…{" "} + {loginUrl && ( + + Abrir a página de autorização + + )} +

+ ) : ( + <> + + + )} + {error &&

{error}

} +

+ A tua palavra-passe só é escrita na página da cloud.{" "} + {keep + ? `Com a sessão mantida, o acesso que deres fica guardado (cifrado) para voltar a ler, de poucos em poucos minutos, o que está partilhado contigo: se te tirarem uma partilha em ${info.cloud}, deixa de aparecer aqui. Dura enquanto a usares pelo menos uma vez por mês; "Sair" revoga o acesso.` + : "Sem manter sessão, o acesso serve só para saber o que está partilhado contigo, é revogado de imediato e a sessão acaba ao fechar o separador."} +

- ) : ( - <> - - - - )} - {error &&

{error}

} -

- A tua palavra-passe é escrita apenas na página da cloud.{" "} - {keep - ? `Com a sessão mantida, o PhotoReport guarda (cifrado) o acesso que deres para voltar a ler, de poucos em poucos minutos, o que está partilhado contigo: se te tirarem uma partilha em ${info.cloud}, deixa de aparecer aqui. A sessão dura enquanto a usares pelo menos uma vez por mês; "Sair" revoga o acesso.` - : "Sem manter sessão, o acesso serve só para saber o que está partilhado contigo, é revogado de imediato e a sessão acaba ao fechar o separador."} -

+
+
); } - -type Tab = "galleries" | "people" | "teams"; - -/** - * What is shown while something loads: never a blank page. After a while it says so and offers to try again (a - * big gallery, a busy server), with the way back always there. - */ -function Loading({ onBack, backLabel = "← Voltar", onRetry }: { onBack?: () => void; backLabel?: string; onRetry?: () => void }) { - const [slow, setSlow] = useState(false); - useEffect(() => { - const timer = setTimeout(() => setSlow(true), 8000); - return () => clearTimeout(timer); - }, []); - return ( - <> - {onBack && ( -
- -
- )} -
-
- - ); -} - -/** Where the viewer is: browsing, in a gallery, on a person's photos, or on "more of this face". */ -export type View = { kind: "browse" } | { kind: "gallery"; id: string } | { kind: "person"; id: string } | { kind: "face"; id: string }; - -const fold = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase(); -const LEVEL: Record = { confirmed: "Identificado", probable: "Provável", similar: "Parecido" }; - -/** A face cut from a photo with CSS (no extra files): the box, with some room around it. */ -function FaceCrop({ src, box, aspect, size = 96, round = true }: { src: string; box: Box | null; aspect: number; size?: number; round?: boolean }) { - if (!box) return ; - const side = Math.max((box.x1 - box.x0) * aspect, box.y1 - box.y0) * 1.6; - const sw = Math.min(1, side / aspect); - const sh = Math.min(1, side); - const left = Math.max(0, Math.min(1 - sw, (box.x0 + box.x1) / 2 - sw / 2)); - const top = Math.max(0, Math.min(1 - sh, (box.y0 + box.y1) / 2 - sh / 2)); - return ( -
+
+ {who && view.kind === "person" && me?.canReview && onReview(who.id)} onExpired={onExpired} />} +
))}
+
+
{index !== null && photos[index] && ( forget(`/v1/archive/${sourceId}/`) } : undefined} extra={(p) => p.gallery ? ( <> @@ -196,3 +206,151 @@ export function PhotosOf({ ); } + +const ACTION: Record = { + confirm: "confirmou", + reject: "disse “não é”", + false_positive: "marcou falso positivo", + undo: "desfez", + recognition_off: "desligou o reconhecimento", + recognition_off_all: "desligou o reconhecimento e retirou os nomes", + recognition_on: "voltou a ligar o reconhecimento", + drop_suggestions: "retirou as sugestões", + drop_reference: "retirou a foto de referência", +}; + +/** + * Face recognition of one person, for those who edit on the cloud: the state, the way to review their faces, + * and (whoever edits the whole archive) taking back every suggestion, dropping a wrong reference photo, or + * turning their recognition off, with the names already given or not. + */ +function Editor({ sourceId, token, person, onReview, onExpired }: { sourceId: string; token: string; person: { id: string; name: string }; onReview: () => void; onExpired: () => void }) { + const [h, setH] = useState(null); + const [asking, setAsking] = useState(false); + const [removeConfirmed, setRemoveConfirmed] = useState(false); + const [busy, setBusy] = useState(false); + const [note, setNote] = useState(null); + const [attempt, setAttempt] = useState(0); + + useEffect(() => { + call(`/v1/archive/${sourceId}/people/${person.id}/history`, token).then( + ({ body }) => setH(body), + (err) => (err instanceof Unauthorised ? onExpired() : setH(null)), + ); + }, [sourceId, person.id, token, onExpired, attempt]); + + const run = async (path: string, init: RequestInit, done: string) => { + setBusy(true); + setNote(null); + try { + await call(path, token, init); + forget(`/v1/archive/${sourceId}/`); + setNote(done); + setAttempt((n) => n + 1); + } catch (err) { + if (err instanceof Unauthorised) return onExpired(); + setNote(err instanceof Forbidden ? "Só quem edita todo o arquivo na cloud pode fazer isto." : "Não foi possível. Tenta outra vez."); + } finally { + setBusy(false); + setAsking(false); + } + }; + + if (!h) return null; + const off = h.recognitionOff; + const base = `/v1/archive/${sourceId}/people/${person.id}`; + return ( + + ); +} diff --git a/apps/site/src/app/arquivo/[id]/Review.tsx b/apps/site/src/app/arquivo/[id]/Review.tsx new file mode 100644 index 0000000..02daeef --- /dev/null +++ b/apps/site/src/app/arquivo/[id]/Review.tsx @@ -0,0 +1,296 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useState } from "react"; +import { call, fold, forget, Forbidden, shortDay, Unauthorised, type Me, type PeopleList, type ReviewGroup, type ReviewResult, type ReviewStatus } from "./api"; +import { FaceCrop, Icon, Loading, PersonFace } from "./parts"; + +const STATUS: [ReviewStatus, string][] = [ + ["suggested", "Por confirmar"], + ["unnamed", "Sem nome"], + ["confirmed", "Confirmados"], + ["rejected", "Não é"], + ["ignored", "Falsos positivos"], +]; + +type Action = "confirm" | "reject" | "ignore" | "undo"; + +/** + * Faces to review in the folders the viewer edits on the cloud: one card per face group (the same person in one + * event). Confirm the suggestion, say "não é", mark a false positive, name an unnamed face, undo. Selected cards + * take the same action at once. Keys on a focused card: C confirm, N não é, F false positive. + */ +export function Review({ sourceId, token, me, person, onPerson, onExpired, onChanged }: { sourceId: string; token: string; me: Me; person: string | null; onPerson: (id: string | null) => void; onExpired: () => void; onChanged: () => void }) { + const [status, setStatus] = useState("suggested"); + const [data, setData] = useState(null); + const [busy, setBusy] = useState>(new Set()); + const [selected, setSelected] = useState>(new Set()); + const [error, setError] = useState(null); + const [attempt, setAttempt] = useState(0); + const [everyone, setEveryone] = useState(null); + + useEffect(() => { + let cancel = false; + setData(null); + setSelected(new Set()); + const params = new URLSearchParams({ status, limit: "60" }); + if (person) params.set("person", person); + call(`/v1/archive/${sourceId}/review?${params}`, token).then( + ({ body }) => !cancel && setData(body), + (err) => { + if (cancel) return; + if (err instanceof Unauthorised) onExpired(); + else setError(err instanceof Forbidden ? "Já não tens permissão de edição nestas pastas na cloud." : "Não foi possível carregar a revisão."); + }, + ); + return () => { + cancel = true; + }; + }, [sourceId, token, status, person, onExpired, attempt]); + + // Names to give an unnamed face: the people of the archive. + useEffect(() => { + if (status !== "unnamed" || everyone) return; + call(`/v1/archive/${sourceId}/people`, token).then(({ body }) => setEveryone(body.people), () => setEveryone([])); + }, [status, everyone, sourceId, token]); + + const act = useCallback( + async (ids: string[], action: Action, personId?: string) => { + setError(null); + setBusy((b) => new Set([...b, ...ids])); + const done: string[] = []; + for (const id of ids) { + try { + await call(`/v1/archive/${sourceId}/review/groups/${id}`, token, { method: "POST", body: JSON.stringify({ action, ...(personId && { personId }) }) }); + done.push(id); + } catch (err) { + if (err instanceof Unauthorised) return onExpired(); + setError(err instanceof Forbidden ? "Sem permissão de edição na cloud para todas as fotos deste rosto." : "Não foi possível guardar. Tenta outra vez."); + } + } + setBusy((b) => new Set([...b].filter((x) => !ids.includes(x)))); + setSelected(new Set()); + if (!done.length) return; + forget(`/v1/archive/${sourceId}/`); + onChanged(); + setData((cur) => { + if (!cur) return cur; + const counts = { ...cur.counts, [status]: Math.max(0, cur.counts[status] - done.length) }; + const to: ReviewStatus | null = action === "confirm" ? "confirmed" : action === "reject" ? "rejected" : action === "ignore" ? "ignored" : null; + if (to) counts[to] = (counts[to] ?? 0) + done.length; + return { ...cur, counts, groups: cur.groups.filter((g) => !done.includes(g.id)) }; + }); + }, + [sourceId, token, status, onExpired, onChanged], + ); + + const toggle = (id: string) => setSelected((s) => (s.has(id) ? new Set([...s].filter((x) => x !== id)) : new Set([...s, id]))); + const chosen = data?.people.find((p) => p.id === person) ?? null; + const ids = [...selected]; + + return ( +
+
+
+

+ Rever rostos +

+ Confirma quem está em cada foto. Só aparecem as pastas onde tens permissão de edição na cloud. +
+ {chosen && ( + + )} +
+ +
+ {STATUS.map(([s, label]) => ( + + ))} +
+ + {error && ( +

+ {error}{" "} + +

+ )} + +
+ {data && data.people.length > 0 && ( + + )} +
+ {data && data.people.length > 0 && ( +
+ + {data.people.map((p) => ( + + ))} +
+ )} + {!data && !error && } + {data && data.groups.length === 0 &&

{status === "suggested" ? "Nada por confirmar aqui. Bom trabalho." : "Nada nesta lista."}

} +
+ {data?.groups.map((g) => ( + toggle(g.id)} onAct={(a, p) => void act([g.id], a, p)} everyone={everyone} /> + ))} +
+
+
+ + {ids.length > 0 && ( +
+ {ids.length} selecionados + + {status === "suggested" && ( + + )} + {(status === "suggested" || status === "confirmed") && ( + + )} + {status !== "ignored" && status !== "rejected" && ( + + )} + {(status === "ignored" || status === "rejected") && ( + + )} + +
+ )} + {me.canManagePeople && chosen && ( +

+ Para desligar o reconhecimento de {chosen.name} ou retirar todas as sugestões, abre a página da pessoa. +

+ )} +
+ ); +} + +function Card({ + g, + status, + busy, + selected, + onToggle, + onAct, + everyone, +}: { + g: ReviewGroup; + status: ReviewStatus; + busy: boolean; + selected: boolean; + onToggle: () => void; + onAct: (a: Action, personId?: string) => void; + everyone: PeopleList["people"] | null; +}) { + const [q, setQ] = useState(""); + const who = g.person ?? g.suggested; + const [first, ...rest] = g.faces; + const matches = useMemo(() => (q.trim().length < 2 ? [] : (everyone ?? []).filter((p) => fold(`${p.name} ${p.club ?? ""} ${p.number ?? ""}`).includes(fold(q.trim()))).slice(0, 6)), [q, everyone]); + const onKey = (e: React.KeyboardEvent) => { + if (busy || e.target instanceof HTMLInputElement) return; + const k = e.key.toLowerCase(); + if (k === "c" && status === "suggested") onAct("confirm"); + else if (k === "n" && (status === "suggested" || status === "confirmed")) onAct("reject"); + else if (k === "f" && status !== "ignored") onAct("ignore"); + else if (k === "x") onToggle(); + else return; + e.preventDefault(); + }; + return ( +
+ +
+ {who ? who.name : "Sem nome"} + + {[who?.number && `nº ${who.number}`, who?.club, `${g.photos} ${g.photos === 1 ? "foto" : "fotos"}`].filter(Boolean).join(" · ")} + + {g.event && {[g.event.title, g.event.startsAt ? shortDay.format(new Date(g.event.startsAt)) : null].filter(Boolean).join(" · ")}} + {g.notThem.length > 0 && Não é: {g.notThem.map((n) => n.name).join(", ")}} + {status === "unnamed" && ( + + setQ(e.target.value)} placeholder="Quem é? Nome ou número" aria-label="Quem é?" /> + {matches.map((p) => ( + + ))} + + )} +
+
+ {status === "suggested" && ( + + )} + {(status === "suggested" || status === "confirmed") && ( + + )} + {status !== "ignored" && status !== "rejected" && ( + + )} + {(status === "ignored" || status === "rejected") && ( + + )} +
+
+ ); +} diff --git a/apps/site/src/app/arquivo/[id]/api.ts b/apps/site/src/app/arquivo/[id]/api.ts index b4c3240..4524366 100644 --- a/apps/site/src/app/arquivo/[id]/api.ts +++ b/apps/site/src/app/arquivo/[id]/api.ts @@ -26,6 +26,8 @@ export interface GalleryCard { export interface PhotoFace { id: string; + /** The face's group (one per person per event): what a review acts on. */ + groupId?: string | null; box: Box | null; person: { id: string; name: string } | null; level: "confirmed" | "probable" | null; @@ -118,7 +120,57 @@ export interface PhotosOfResult { photos: ArchivePhoto[]; } +/** What this viewer may do, from their rights on the cloud. */ +export interface Me { + name: string; + /** Some folder shared with them with edit rights: they review its faces. */ + canReview: boolean; + /** They edit the whole archive: they may act on a person as a whole. */ + canManagePeople: boolean; + /** Suggestions waiting in their folders. */ + pending: number; +} + +export type ReviewStatus = "suggested" | "unnamed" | "confirmed" | "rejected" | "ignored"; + +export interface ReviewPerson { + id: string; + name: string; + club: string | null; + number: string | null; + reference: string | null; + recognitionOff?: boolean; +} + +export interface ReviewGroup { + id: string; + size: number; + photos: number; + score: number | null; + person: ReviewPerson | null; + suggested: ReviewPerson | null; + ignored: boolean; + notThem: { id: string; name: string; by: string }[]; + event: { title: string; startsAt: string | null } | null; + faces: { id: string; photoId: string; src: string; box: Box | null; aspect: number }[]; +} + +export interface ReviewResult { + status: ReviewStatus; + counts: Record; + people: (ReviewPerson & { waiting: number })[]; + groups: ReviewGroup[]; +} + +export interface PersonHistory { + recognitionOff: { at: string; by: string | null } | null; + hasReference: boolean; + canManage: boolean; + actions: { at: string; viewer: string; action: string; faces: number }[]; +} + export class Unauthorised extends Error {} +export class Forbidden extends Error {} /** * Answers to GETs, kept for the page's life: going back to a list, or switching tabs, shows it at once and reads @@ -136,6 +188,7 @@ export async function call(path: string, token: string | null, init: RequestI cache.clear(); throw new Unauthorised(); } + if (res.status === 403) throw new Forbidden(); if (!res.ok) throw new Error(`${res.status}`); if (res.status === 204) return { status: 204, body: undefined as T }; return { status: res.status, body: (await res.json()) as T }; @@ -217,3 +270,9 @@ export function initials(name: string | null | undefined): string { .map((w) => w[0]!.toUpperCase()) .join(""); } + +/** Forgets kept answers (after a review changes what lists show). */ +export function forget(prefix?: string) { + if (!prefix) return cache.clear(); + for (const k of [...cache.keys()]) if (k.includes(prefix)) cache.delete(k); +} diff --git a/apps/site/src/app/arquivo/[id]/archive.css b/apps/site/src/app/arquivo/[id]/archive.css index c5c3ea7..fa42f81 100644 --- a/apps/site/src/app/arquivo/[id]/archive.css +++ b/apps/site/src/app/arquivo/[id]/archive.css @@ -1490,6 +1490,314 @@ white-space: nowrap; } +/* Face review */ +.arq-review { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + gap: 12px; +} +.arq-rcard { + display: flex; + flex-direction: column; + border-radius: 12px; + overflow: hidden; + background: var(--card); + box-shadow: 0 0 0 1px var(--line); +} +.arq-rcard.on { + box-shadow: 0 0 0 3px var(--primary); +} +.arq-rcard.busy { + opacity: 0.5; + pointer-events: none; +} +.arq-rfaces { + position: relative; + display: block; + width: 100%; + aspect-ratio: 1; + padding: 0; + border: 0; + background: var(--chip); + cursor: pointer; +} +.arq-rfaces > .arq-crop { + width: 100% !important; + height: 100% !important; +} +.arq-check { + position: absolute; + left: 8px; + top: 8px; + width: 26px; + height: 26px; + border-radius: 7px; + background: rgba(0, 0, 0, 0.35); + box-shadow: inset 0 0 0 2px #ffffff; + color: #ffffff; + font-weight: 700; + display: flex; + align-items: center; + justify-content: center; +} +.arq-rcard.on .arq-check { + background: var(--primary); +} +.arq-conf { + position: absolute; + right: 8px; + top: 8px; +} +.arq-more-faces { + position: absolute; + left: 8px; + bottom: 8px; + display: flex; + gap: 4px; +} +.arq-more-faces .arq-crop { + border-radius: 6px; + box-shadow: 0 0 0 2px #ffffff; +} +.arq-rbody { + padding: 10px 12px; + display: flex; + flex-direction: column; + gap: 2px; + flex: 1 1 auto; +} +.arq-rbody strong { + font-size: 16px; + line-height: 1.2; +} +.arq-rbody small { + font-size: 13px; + color: var(--muted); +} +.arq-name-it { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 6px; +} +.arq-name-it input { + width: 100%; + height: 40px; + padding: 0 12px; + border-radius: 999px; + border: 1px solid var(--line); + background: var(--card); +} +.arq-ractions { + display: grid; + grid-auto-flow: column; + grid-auto-columns: minmax(0, 1fr); + border-top: 1px solid var(--line); +} +.arq-ractions button { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 2px; + min-height: 52px; + padding: 4px; + border: 0; + border-left: 1px solid var(--line); + background: var(--card); + color: var(--ink); + font-size: 12px; + font-weight: 700; + cursor: pointer; +} +.arq-ractions button:first-child { + border-left: 0; +} +.arq-ractions button.ok { + background: #e3f6ea; + color: #11592d; +} +.arq-ractions button.bad { + background: #fdecea; + color: #9b2216; +} +.arq-btn.ok { + background: #3ddc84; + color: #062814; +} +.arq-btn.bad { + color: #ffb4a8; +} +.arq-btn.danger { + background: #b42318; + color: #ffffff; +} +.arq-bulk { + position: sticky; + bottom: 12px; + z-index: 15; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + padding: 8px 8px 8px 18px; + border-radius: 999px; + background: var(--hero); + color: var(--hero-ink); + font-weight: 700; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25); +} +.arq-alert { + margin: 0; + padding: 12px 16px; + border-radius: var(--r); + background: #fdecea; + color: #7a1a10; +} +.arq-editor { + flex: 0 0 340px; + display: flex; + flex-direction: column; + gap: 14px; +} +.arq-editor .arq-box { + padding: 18px; + border-radius: var(--r); + background: var(--card); + box-shadow: 0 0 0 1px var(--line); + display: flex; + flex-direction: column; + gap: 12px; +} +.arq-editor h2 { + margin: 0; + font-size: 26px; +} +.arq-editor .arq-danger { + border-top: 1px solid var(--line); + padding-top: 12px; + display: flex; + flex-direction: column; + gap: 8px; +} +.arq-editor ul { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 6px; + font-size: 14px; +} +.arq-editor li span { + color: var(--muted); + margin-right: 6px; +} +.arq-state { + align-self: flex-start; + padding: 3px 10px; + border-radius: 999px; + font-size: 12px; + font-weight: 700; + background: #e3f6ea; + color: #11592d; +} +.arq-state.off { + background: #fff4d6; + color: #4a3800; +} +.arq-scrim { + position: fixed; + inset: 0; + z-index: 60; + background: rgba(8, 10, 14, 0.6); + display: flex; + align-items: center; + justify-content: center; + padding: 24px; +} +.arq-dialog { + width: 100%; + max-width: 520px; + padding: 24px; + border-radius: 16px; + background: var(--card); + color: var(--ink); + display: flex; + flex-direction: column; + gap: 14px; +} +.arq-dialog h2 { + margin: 0; + font-size: 30px; +} +.arq-dialog ul { + margin: 0; + padding-left: 20px; + color: var(--muted); + display: flex; + flex-direction: column; + gap: 6px; +} +.arq-dialog .arq-keep { + padding: 10px 12px; + border-radius: 10px; + background: var(--panel); +} +.arq-lb-actions { + display: flex; + flex-wrap: wrap; + gap: 6px; +} +.arq-lb-actions button { + min-height: 36px; + padding: 0 12px; + border-radius: 999px; + border: 1px solid rgba(255, 255, 255, 0.35); + background: transparent; + color: #ffffff; + font-weight: 700; + font-size: 13px; + cursor: pointer; +} +.arq-lb-actions button.ok { + background: #3ddc84; + border-color: #3ddc84; + color: #062814; +} +.arq-lb-actions button.bad { + color: #ffb4a8; + border-color: rgba(255, 180, 168, 0.45); +} +@media (max-width: 1023px) { + .arq-editor { + flex: 1 1 auto; + width: 100%; + } + .arq-review { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } +} +@media (max-width: 639px) { + .arq-review { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px; + } + .arq-ractions button span { + display: none; + } + .arq-bulk { + bottom: 72px; + } + .arq-scrim { + align-items: flex-end; + padding: 0; + } + .arq-dialog { + border-radius: 16px 16px 0 0; + } +} + /* Tablet */ @media (max-width: 1023px) { .arq-cards, diff --git a/apps/site/src/app/arquivo/[id]/page.tsx b/apps/site/src/app/arquivo/[id]/page.tsx index 80db121..a0ac892 100644 --- a/apps/site/src/app/arquivo/[id]/page.tsx +++ b/apps/site/src/app/arquivo/[id]/page.tsx @@ -4,7 +4,7 @@ import { load } from "./load"; export type { ArchiveInfo } from "./load"; -type Params = { params: Promise<{ id: string }>; searchParams: Promise<{ t?: string }> }; +type Params = { params: Promise<{ id: string }>; searchParams: Promise<{ t?: string; p?: string }> }; export async function generateMetadata({ params }: Params): Promise { const info = await load((await params).id); @@ -16,7 +16,8 @@ export async function generateMetadata({ params }: Params): Promise { * authorise), and see the galleries of the folders shared with them. */ export default async function ArchivePage({ params, searchParams }: Params) { - const { t } = await searchParams; - const tab = t === "pessoas" ? "people" : t === "equipas" ? "teams" : "galleries"; - return ; + const { t, p } = await searchParams; + const tab = t === "pessoas" ? "people" : t === "equipas" ? "teams" : t === "rever" ? "review" : "galleries"; + const person = p && /^[0-9a-f-]{36}$/i.test(p) ? p : undefined; + return ; } diff --git a/apps/site/src/app/arquivo/[id]/parts.tsx b/apps/site/src/app/arquivo/[id]/parts.tsx index 1ae3ac2..0634a7d 100644 --- a/apps/site/src/app/arquivo/[id]/parts.tsx +++ b/apps/site/src/app/arquivo/[id]/parts.tsx @@ -92,6 +92,9 @@ const PATHS = { close: "M6 6l12 12M18 6L6 18", cloud: "M7 18h10a4 4 0 00.5-8 6 6 0 00-11.4 1.5A3.3 3.3 0 007 18z", download: "M12 4v11M7 10l5 5 5-5M5 20h14", + check: "M5 12l5 5 9-10", + ban: "M12 20a8 8 0 100-16 8 8 0 000 16zM6.5 6.5l11 11", + review: "M4 8V5h3M17 5h3v3M20 16v3h-3M7 19H4v-3M9 10h.01M15 10h.01M9 15c2 1.5 4 1.5 6 0", } as const; export function Icon({ name, size = 20 }: { name: keyof typeof PATHS; size?: number }) { diff --git a/docs/archive.md b/docs/archive.md index 1d5a425..d9a1852 100644 --- a/docs/archive.md +++ b/docs/archive.md @@ -117,10 +117,14 @@ played games. ## Viewers (site) -- Each archive can wear its owner's look (`cloud_sources.look`): `liga` (Liga Portugal: night blue, orange, - condensed capitals) or `fpa` (Federação de Andebol: light grey, red bar, Open Sans capitals); none is - PhotoReport's. Set from the source's name or folder when connected, changed in the app (Arquivo → "Aspeto do - site"). Colours and type only, no marks or logos of theirs (`globals.css`, `[data-look]`). +- 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/` (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 @@ -162,3 +166,21 @@ face). Nothing outside the folders shared with the viewer is compared or shown. 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. -- 2.47.3 From 16c23c3eb8a242135d8661665eb944b150608f37 Mon Sep 17 00:00:00 2001 From: spark Date: Sun, 18 Oct 2026 23:09:23 +0000 Subject: [PATCH 5/6] Fix the archive's buttons, sidebars and narrow screens. The archive's resets had more weight than the component classes, so primary buttons took the text colour of their parent; they are weightless now (:where). Faces in the review sidebar stretched; stacked columns on phone and tablet grew to their content's width. Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1 --- apps/site/src/app/arquivo/[id]/archive.css | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/apps/site/src/app/arquivo/[id]/archive.css b/apps/site/src/app/arquivo/[id]/archive.css index fa42f81..5b038aa 100644 --- a/apps/site/src/app/arquivo/[id]/archive.css +++ b/apps/site/src/app/arquivo/[id]/archive.css @@ -130,13 +130,14 @@ .arq *::after { box-sizing: border-box; } -.arq button, -.arq input, -.arq select { +/* Resets without weight (:where), so every component class below wins over them. */ +:where(.arq) button, +:where(.arq) input, +:where(.arq) select { font: inherit; color: inherit; } -.arq a { +:where(.arq) a { color: inherit; } .arq :focus-visible { @@ -869,6 +870,8 @@ gap: 8px; } .arq-faces-row { + flex: 1 1 100%; + min-width: 0; display: flex; gap: 8px; overflow-x: auto; @@ -967,8 +970,9 @@ text-align: left; cursor: pointer; } -.arq-aside button span:first-child { +.arq-aside button > span:first-child { flex: 1 1 auto; + min-width: 0; } .arq-aside button[aria-pressed="true"] { background: var(--chip-on); @@ -1820,7 +1824,9 @@ display: none; } .arq-split { - flex-direction: column; + flex-direction: column !important; + flex-wrap: nowrap !important; + align-items: stretch; } .arq-aside { display: none; @@ -1956,8 +1962,8 @@ top: 60px; } .arq-sticky .arq-wrap { - flex-wrap: nowrap; - overflow-x: auto; + padding-top: 8px; + padding-bottom: 8px; } .arq-match { gap: 10px; -- 2.47.3 From 56f8660667cfd86d3adadc3813115a5d66413ec2 Mon Sep 17 00:00:00 2001 From: spark Date: Sun, 18 Oct 2026 23:27:33 +0000 Subject: [PATCH 6/6] Let archive viewers download at web size, keep the cloud for editors, and serve an archive at its own address. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Downloads: one photo, a selection (up to 100) or a whole gallery (ZIP, up to 1000) at 2048 px with metadata, through a short-lived signed link. Gallery and large view get the buttons. - The cloud is named only to those who edit the folder there (a small "originals" link); sign-in no longer mentions it. - cloud_sources.hostname: the site's middleware serves that archive at the root of its own host; Caddy asks /v1/archive/host before getting a certificate. Set in the app (Endereço próprio). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1 --- .../migration.sql | 3 + apps/api/prisma/schema.prisma | 2 + apps/api/src/app.ts | 2 +- apps/api/src/archive/downloads.ts | 168 ++++++++++++++++++ apps/api/src/archive/routes.ts | 23 ++- apps/api/src/archive/viewer.ts | 30 +++- apps/api/test/archive.test.ts | 45 +++++ apps/app/src/i18n.ts | 5 + apps/app/src/pages/ArchivePage.tsx | 28 ++- .../site/src/app/arquivo/[id]/ArchiveView.tsx | 30 ++-- apps/site/src/app/arquivo/[id]/Gallery.tsx | 94 ++++++++-- apps/site/src/app/arquivo/[id]/Lightbox.tsx | 12 +- apps/site/src/app/arquivo/[id]/PhotosOf.tsx | 3 +- apps/site/src/app/arquivo/[id]/api.ts | 22 ++- apps/site/src/app/arquivo/[id]/archive.css | 41 +++++ apps/site/src/app/arquivo/[id]/frame.tsx | 5 +- apps/site/src/app/arquivo/[id]/load.ts | 4 + apps/site/src/middleware.ts | 43 ++++- docs/archive.md | 19 +- infra/proxy/Caddyfile.example | 18 ++ packages/sdk/src/client.ts | 2 +- packages/sdk/src/types.ts | 2 + 22 files changed, 556 insertions(+), 45 deletions(-) create mode 100644 apps/api/prisma/migrations/20261019090000_archive_hostname/migration.sql create mode 100644 apps/api/src/archive/downloads.ts diff --git a/apps/api/prisma/migrations/20261019090000_archive_hostname/migration.sql b/apps/api/prisma/migrations/20261019090000_archive_hostname/migration.sql new file mode 100644 index 0000000..e473115 --- /dev/null +++ b/apps/api/prisma/migrations/20261019090000_archive_hostname/migration.sql @@ -0,0 +1,3 @@ +-- The archive's own address: the public site serves it at the root of that host. +ALTER TABLE "cloud_sources" ADD COLUMN "hostname" TEXT; +CREATE UNIQUE INDEX "cloud_sources_hostname_key" ON "cloud_sources"("hostname"); diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 24f3bfa..36475e7 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -1621,6 +1621,8 @@ model CloudSource { status String @default("LOGIN") /// How the archive's site looks: "liga" (Liga Portugal), "fpa" (Federação de Andebol), or null (PhotoReport). look String? + /// The archive's own address ("arquivo.ligaportugal.pt"): the site serves this archive at its root there. + hostname String? @unique /// Nextcloud login flow v2: where to poll for the app password while status is LOGIN (sealed token). loginPoll String? @map("login_poll") loginExpires DateTime? @map("login_expires") diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index ac52867..34bcb16 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -145,7 +145,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give await registerArchiveRoutes(app, { db, sessions, archive, storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9 }); // The API never runs the face engine: it confirms and merges groups; the worker detects and groups. const faces = new FaceService({ db, storage, broadcaster, log: app.log }); - await registerArchiveViewerRoutes(app, { db, secrets, signer, archive, tokens: new ViewerTokens(config.JWT_SECRET), faces, fetchImpl }); + await registerArchiveViewerRoutes(app, { db, secrets, signer, archive, tokens: new ViewerTokens(config.JWT_SECRET), faces, storage, secret: config.JWT_SECRET, fetchImpl }); await registerCompositionRoutes(app, { db, sessions, storage, storageRoot: config.STORAGE_ROOT }); await registerSearchRoutes(app, { db, sessions, signer }); await registerFtpRoutes(app, { db, sessions, ingestRoot: config.INGEST_ROOT, hookSecret: config.SFTPGO_HOOK_KEY }); diff --git a/apps/api/src/archive/downloads.ts b/apps/api/src/archive/downloads.ts new file mode 100644 index 0000000..5984411 --- /dev/null +++ b/apps/api/src/archive/downloads.ts @@ -0,0 +1,168 @@ +import { createHmac, timingSafeEqual } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { createReadStream } from "node:fs"; +import type { FastifyInstance, FastifyRequest } from "fastify"; +import sharp from "sharp"; +import { eventName } from "@photoreport/metadata"; +import { z } from "zod"; +import type { Db } from "../db.js"; +import { AppError, badRequest, notFound } from "../lib/errors.js"; +import { zipStream, ZipTooLarge, type ZipEntry } from "../lib/zip.js"; +import type { LocalStorage } from "../storage/storage.js"; +import type { Viewer } from "./viewer.js"; + +/** + * Downloads for archive viewers: photos at web size (2048 px on the long side, with their metadata: credits, + * caption, names), one as a JPEG, several as a ZIP. Never the full-size original: whoever needs it edits on the + * cloud and has its link there. + * + * The browser fetches a download by a plain link, so the page first asks for one (`POST …/downloads`, with the + * viewer's session); the link carries a short-lived signed ticket naming the photos, checked when it is used. + */ +const WEB_SIZE = 2048; +const TICKET_TTL_SEC = 10 * 60; +/** A gallery at once (named by its folder in the link), or up to this many photos picked one by one. */ +const MAX_PHOTOS = 1000; +const MAX_PICKED = 100; + +interface Deps { + db: Db; + storage: LocalStorage; + secret: string; + viewerOf: (req: FastifyRequest, sourceId?: string) => Viewer; + visibleFolders: (v: Viewer) => Promise; +} + +const SourceParams = z.object({ sourceId: z.uuid() }); +const Ask = z.union([z.object({ photoIds: z.array(z.uuid()).min(1).max(MAX_PICKED) }), z.object({ folderId: z.uuid() })]); +const TicketQuery = z.object({ t: z.string().min(10).max(20_000) }); + +interface Ticket { + s: string; + /** Photos picked, or (`f`) every photo of a gallery folder. */ + ids?: string[]; + f?: string; + /** Name of the ZIP (a gallery's title). */ + n: string | null; + exp: number; +} + +export async function registerArchiveDownloadRoutes(app: FastifyInstance, deps: Deps) { + const { db, storage, viewerOf, visibleFolders } = deps; + const key = createHmac("sha256", deps.secret).update("photoreport:archive-download").digest(); + const mac = (body: string) => createHmac("sha256", key).update(body).digest("base64url"); + const sign = (t: Omit) => { + const body = Buffer.from(JSON.stringify({ ...t, exp: Math.floor(Date.now() / 1000) + TICKET_TTL_SEC })).toString("base64url"); + return `${body}.${mac(body)}`; + }; + const open = (ticket: string): Ticket | null => { + const [body, sig] = ticket.split("."); + if (!body || !sig) return null; + const want = Buffer.from(mac(body), "base64url"); + const got = Buffer.from(sig, "base64url"); + if (got.length !== want.length || !timingSafeEqual(got, want)) return null; + try { + const t = JSON.parse(Buffer.from(body, "base64url").toString("utf8")) as Ticket; + return t.exp * 1000 > Date.now() ? t : null; + } catch { + return null; + } + }; + + /** A link to download photos the viewer may see: some photos, or a whole gallery. */ + app.post("/v1/archive/:sourceId/downloads", { config: { rateLimit: { max: 60, timeWindow: "1 minute" } } }, async (req) => { + const { sourceId } = SourceParams.parse(req.params); + const v = viewerOf(req, sourceId); + const ask = Ask.parse(req.body); + const visible = await visibleFolders(v); + const scope = visible === "all" ? {} : { folderId: { in: visible } }; + let name: string | null = null; + let ids: string[] = []; + if ("folderId" in ask) { + if (visible !== "all" && !visible.includes(ask.folderId)) throw notFound("gallery_not_found"); + const folder = await db.cloudFolder.findFirst({ where: { id: ask.folderId, sourceId }, include: { event: true } }); + if (!folder) throw notFound("gallery_not_found"); + name = folder.event ? eventName(folder.event) : (folder.path.split("/").pop() ?? null); + const n = await db.cloudFile.count({ where: { folderId: folder.id, status: "DONE", photoId: { not: null } } }); + if (n > MAX_PHOTOS) throw new AppError(413, "too_many_photos"); + if (!n) throw notFound("photo_not_found"); + return { url: `/v1/archive/dl?t=${sign({ s: sourceId, f: folder.id, n: name })}`, photos: n }; + } else { + const files = await db.cloudFile.findMany({ where: { sourceId, status: "DONE", photoId: { in: ask.photoIds }, ...scope }, select: { photoId: true }, distinct: ["photoId"] }); + ids = ask.photoIds.filter((id) => files.some((f) => f.photoId === id)); + } + if (!ids.length) throw notFound("photo_not_found"); + return { url: `/v1/archive/dl?t=${sign({ s: sourceId, ids, n: name })}`, photos: ids.length }; + }); + + /** The download itself: one JPEG, or a ZIP. */ + app.get("/v1/archive/dl", async (req, reply) => { + const { t: ticket } = TicketQuery.parse(req.query); + const t = open(ticket); + if (!t) throw notFound("download_expired"); + const ids = t.f + ? (await db.cloudFile.findMany({ where: { folderId: t.f, sourceId: t.s, status: "DONE", photoId: { not: null } }, orderBy: { path: "asc" }, select: { photoId: true }, take: MAX_PHOTOS })).map((f) => f.photoId!) + : (t.ids ?? []); + const photos = await db.photo.findMany({ + where: { id: { in: ids }, cloudFiles: { some: { sourceId: t.s } } }, + select: { id: true, storageKey: true, originalName: true, originalStored: true, width: true, height: true, capturedAt: true }, + }); + if (!photos.length) throw notFound("photo_not_found"); + const order = new Map(ids.map((id, i) => [id, i])); + photos.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0)); + const dir = await mkdtemp(path.join(tmpdir(), "pr-archive-dl-")); + const cleanup = () => void rm(dir, { recursive: true, force: true }); + try { + // The archive keeps a 2048 px copy with its metadata; a photo with its full original is made web size here. + const files: ZipEntry[] = []; + for (const p of photos) { + const kept = storage.resolve(p.storageKey); + const big = p.originalStored || Math.max(p.width ?? 0, p.height ?? 0) > WEB_SIZE; + let file = kept; + if (big) { + file = path.join(dir, `${p.id}.jpg`); + await sharp(kept).resize(WEB_SIZE, WEB_SIZE, { fit: "inside", withoutEnlargement: true }).keepMetadata().jpeg({ quality: 90 }).toFile(file); + } + const name = p.originalName.replace(/\.[^.]+$/, "") + ".jpg"; + files.push({ name, path: file, ...(p.capturedAt && { modified: p.capturedAt }) }); + } + if (files.length === 1) { + const [only] = files; + const stream = createReadStream(only!.path); + stream.on("close", cleanup); + return reply + .header("content-type", "image/jpeg") + .header("content-disposition", disposition(only!.name)) + .header("cache-control", "private, no-store") + .send(stream); + } + let zip; + try { + zip = await zipStream(files); + } catch (err) { + if (err instanceof ZipTooLarge) throw new AppError(413, "zip_too_large"); + throw err; + } + zip.stream.on("close", cleanup); + zip.stream.on("end", cleanup); + return reply + .header("content-type", "application/zip") + .header("content-length", String(zip.size)) + .header("content-disposition", disposition(`${t.n ?? "fotografias"}.zip`)) + .header("cache-control", "private, no-store") + .send(zip.stream); + } catch (err) { + cleanup(); + if (err instanceof AppError) throw err; + throw badRequest("download_failed", (err as Error).message); + } + }); +} + +/** `attachment` with a plain ASCII name and the real one (accents) for browsers that read it. */ +function disposition(name: string): string { + const ascii = name.normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^\w.\- ]+/g, "_"); + return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`; +} diff --git a/apps/api/src/archive/routes.ts b/apps/api/src/archive/routes.ts index 55187ff..4ce4d9b 100644 --- a/apps/api/src/archive/routes.ts +++ b/apps/api/src/archive/routes.ts @@ -6,7 +6,7 @@ import type { SessionService } from "../auth/sessions.js"; import type { Db } from "../db.js"; import { NextcloudError } from "../delivery/nextcloud.js"; import type { CloudSource } from "../generated/prisma/client.js"; -import { AppError, badRequest, notFound } from "../lib/errors.js"; +import { AppError, badRequest, conflict, notFound } from "../lib/errors.js"; import { ARCHIVE_LOOKS, ArchiveRejected, BYTES_PER_PHOTO, diskSpace, normalisePath, type ArchiveService, type RematchReport } from "./service.js"; const OrgParams = z.object({ orgId: z.uuid() }); @@ -23,6 +23,16 @@ const Update = z.object({ rootPath: z.string().trim().min(1).max(500).optional(), paused: z.boolean().optional(), look: z.enum(ARCHIVE_LOOKS).nullable().optional(), + /** The archive's own address (a host name, no scheme or path); empty or null takes it away. */ + hostname: z + .string() + .trim() + .toLowerCase() + .max(253) + .transform((h) => h.replace(/^https?:\/\//, "").replace(/\/.*$/, "").replace(/\.$/, "")) + .refine((h) => h === "" || /^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(h), "host name") + .nullable() + .optional(), }); const FolderQuery = z.object({ /** games: official games; named: games known only by their folder; events (or folders): not games. */ @@ -78,6 +88,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db baseUrl: s.baseUrl, rootPath: s.rootPath, look: s.look, + hostname: s.hostname, account: s.username || null, status: s.status, lastScanAt: s.lastScanAt, @@ -137,6 +148,15 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db const body = Update.parse(req.body); const current = await loadSource(req, sourceId, "ADMIN"); const status = body.paused === undefined ? undefined : body.paused ? "PAUSED" : current.secretEnc ? "READY" : "LOGIN"; + const hostname = body.hostname === undefined ? undefined : body.hostname || null; + if (hostname) { + // One address, one thing: not another archive's, nor a public site's (the site would not know which to show). + const [archiveThere, siteThere] = await Promise.all([ + db.cloudSource.findFirst({ where: { hostname, id: { not: sourceId } }, select: { id: true } }), + db.site.findUnique({ where: { domain: hostname }, select: { id: true } }), + ]); + if (archiveThere || siteThere) throw conflict("hostname_taken"); + } const source = await db.cloudSource.update({ where: { id: sourceId }, data: { @@ -145,6 +165,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db ...(status && { status }), ...(status === "READY" && { nextScanAt: new Date() }), ...(body.look !== undefined && { look: body.look }), + ...(hostname !== undefined && { hostname }), }, }); return serialize(source, (await counts([source.id])).get(source.id)); diff --git a/apps/api/src/archive/viewer.ts b/apps/api/src/archive/viewer.ts index 763128b..e288650 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -7,11 +7,12 @@ import type { Db } from "../db.js"; import { NextcloudError } from "../delivery/nextcloud.js"; import type { SecretBox } from "../delivery/secrets.js"; import { AppError, badRequest, notFound, unauthorized } from "../lib/errors.js"; -import type { UrlSigner } from "../storage/storage.js"; +import type { LocalStorage, UrlSigner } from "../storage/storage.js"; import { CloudClient, pollLogin, startLogin } from "./nextcloud.js"; import { canonicalTeam, describeFolder } from "./match.js"; import type { FaceService } from "../faces/service.js"; import { faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js"; +import { registerArchiveDownloadRoutes } from "./downloads.js"; import { registerArchiveReviewRoutes } from "./review.js"; import type { ArchiveService } from "./service.js"; @@ -95,7 +96,7 @@ const ListQuery = z.object({ export async function registerArchiveViewerRoutes( app: FastifyInstance, - deps: { db: Db; secrets: SecretBox | undefined; signer: UrlSigner; archive: ArchiveService; tokens: ViewerTokens; faces: FaceService; fetchImpl?: typeof fetch | undefined }, + deps: { db: Db; secrets: SecretBox | undefined; signer: UrlSigner; archive: ArchiveService; tokens: ViewerTokens; faces: FaceService; storage: LocalStorage; secret: string; fetchImpl?: typeof fetch | undefined }, ) { const { db, signer, tokens } = deps; const fetchImpl = deps.fetchImpl ?? fetch; @@ -285,7 +286,22 @@ export async function registerArchiveViewerRoutes( const { sourceId } = SourceParams.parse(req.params); const source = await db.cloudSource.findUnique({ where: { id: sourceId }, include: { organization: { select: { name: true } } } }); if (!source || !source.secretEnc) throw notFound("archive_not_found"); - return { id: source.id, name: source.name, cloud: new URL(source.baseUrl).host, organization: source.organization.name, look: source.look }; + return { id: source.id, name: source.name, cloud: new URL(source.baseUrl).host, organization: source.organization.name, look: source.look, hostname: source.hostname }; + }); + + /** + * Which archive an address of its own shows (the site asks, to serve it at the root there). `?domain=` answers + * the proxy's question before it gets a certificate for a host (Caddy's on-demand TLS): 200 only for an + * archive's address. + */ + app.get("/v1/archive/host", { config: { rateLimit: { max: 600, timeWindow: "1 minute" } } }, async (req, reply) => { + const raw = (req.query as { domain?: string; host?: string }).domain ?? (req.query as { host?: string }).host ?? ""; + const hostname = raw.trim().toLowerCase().replace(/:\d+$/, "").replace(/\.$/, ""); + if (!hostname || hostname.length > 253) throw notFound("archive_not_found"); + const source = await db.cloudSource.findUnique({ where: { hostname }, select: { id: true, secretEnc: true } }); + if (!source || !source.secretEnc) throw notFound("archive_not_found"); + reply.header("cache-control", "public, max-age=60"); + return { id: source.id }; }); /** Starts the viewer's sign-in on the cloud: they open `loginUrl`, the page polls with `state`. */ @@ -483,6 +499,9 @@ export async function registerArchiveViewerRoutes( if (visible !== "all" && !visible.includes(folderId)) throw notFound("gallery_not_found"); const folder = await db.cloudFolder.findFirst({ where: { id: folderId, sourceId: v.s }, include: { event: true, source: { select: { baseUrl: true } } } }); if (!folder) throw notFound("gallery_not_found"); + // Links to the cloud only for those who edit there; the others need not know where the photos live. + const editable = await editableFolders(v); + const onCloud = editable === "all" || editable.includes(folderId); const where = { folderId, status: "DONE" as const, @@ -557,7 +576,7 @@ export async function registerArchiveViewerRoutes( competition: folder.event?.competition ?? null, startsAt: folder.event?.startsAt ?? null, /** The folder on the cloud (opens for those it is shared with). */ - cloudUrl: `${base}/f/${folder.fileId}`, + cloudUrl: onCloud ? `${base}/f/${folder.fileId}` : null, total, people: named.map((p) => ({ id: p.id, name: p.name, count: Number(p.count), face: faceOf.get(p.id) ?? null })), /** Everyone named in this game, so a gallery can offer them even when this part has only some. */ @@ -571,7 +590,7 @@ export async function registerArchiveViewerRoutes( capturedAt: f.photo!.capturedAt, thumb: signer.url(f.photo!.id, "thumb", f.photo!.renderedSeq), preview: signer.url(f.photo!.id, "preview", f.photo!.renderedSeq), - cloudUrl: `${base}/f/${f.fileId}`, + ...(onCloud && { cloudUrl: `${base}/f/${f.fileId}` }), })), }; }); @@ -593,6 +612,7 @@ export async function registerArchiveViewerRoutes( await registerArchivePeopleRoutes(app, { db, signer, viewerOf, visibleFolders }); await registerArchiveReviewRoutes(app, { db, signer, faces: deps.faces, viewerOf, editableFolders }); + await registerArchiveDownloadRoutes(app, { db, storage: deps.storage, secret: deps.secret, viewerOf, visibleFolders }); } /** File ids of a folder and of each folder above it ("/FPA/Fotos" → /FPA/Fotos, /FPA, and the account's root). */ diff --git a/apps/api/test/archive.test.ts b/apps/api/test/archive.test.ts index 557f4df..1d69d6e 100644 --- a/apps/api/test/archive.test.ts +++ b/apps/api/test/archive.test.ts @@ -821,6 +821,30 @@ describe("archive from a Nextcloud", () => { expect((await act(editor, gGala.id, { action: "confirm" })).statusCode).toBe(403); expect((await act(reader, g1.id, { action: "undo" })).statusCode).toBe(403); + // Downloads at web size for anyone who sees the photos; the cloud's links only for those who edit there. + const game = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "20250913 - SCP x ABC" } } }); + const seen = async (t: string) => (await ctx.app.inject({ method: "GET", url: `/v1/archive/galleries/${game.id}`, headers: as(t) })).json() as { cloudUrl: string | null; photos: { cloudUrl?: string }[] }; + expect((await seen(reader)).cloudUrl).toBeNull(); + expect((await seen(reader)).photos[0]!.cloudUrl).toBeUndefined(); + expect((await seen(editor)).cloudUrl).toMatch(/^https:\/\/cloud\.test\/f\//); + const ask = (t: string, payload: Record) => ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/downloads`, headers: as(t), payload }); + res = await ask(reader, { photoIds: [p1.id] }); + const one = res.json() as { url: string; photos: number }; + expect(one.photos).toBe(1); + res = await ctx.app.inject({ method: "GET", url: one.url }); + expect(res.statusCode).toBe(200); + expect(res.headers["content-type"]).toBe("image/jpeg"); + expect(res.headers["content-disposition"]).toContain('filename="PS_0001.jpg"'); + const meta = await sharp(res.rawPayload).metadata(); + expect(Math.max(meta.width!, meta.height!)).toBeLessThanOrEqual(2048); + expect((await ask(reader, { photoIds: [gala.id] })).statusCode).toBe(404); + res = await ask(reader, { folderId: game.id }); + expect(res.json()).toMatchObject({ photos: 2 }); + res = await ctx.app.inject({ method: "GET", url: (res.json() as { url: string }).url }); + expect(res.headers["content-type"]).toBe("application/zip"); + expect(res.rawPayload.subarray(0, 2).toString()).toBe("PK"); + expect((await ctx.app.inject({ method: "GET", url: one.url.slice(0, -3) + "abc" })).statusCode).toBe(404); + // A person as a whole: only the account that edits everything. const off = (t: string, payload: Record) => ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/people/${martim.id}/recognition`, headers: as(t), payload }); expect((await off(editor, { enabled: false })).statusCode).toBe(403); @@ -1003,6 +1027,27 @@ describe("archive from a Nextcloud", () => { expect((await ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { look: "benfica" } })).statusCode).toBe(400); }); + it("serves an archive at an address of its own, one archive per address", async () => { + const source = await connect(); + cloud.authorised = true; + await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); + const patch = (hostname: unknown) => ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { hostname } }); + let res = await patch("https://Arquivo.LigaPortugal.pt/"); + expect(res.json()).toMatchObject({ hostname: "arquivo.ligaportugal.pt" }); + expect((await ctx.app.inject({ method: "GET", url: "/v1/archive/host?host=arquivo.ligaportugal.pt" })).json()).toEqual({ id: source.id }); + // The proxy asks before a certificate: only an archive's address gets one. + expect((await ctx.app.inject({ method: "GET", url: "/v1/archive/host?domain=arquivo.ligaportugal.pt" })).statusCode).toBe(200); + expect((await ctx.app.inject({ method: "GET", url: "/v1/archive/host?domain=other.example.pt" })).statusCode).toBe(404); + expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}` })).json()).toMatchObject({ hostname: "arquivo.ligaportugal.pt" }); + expect((await patch("not a host")).statusCode).toBe(400); + // A public site's domain is taken. + await ctx.db.site.create({ data: { organizationId: orgId, domain: "fotos.example.pt", name: "Fotos" } }); + expect((await patch("fotos.example.pt")).statusCode).toBe(409); + res = await patch(""); + expect(res.json()).toMatchObject({ hostname: null }); + expect((await ctx.app.inject({ method: "GET", url: "/v1/archive/host?host=arquivo.ligaportugal.pt" })).statusCode).toBe(404); + }); + it("shares the worker between clouds: a big newer archive does not starve another", async () => { const source = await connect(); cloud.authorised = true; diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 328092c..c6de03f 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -453,6 +453,10 @@ export const t = { pause: "Pausar", look: "Aspeto do site", looks: { none: "PhotoReport", liga: "Liga Portugal", fpa: "Federação de Andebol" } as Record, + hostname: "Endereço próprio", + 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", resume: "Retomar", remove: "Desligar", removeConfirm: "Desligar esta cloud? As fotos já indexadas ficam na biblioteca.", @@ -826,6 +830,7 @@ export const t = { slug_taken: "Já existe uma galeria com esse endereço.", gallery_empty: "Junta fotos antes de publicar.", domain_taken: "Esse domínio já está em uso.", + hostname_taken: "Esse endereço já está em uso por outro arquivo ou site.", invalid_stripe_key: "A chave da Stripe começa por sk_live_ ou sk_test_.", invalid_webhook_secret: "O segredo do webhook começa por whsec_.", secret_key_missing: "Falta configurar a chave de cifra do servidor (DELIVERY_SECRET_KEY).", diff --git a/apps/app/src/pages/ArchivePage.tsx b/apps/app/src/pages/ArchivePage.tsx index a129467..f36cf78 100644 --- a/apps/app/src/pages/ArchivePage.tsx +++ b/apps/app/src/pages/ArchivePage.tsx @@ -118,7 +118,9 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove const c = source.counts; const total = c.done + c.pending + c.failed; const pct = total ? Math.round((c.done / total) * 100) : 0; - const viewerUrl = `${VIEWER_BASE.replace(/\/+$/, "")}/arquivo/${source.id}`; + 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 run = (fn: () => Promise) => { setBusy(true); @@ -210,6 +212,30 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove )} + {isAdmin && ( +
{ + e.preventDefault(); + void run(() => api.updateCloudSource(source.id, { hostname: hostname.trim() || null })); + }} + > + {A.hostname}: + setHostname(e.target.value)} + placeholder={A.hostnamePlaceholder} + disabled={busy} + className="h-6 min-w-[220px] border border-black bg-cell px-2 font-mono text-[11px] text-ink" + /> + {hostname.trim() !== (source.hostname ?? "") && ( + + )} + {A.hostnameHelp} +
+ )} )} diff --git a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx index 40ebf0e..e60d49a 100644 --- a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx +++ b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx @@ -40,7 +40,8 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } const [reviewPerson, setReviewPerson] = useState(view.kind === "browse" ? (view.person ?? null) : null); const [meTick, setMeTick] = useState(0); const template = info.look ? TEMPLATE[info.look] : null; - const base = `/arquivo/${info.id}`; + const base = info.base ?? `/arquivo/${info.id}`; + const home = base || "/"; useEffect(() => { setToken(readStored(storageKey(info.id))); @@ -74,7 +75,7 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } (v: View) => { const href = v.kind === "browse" - ? `${base}${v.tab && TAB_PARAM[v.tab] ? `?t=${TAB_PARAM[v.tab]}${v.person ? `&p=${v.person}` : ""}` : ""}` + ? `${home}${v.tab && TAB_PARAM[v.tab] ? `?t=${TAB_PARAM[v.tab]}${v.person ? `&p=${v.person}` : ""}` : ""}` : v.kind === "gallery" ? `${base}/g/${v.id}` : v.kind === "person" @@ -83,7 +84,7 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } router.push(href); window.scrollTo({ top: 0 }); }, - [base, router], + [base, home, router], ); /** A tab of the lists: in place when they are on screen (no reload), else back to them. */ @@ -91,16 +92,16 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } (t: Tab) => { if (view.kind !== "browse") return go({ kind: "browse", tab: t }); setTab(t); - window.history.replaceState(null, "", `${base}${TAB_PARAM[t] ? `?t=${TAB_PARAM[t]}` : ""}`); + window.history.replaceState(null, "", `${home}${TAB_PARAM[t] ? `?t=${TAB_PARAM[t]}` : ""}`); window.scrollTo({ top: 0 }); }, - [view.kind, go, base], + [view.kind, go, home], ); const current: Tab | null = view.kind === "browse" ? tab : view.kind === "person" || view.kind === "face" ? "people" : "galleries"; const brand = ( - (e.preventDefault(), openTab("galleries"))}> + (e.preventDefault(), openTab("galleries"))}> {template ? {template.owner} : {info.organization}} Arquivo @@ -158,7 +159,6 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } {t === "review" && !!me?.pending && {me.pending}} ))} - Mostra só o que podes ver em {info.cloud} @@ -188,7 +188,7 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } person={reviewPerson} onPerson={(id) => { setReviewPerson(id); - window.history.replaceState(null, "", `${base}?t=rever${id ? `&p=${id}` : ""}`); + window.history.replaceState(null, "", `${home}?t=rever${id ? `&p=${id}` : ""}`); }} onExpired={expired} onChanged={() => setMeTick((n) => n + 1)} @@ -257,7 +257,7 @@ function SignIn({ info, logo, owner, onDone }: { info: ArchiveInfo; logo: string }, () => { win?.close(); - setError("Não foi possível falar com a cloud. Tenta daqui a pouco."); + setError("Não foi possível iniciar a entrada. Tenta daqui a pouco."); }, ) .finally(() => setBusy(false)); @@ -272,12 +272,12 @@ function SignIn({ info, logo, owner, onDone }: { info: ArchiveInfo; logo: string Arquivo fotográfico

Todas as fotos, num só sítio

- As fotografias estão em {info.cloud}. Entra com a tua conta dessa cloud: vês aqui exatamente o que podes ver lá, nem mais nem menos. + Entra com a tua conta {owner}: vês as galerias a que tens acesso, procuras por jogo, equipa ou pessoa, e descarregas as fotos.

{state ? (

- A aguardar a autorização em {info.cloud}…{" "} + A aguardar que autorizes a entrada na outra janela…{" "} {loginUrl && ( Abrir a página de autorização @@ -287,7 +287,7 @@ function SignIn({ info, logo, owner, onDone }: { info: ArchiveInfo; logo: string ) : ( <>

{error}

}

- A tua palavra-passe só é escrita na página da cloud.{" "} + A tua palavra-passe só é escrita na página de entrada, nunca aqui.{" "} {keep - ? `Com a sessão mantida, o acesso que deres fica guardado (cifrado) para voltar a ler, de poucos em poucos minutos, o que está partilhado contigo: se te tirarem uma partilha em ${info.cloud}, deixa de aparecer aqui. Dura enquanto a usares pelo menos uma vez por mês; "Sair" revoga o acesso.` - : "Sem manter sessão, o acesso serve só para saber o que está partilhado contigo, é revogado de imediato e a sessão acaba ao fechar o separador."} + ? 'Com a sessão mantida, não precisas de voltar a entrar neste dispositivo enquanto usares o arquivo pelo menos uma vez por mês. "Sair" termina a sessão.' + : "Sem manter sessão, sais ao fechar o separador."}

diff --git a/apps/site/src/app/arquivo/[id]/Gallery.tsx b/apps/site/src/app/arquivo/[id]/Gallery.tsx index 391c37e..d95e6f7 100644 --- a/apps/site/src/app/arquivo/[id]/Gallery.tsx +++ b/apps/site/src/app/arquivo/[id]/Gallery.tsx @@ -1,11 +1,13 @@ "use client"; import { useCallback, useEffect, useState } from "react"; -import { cached, call, forget, initials, shortDay, Unauthorised, type GalleryDetail, type Me, type PhotoFace } from "./api"; +import { cached, call, download, forget, initials, MAX_PICKED, shortDay, Unauthorised, type GalleryDetail, type Me, type PhotoFace } from "./api"; import { Lightbox } from "./Lightbox"; import { FaceCrop, Icon, Loading } from "./parts"; const PAGE = 48; +/** A whole gallery downloads as one ZIP up to this many photos (the API's limit). */ +const MAX_ZIP = 1000; /** A game's (or an event's) gallery: the match on top, the people of the game to filter by, the photos. */ export function Gallery({ @@ -33,6 +35,27 @@ export function Gallery({ const [error, setError] = useState(false); const [more, setMore] = useState(false); const [attempt, setAttempt] = useState(0); + /** Photos picked for a download (null: not picking). */ + const [picked, setPicked] = useState | null>(null); + const [saving, setSaving] = useState(null); + const [note, setNote] = useState(null); + + const save = useCallback( + (ask: { photoIds: string[] } | { folderId: string }, label: string) => { + setSaving(label); + setNote(null); + download(sourceId, token, ask) + .then( + (n) => { + setNote(n > 1 ? `A preparar ${n} fotos (ZIP). O download começa já a seguir.` : null); + if ("photoIds" in ask && ask.photoIds.length > 1) setPicked(null); + }, + (err) => (err instanceof Unauthorised ? onExpired() : setNote("Não foi possível descarregar. Tenta outra vez.")), + ) + .finally(() => setSaving(null)); + }, + [sourceId, token, onExpired], + ); const url = useCallback( (offset: number, person: string | null) => { @@ -126,7 +149,7 @@ export function Gallery({ const people = g.people ?? []; const roster = g.roster ?? []; - const picked = roster.find((p) => p.id === only) ?? null; + const chosen = roster.find((p) => p.id === only) ?? null; const photos = g.photos; const total = g.total ?? photos.length; const isGame = !!(g.home && g.away); @@ -162,11 +185,24 @@ export function Gallery({ )}
- - - Abrir a pasta na cloud - + {total <= MAX_ZIP && ( + + )} +
+ {note &&

{note}

} + {g.cloudUrl && ( + + + Originais em alta qualidade na cloud + + )} @@ -209,9 +245,9 @@ export function Gallery({ )} - {picked && ( - )} @@ -219,11 +255,26 @@ export function Gallery({ )}
- {picked && photos.length === 0 &&

Sem fotos de {picked.name} nesta parte do jogo.

} -
+ {chosen && photos.length === 0 &&

Sem fotos de {chosen.name} nesta parte do jogo.

} +
{photos.map((p, i) => ( - ))}
+ {picked && ( +
+ {picked.size ? `${picked.size} ${picked.size === 1 ? "foto" : "fotos"}` : "Toca nas fotos que queres"} + + {picked.size < Math.min(photos.length, MAX_PICKED) && ( + + )} + + +
+ )} {photos.length < total && (
+ )} {current.cloudUrl && ( - + - Original na cloud )}