From 11282efa1a04815fcede6742e24059aa2812596a Mon Sep 17 00:00:00 2001 From: spark Date: Sat, 17 Oct 2026 17:46:24 +0100 Subject: [PATCH] Archive: open each gallery by the page, with a link that survives refresh. The public archive was loading every indexed photo on each click. Pages now come from the database, and Nextcloud is only asked when someone signs in. --- .../migration.sql | 31 ++++ apps/api/prisma/schema.prisma | 33 ++++ apps/api/src/archive/people.ts | 142 +++++++++++------- apps/api/src/archive/viewer.ts | 142 ++++++++++++++---- apps/api/test/archive.test.ts | 14 +- .../site/src/app/arquivo/[id]/ArchiveView.tsx | 126 ++++++++++++---- .../src/app/arquivo/[id]/f/[faceId]/page.tsx | 20 +++ apps/site/src/app/arquivo/[id]/frame.tsx | 14 ++ .../app/arquivo/[id]/g/[folderId]/page.tsx | 20 +++ apps/site/src/app/arquivo/[id]/layout.tsx | 15 ++ apps/site/src/app/arquivo/[id]/load.ts | 20 +++ .../app/arquivo/[id]/p/[personId]/page.tsx | 20 +++ apps/site/src/app/arquivo/[id]/page.tsx | 41 +---- docs/archive.md | 14 +- 14 files changed, 498 insertions(+), 154 deletions(-) create mode 100644 apps/api/prisma/migrations/20261017210000_archive_viewer_pages/migration.sql create mode 100644 apps/site/src/app/arquivo/[id]/f/[faceId]/page.tsx create mode 100644 apps/site/src/app/arquivo/[id]/frame.tsx create mode 100644 apps/site/src/app/arquivo/[id]/g/[folderId]/page.tsx create mode 100644 apps/site/src/app/arquivo/[id]/layout.tsx create mode 100644 apps/site/src/app/arquivo/[id]/load.ts create mode 100644 apps/site/src/app/arquivo/[id]/p/[personId]/page.tsx diff --git a/apps/api/prisma/migrations/20261017210000_archive_viewer_pages/migration.sql b/apps/api/prisma/migrations/20261017210000_archive_viewer_pages/migration.sql new file mode 100644 index 0000000..33a712d --- /dev/null +++ b/apps/api/prisma/migrations/20261017210000_archive_viewer_pages/migration.sql @@ -0,0 +1,31 @@ +-- Gallery pages read one folder at a time, in path order. The walk looks up children by parent. +CREATE INDEX "cloud_files_folder_id_status_path_idx" ON "cloud_files"("folder_id", "status", "path"); +CREATE INDEX "cloud_folders_parent_id_idx" ON "cloud_folders"("parent_id"); +-- The gallery list is "this source, folders that have photos". +CREATE INDEX "cloud_folders_source_galleries_idx" ON "cloud_folders"("source_id") WHERE "photo_count" > 0; + +-- One row per sign-in. The session token carries this id, not the folder list. +CREATE TABLE "archive_grants" ( + "id" UUID NOT NULL, + "source_id" UUID NOT NULL, + "viewer_name" TEXT NOT NULL, + "sees_all" BOOLEAN NOT NULL DEFAULT false, + "expires_at" TIMESTAMP(3) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "archive_grants_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE "archive_grant_folders" ( + "grant_id" UUID NOT NULL, + "folder_id" UUID NOT NULL, + + CONSTRAINT "archive_grant_folders_pkey" PRIMARY KEY ("grant_id","folder_id") +); + +CREATE INDEX "archive_grants_source_id_expires_at_idx" ON "archive_grants"("source_id", "expires_at"); +CREATE INDEX "archive_grant_folders_folder_id_idx" ON "archive_grant_folders"("folder_id"); + +ALTER TABLE "archive_grants" ADD CONSTRAINT "archive_grants_source_id_fkey" FOREIGN KEY ("source_id") REFERENCES "cloud_sources"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "archive_grant_folders" ADD CONSTRAINT "archive_grant_folders_grant_id_fkey" FOREIGN KEY ("grant_id") REFERENCES "archive_grants"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "archive_grant_folders" ADD CONSTRAINT "archive_grant_folders_folder_id_fkey" FOREIGN KEY ("folder_id") REFERENCES "cloud_folders"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 20de581..66c34ad 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -1608,6 +1608,7 @@ model CloudSource { organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) folders CloudFolder[] files CloudFile[] + grants ArchiveGrant[] @@index([organizationId]) @@map("cloud_sources") @@ -1636,9 +1637,11 @@ model CloudFolder { source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade) event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull) files CloudFile[] + grants ArchiveGrantFolder[] @@unique([sourceId, fileId]) @@index([sourceId, path]) + @@index([parentId]) @@map("cloud_folders") } @@ -1667,5 +1670,35 @@ model CloudFile { @@unique([sourceId, fileId]) @@index([status, sourceId]) @@index([photoId]) + @@index([folderId, status, path]) @@map("cloud_files") } + +/// What one viewer may see, written when they sign in. Later pages read this row; they do not call the cloud again. +/// Shares stay as they were at sign-in until the session ends. +model ArchiveGrant { + id String @id @default(uuid()) @db.Uuid + sourceId String @map("source_id") @db.Uuid + viewerName String @map("viewer_name") + seesAll Boolean @default(false) @map("sees_all") + expiresAt DateTime @map("expires_at") + createdAt DateTime @default(now()) @map("created_at") + + source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade) + folders ArchiveGrantFolder[] + + @@index([sourceId, expiresAt]) + @@map("archive_grants") +} + +model ArchiveGrantFolder { + grantId String @map("grant_id") @db.Uuid + folderId String @map("folder_id") @db.Uuid + + grant ArchiveGrant @relation(fields: [grantId], references: [id], onDelete: Cascade) + folder CloudFolder @relation(fields: [folderId], references: [id], onDelete: Cascade) + + @@id([grantId, folderId]) + @@index([folderId]) + @@map("archive_grant_folders") +} diff --git a/apps/api/src/archive/people.ts b/apps/api/src/archive/people.ts index 08ae6b2..c2f1015 100644 --- a/apps/api/src/archive/people.ts +++ b/apps/api/src/archive/people.ts @@ -1,6 +1,7 @@ import type { FastifyInstance, FastifyRequest } from "fastify"; import { eventName } from "@photoreport/metadata"; import { z } from "zod"; +import { Prisma } from "../generated/prisma/client.js"; import type { Db } from "../db.js"; import { boxInCrop, cropOfSettings } from "../faces/frame.js"; import { cosine, inFocus, THRESHOLDS } from "../faces/math.js"; @@ -41,14 +42,15 @@ export function faceBox( export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: Deps) { const { db, signer, viewerOf, visibleFolders } = deps; - /** Photos of the source the viewer may see (indexed, in a visible gallery), with their gallery. */ - const visiblePhotos = async (v: Viewer): Promise> => { + /** + * Indexed files of this source the viewer may see, as a join condition on `cf`. Empty access is null, so callers + * skip the query instead of building a list of every photo id. + */ + const scopeOf = async (v: Viewer): Promise => { const visible = await visibleFolders(v); - const rows = await db.cloudFile.findMany({ - where: { sourceId: v.s, status: "DONE", photoId: { not: null }, ...(visible !== "all" && { folderId: { in: visible } }) }, - select: { photoId: true, folderId: true }, - }); - return new Map(rows.map((r) => [r.photoId!, r.folderId])); + if (visible !== "all" && !visible.length) return null; + if (visible === "all") return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`; + return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[])`; }; const galleryInfo = async (folderIds: string[]) => { @@ -56,19 +58,26 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De return new Map(folders.map((f) => [f.id, { id: f.id, title: f.event ? eventName(f.event) : (f.path.split("/").pop() ?? ""), startsAt: f.event?.startsAt ?? null, competition: f.event?.competition ?? null }])); }; - /** Photos (with the face found) as the pages show them, newest game first. */ - const photoCards = async (hits: { photoId: string; faceId: string; level: Level; score: number | null }[], where: Map) => { + /** Photos (with the face found) as the pages show them, newest game first. Faces of the photo load when it is opened. */ + const photoCards = async (hits: { photoId: string; faceId: string; level: Level; score: number | null }[], scope: Prisma.Sql) => { + if (!hits.length) return []; + const ids = hits.map((h) => h.photoId); + const links = await db.$queryRaw<{ photo_id: string; folder_id: string }[]>` + SELECT DISTINCT ON (cf.photo_id) cf.photo_id, cf.folder_id + FROM cloud_files cf + WHERE cf.photo_id = ANY(${ids}::uuid[]) AND ${scope} + ORDER BY cf.photo_id, cf.path`; + const folderOf = new Map(links.map((r) => [r.photo_id, r.folder_id])); const photos = await db.photo.findMany({ - where: { id: { in: hits.map((h) => h.photoId) } }, + where: { id: { in: ids } }, select: { id: true, width: true, height: true, players: true, capturedAt: true, renderedSeq: true, developSnapshot: true, originalName: true }, }); const byId = new Map(photos.map((p) => [p.id, p])); const faces = await db.face.findMany({ where: { id: { in: hits.map((h) => h.faceId) } }, select: { id: true, x0: true, y0: true, x1: true, y1: true } }); const faceById = new Map(faces.map((f) => [f.id, f])); - const galleries = await galleryInfo(hits.map((h) => where.get(h.photoId)!).filter(Boolean)); - const facesIn = await facesOfPhotos(db, photos); + const galleries = await galleryInfo([...folderOf.values()]); return hits - .filter((h) => byId.has(h.photoId)) + .filter((h) => byId.has(h.photoId) && folderOf.has(h.photoId)) .map((h) => { const p = byId.get(h.photoId)!; const f = faceById.get(h.faceId); @@ -84,8 +93,7 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De level: h.level, score: h.score, face: f ? faceBox(f, p) : null, - faces: facesIn.get(p.id) ?? [], - gallery: galleries.get(where.get(h.photoId)!) ?? null, + gallery: galleries.get(folderOf.get(h.photoId)!) ?? null, }; }) .sort((a, b) => (b.gallery?.startsAt?.getTime() ?? 0) - (a.gallery?.startsAt?.getTime() ?? 0) || (a.capturedAt?.getTime() ?? 0) - (b.capturedAt?.getTime() ?? 0)); @@ -112,17 +120,17 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De const { sourceId } = SourceParams.parse(req.params); const v = viewerOf(req, sourceId); const query = PeopleQuery.parse(req.query); - const where = await visiblePhotos(v); - if (!where.size) return { people: [], clubs: [] }; - const photoIds = [...where.keys()]; + const scope = await scopeOf(v); + if (!scope) return { people: [], clubs: [] }; const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; confirmed: bigint; probable: bigint }[]>` SELECT p.id, p.name, p.club, p.number, p.reference_key IS NOT NULL AS reference, count(DISTINCT f.photo_id) FILTER (WHERE g.person_id = p.id) AS confirmed, count(DISTINCT f.photo_id) FILTER (WHERE g.person_id IS NULL) AS probable FROM face_groups g JOIN faces f ON f.group_id = g.id + JOIN cloud_files cf ON cf.photo_id = f.photo_id JOIN people p ON p.id = coalesce(g.person_id, g.suggested_person_id) - WHERE g.ignored_at IS NULL AND f.photo_id = ANY(${photoIds}::uuid[]) + WHERE g.ignored_at IS NULL AND ${scope} GROUP BY p.id`; const fold = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase(); const words = fold(query.q ?? "").split(/\s+/).filter(Boolean); @@ -132,8 +140,10 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De const faces = noRef.length ? await db.$queryRaw<{ person_id: string; photo_id: string; x0: number; y0: number; x1: number; y1: number }[]>` SELECT DISTINCT ON (coalesce(g.person_id, g.suggested_person_id)) coalesce(g.person_id, g.suggested_person_id) AS person_id, f.photo_id, f.x0, f.y0, f.x1, f.y1 - FROM faces f JOIN face_groups g ON g.id = f.group_id - WHERE coalesce(g.person_id, g.suggested_person_id) = ANY(${noRef}::uuid[]) AND g.ignored_at IS NULL AND f.photo_id = ANY(${photoIds}::uuid[]) + FROM faces f + JOIN face_groups g ON g.id = f.group_id + JOIN cloud_files cf ON cf.photo_id = f.photo_id + WHERE coalesce(g.person_id, g.suggested_person_id) = ANY(${noRef}::uuid[]) AND g.ignored_at IS NULL AND ${scope} ORDER BY coalesce(g.person_id, g.suggested_person_id), (g.person_id IS NOT NULL) DESC, f.sharpness DESC NULLS LAST, f.score DESC` : []; const facePhotos = await db.photo.findMany({ where: { id: { in: faces.map((f) => f.photo_id) } }, select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true } }); @@ -171,28 +181,32 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De const { sourceId, personId } = PersonParams.parse(req.params); const v = viewerOf(req, sourceId); const query = PhotosQuery.parse(req.query); - const where = await visiblePhotos(v); + const scope = await scopeOf(v); const person = await db.person.findFirst({ where: { id: personId, organization: { cloudSources: { some: { id: sourceId } } } } }); if (!person) throw notFound("person_not_found"); - const photoIds = [...where.keys()]; - const named = await db.face.findMany({ - where: { photoId: { in: photoIds }, group: { ignoredAt: null, OR: [{ personId }, ...(query.level === "all" ? [{ personId: null, suggestedPersonId: personId }] : [])] } }, - select: { id: true, photoId: true, sharpness: true, group: { select: { personId: true, suggestionScore: true } } }, - }); + const named = scope + ? await db.$queryRaw<{ id: string; photo_id: string; sharpness: number | null; person_id: string | null; suggestion_score: number | null }[]>` + SELECT f.id, f.photo_id, f.sharpness, g.person_id, g.suggestion_score + FROM faces f + JOIN face_groups g ON g.id = f.group_id + JOIN cloud_files cf ON cf.photo_id = f.photo_id + WHERE g.ignored_at IS NULL AND ${scope} + AND (g.person_id = ${personId}::uuid OR (${query.level === "all"} AND g.person_id IS NULL AND g.suggested_person_id = ${personId}::uuid))` + : []; const hits: { photoId: string; faceId: string; level: Level; score: number | null; sharpness: number | null }[] = named.map((f) => ({ - photoId: f.photoId, + photoId: f.photo_id, faceId: f.id, - level: f.group?.personId === personId ? "confirmed" : "probable", - score: f.group?.personId === personId ? null : (f.group?.suggestionScore ?? null), + level: f.person_id === personId ? "confirmed" : "probable", + score: f.person_id === personId ? null : f.suggestion_score, sharpness: f.sharpness, })); - if (query.level === "all" && person.centroid.length && person.model) { - const similar = await similarGroups(person.centroid, person.model, photoIds, new Set()); + if (scope && query.level === "all" && person.centroid.length && person.model) { + const similar = await similarGroups(person.centroid, person.model, scope, new Set()); const seen = new Set(hits.map((h) => h.photoId)); for (const s of similar) if (!s.personId && !seen.has(s.photoId)) hits.push({ photoId: s.photoId, faceId: s.faceId, level: "similar", score: s.score, sharpness: s.sharpness }); } const chosen = onePerPhoto(hits).slice(0, query.limit); - const photos = await photoCards(chosen, where); + const photos = scope ? await photoCards(chosen, scope) : []; return { person: { id: person.id, name: person.name, club: person.club, number: person.number, reference: person.referenceKey ? signer.personUrl(person.id) : null }, counts: { confirmed: photos.filter((p) => p.level === "confirmed").length, probable: photos.filter((p) => p.level === "probable").length, similar: photos.filter((p) => p.level === "similar").length }, @@ -200,23 +214,34 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De }; }); - /** Face groups (in the given photos) like a face: their faces, with how alike, most alike first. */ - const similarGroups = async (embedding: number[], model: string, photoIds: string[], exclude: Set) => { + /** Face groups in the viewer's galleries like a face: their faces, with how alike, most alike first. */ + const similarGroups = async (embedding: number[], model: string, scope: Prisma.Sql, exclude: Set) => { const t = THRESHOLDS[model] ?? { match: 0.5 }; - const eventIds = await db.photo.findMany({ where: { id: { in: photoIds } }, select: { eventId: true }, distinct: ["eventId"] }); - const groups = await db.faceGroup.findMany({ - where: { eventId: { in: eventIds.map((e) => e.eventId!).filter(Boolean) }, model, ignoredAt: null }, - select: { id: true, centroid: true, personId: true }, - }); + const groups = await db.$queryRaw<{ id: string; centroid: unknown; person_id: string | null }[]>` + SELECT g.id, g.centroid, g.person_id + FROM face_groups g + WHERE g.ignored_at IS NULL AND g.model = ${model} AND cardinality(g.centroid) > 0 + AND g.event_id IN ( + SELECT ph.event_id FROM photos ph + JOIN cloud_files cf ON cf.photo_id = ph.id + WHERE ${scope} AND ph.event_id IS NOT NULL + )`; + const asVector = (v: unknown): number[] => (Array.isArray(v) ? v.map(Number) : typeof v === "string" ? v.replace(/[{}]/g, "").split(",").filter(Boolean).map(Number) : []); const near = groups - .filter((g) => !exclude.has(g.id) && g.centroid.length) - .map((g) => ({ g, score: cosine(embedding, g.centroid) })) + .filter((g) => !exclude.has(g.id)) + .map((g) => ({ g, vector: asVector(g.centroid) })) + .filter((x) => x.vector.length) + .map((x) => ({ g: x.g, score: cosine(embedding, x.vector) })) .filter((x) => x.score >= t.match); if (!near.length) return []; const score = new Map(near.map((x) => [x.g.id, x])); - const faces = await db.face.findMany({ where: { groupId: { in: [...score.keys()] }, photoId: { in: photoIds } }, select: { id: true, photoId: true, groupId: true, sharpness: true } }); + const faces = await db.$queryRaw<{ id: string; photo_id: string; group_id: string; sharpness: number | null }[]>` + SELECT f.id, f.photo_id, f.group_id, f.sharpness + FROM faces f + JOIN cloud_files cf ON cf.photo_id = f.photo_id + WHERE f.group_id = ANY(${[...score.keys()]}::uuid[]) AND ${scope}`; return faces - .map((f) => ({ faceId: f.id, photoId: f.photoId, sharpness: f.sharpness, score: score.get(f.groupId!)!.score, personId: score.get(f.groupId!)!.g.personId })) + .map((f) => ({ faceId: f.id, photoId: f.photo_id, sharpness: f.sharpness, score: score.get(f.group_id)!.score, personId: score.get(f.group_id)!.g.person_id })) .sort((a, b) => b.score - a.score); }; @@ -227,32 +252,41 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De app.get("/v1/archive/:sourceId/faces/:faceId/similar", async (req) => { const { sourceId, faceId } = FaceParams.parse(req.params); const v = viewerOf(req, sourceId); - const where = await visiblePhotos(v); + const scope = await scopeOf(v); const face = await db.face.findUnique({ where: { id: faceId }, include: { group: { include: { person: true, suggested: true } } } }); - if (!face || !where.has(face.photoId)) throw notFound("face_not_found"); + const seen = face && scope + ? await db.$queryRaw<{ ok: number }[]>`SELECT 1 AS ok FROM cloud_files cf WHERE cf.photo_id = ${face.photoId}::uuid AND ${scope} LIMIT 1` + : []; + if (!face || !scope || !seen.length) throw notFound("face_not_found"); const named = face.group?.person ?? null; const probe = face.group?.centroid.length ? face.group.centroid : face.embedding; - const photoIds = [...where.keys()]; const hits: { photoId: string; faceId: string; level: Level; score: number | null; sharpness: number | null }[] = []; // Its own group: the same person in the same game (certain as the grouping is). if (face.groupId) { - const own = await db.face.findMany({ where: { groupId: face.groupId, photoId: { in: photoIds } }, select: { id: true, photoId: true, sharpness: true } }); - for (const f of own) hits.push({ photoId: f.photoId, faceId: f.id, level: named ? "confirmed" : "similar", score: named ? null : 1, sharpness: f.sharpness }); + const own = await db.$queryRaw<{ id: string; photo_id: string; sharpness: number | null }[]>` + SELECT f.id, f.photo_id, f.sharpness FROM faces f + JOIN cloud_files cf ON cf.photo_id = f.photo_id + WHERE f.group_id = ${face.groupId}::uuid AND ${scope!}`; + for (const f of own) hits.push({ photoId: f.photo_id, faceId: f.id, level: named ? "confirmed" : "similar", score: named ? null : 1, sharpness: f.sharpness }); } else hits.push({ photoId: face.photoId, faceId: face.id, level: "similar", score: 1, sharpness: face.sharpness }); // The same named person elsewhere. if (named) { - const more = await db.face.findMany({ where: { photoId: { in: photoIds }, group: { personId: named.id, ignoredAt: null } }, select: { id: true, photoId: true, sharpness: true } }); - for (const f of more) hits.push({ photoId: f.photoId, faceId: f.id, level: "confirmed", score: null, sharpness: f.sharpness }); + const more = await db.$queryRaw<{ id: string; photo_id: string; sharpness: number | null }[]>` + SELECT f.id, f.photo_id, f.sharpness FROM faces f + JOIN face_groups g ON g.id = f.group_id + JOIN cloud_files cf ON cf.photo_id = f.photo_id + WHERE g.person_id = ${named.id}::uuid AND g.ignored_at IS NULL AND ${scope!}`; + for (const f of more) hits.push({ photoId: f.photo_id, faceId: f.id, level: "confirmed", score: null, sharpness: f.sharpness }); } - if (probe.length) { - for (const s of await similarGroups(probe, face.model, photoIds, new Set(face.groupId ? [face.groupId] : []))) { + if (probe.length && scope) { + for (const s of await similarGroups(probe, face.model, scope, new Set(face.groupId ? [face.groupId] : []))) { if (named && s.personId === named.id) continue; // Faces named as someone else are someone else. if (s.personId && named) continue; hits.push({ photoId: s.photoId, faceId: s.faceId, level: s.personId ? "confirmed" : "similar", score: s.score, sharpness: s.sharpness }); } } - const photos = await photoCards(onePerPhoto(hits).slice(0, 400), where); + const photos = await photoCards(onePerPhoto(hits).slice(0, 400), scope!); const suggested = !named && face.group?.suggested ? face.group.suggested : null; return { person: named ? { id: named.id, name: named.name, club: named.club } : null, diff --git a/apps/api/src/archive/viewer.ts b/apps/api/src/archive/viewer.ts index 7ac2c1b..20035fa 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -2,6 +2,7 @@ import { createHmac, timingSafeEqual } from "node:crypto"; import type { FastifyInstance, FastifyRequest } from "fastify"; import { eventName } from "@photoreport/metadata"; import { z } from "zod"; +import { Prisma } from "../generated/prisma/client.js"; import type { Db } from "../db.js"; import { NextcloudError } from "../delivery/nextcloud.js"; import type { SecretBox } from "../delivery/secrets.js"; @@ -9,7 +10,7 @@ import { AppError, badRequest, notFound, unauthorized } from "../lib/errors.js"; import type { UrlSigner } from "../storage/storage.js"; import { CloudClient, pollLogin, startLogin } from "./nextcloud.js"; import { canonicalTeam, describeFolder } from "./match.js"; -import { facesOfPhotos, registerArchivePeopleRoutes } from "./people.js"; +import { faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js"; import type { ArchiveService } from "./service.js"; /** @@ -25,10 +26,12 @@ export interface Viewer { s: string; /** Display name on the cloud. */ n: string; + /** Grant written at sign-in. Sessions signed before grants existed carry `all` and `f` instead. */ + g?: string; /** Sees the whole source (the account that indexes it, or a share of its root or above). */ - all: boolean; + all?: boolean; /** Archive folder ids shared with them (each with everything below). */ - f: string[]; + f?: string[]; exp: number; } @@ -58,6 +61,13 @@ export class ViewerTokens { const SourceParams = z.object({ sourceId: z.uuid() }); const FolderParams = z.object({ folderId: z.uuid() }); +const PhotoParams = z.object({ photoId: z.uuid() }); +const GalleryQuery = z.object({ + offset: z.coerce.number().int().min(0).default(0), + limit: z.coerce.number().int().min(1).max(60).default(48), + player: z.string().trim().max(120).optional(), + person: z.uuid().optional(), +}); const Poll = z.object({ state: z.string().min(10).max(4000) }); const ListQuery = z.object({ q: z.string().trim().max(120).optional(), @@ -86,13 +96,24 @@ export async function registerArchiveViewerRoutes( return v; }; - /** Ids of the gallery folders a viewer may open in a source. */ + /** + * Ids of the gallery folders a viewer may open in a source. A grant is one row ("sees everything", or the shared + * folder ids); a session from before grants still carries that list in the token. + */ const visibleFolders = async (v: Viewer): Promise => { - if (v.all) return "all"; - if (!v.f.length) return []; + let all = !!v.all; + let roots = v.f ?? []; + if (v.g) { + const grant = await db.archiveGrant.findUnique({ where: { id: v.g }, include: { folders: { select: { folderId: true } } } }); + if (!grant || grant.sourceId !== v.s || grant.expiresAt.getTime() <= Date.now()) throw unauthorized("archive_login_required"); + all = grant.seesAll; + roots = grant.folders.map((f) => f.folderId); + } + if (all) return "all"; + if (!roots.length) return []; const rows = await db.$queryRaw<{ id: string }[]>` WITH RECURSIVE tree AS ( - SELECT id FROM cloud_folders WHERE source_id = ${v.s}::uuid AND id = ANY(${v.f}::uuid[]) + SELECT id FROM cloud_folders WHERE source_id = ${v.s}::uuid AND id = ANY(${roots}::uuid[]) UNION SELECT c.id FROM cloud_folders c JOIN tree t ON c.parent_id = t.id ) @@ -100,6 +121,12 @@ export async function registerArchiveViewerRoutes( return rows.map((r) => r.id); }; + /** Indexed files of this source the viewer may see. Joined in later queries; never a list of photo ids. */ + const fileScope = (sourceId: string, visible: string[] | "all"): Prisma.Sql => { + if (visible === "all") return Prisma.sql`cf.source_id = ${sourceId}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`; + return Prisma.sql`cf.source_id = ${sourceId}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[])`; + }; + const folderWhere = (v: Viewer, visible: string[] | "all") => ({ sourceId: v.s, photoCount: { gt: 0 }, @@ -159,7 +186,17 @@ export async function registerArchiveViewerRoutes( folders = rows.map((r) => r.id); } } - return { token: tokens.sign({ s: source.id, n: me.displayName, all, f: folders }), viewer: { name: me.displayName, all, folders: folders.length } }; + await db.archiveGrant.deleteMany({ where: { sourceId: source.id, expiresAt: { lt: new Date() } } }); + const grant = await db.archiveGrant.create({ + data: { + sourceId: source.id, + viewerName: me.displayName, + seesAll: all, + expiresAt: new Date(Date.now() + VIEWER_TTL_SEC * 1000), + ...(!all && folders.length ? { folders: { create: folders.map((folderId) => ({ folderId })) } } : {}), + }, + }); + return { token: tokens.sign({ s: source.id, n: me.displayName, g: grant.id }), viewer: { name: me.displayName, all, folders: folders.length } }; } catch (err) { if (err instanceof NextcloudError) throw new AppError(502, "cloud_error", err.message); throw err; @@ -252,37 +289,74 @@ export async function registerArchiveViewerRoutes( 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 eventIds = [...new Set(folders.map((f) => f.eventId!))]; - const players = eventIds.length - ? await db.$queryRaw<{ name: string; photos: bigint; club: string | null }[]>` - SELECT p.name, count(*) AS photos, max(pe.club) AS club - FROM (SELECT unnest(ph.players) AS name FROM photos ph JOIN cloud_files cf ON cf.photo_id = ph.id - WHERE ph.event_id = ANY(${eventIds}::uuid[]) AND cf.source_id = ${sourceId}::uuid) p - LEFT JOIN people pe ON pe.name = p.name AND pe.organization_id = (SELECT organization_id FROM cloud_sources WHERE id = ${sourceId}::uuid) - GROUP BY p.name ORDER BY count(*) DESC, p.name LIMIT 2000` - : []; + const players = + visible === "all" || visible.length + ? await db.$queryRaw<{ name: string; photos: bigint; club: string | null }[]>` + SELECT p.name, count(*) AS photos, max(pe.club) AS club + FROM (SELECT unnest(ph.players) AS name FROM photos ph JOIN cloud_files cf ON cf.photo_id = ph.id + WHERE ${fileScope(sourceId, visible)} AND cardinality(ph.players) > 0) p + LEFT JOIN people pe ON pe.name = p.name AND pe.organization_id = (SELECT organization_id FROM cloud_sources WHERE id = ${sourceId}::uuid) + WHERE p.name <> '' + GROUP BY p.name ORDER BY count(*) DESC, p.name LIMIT 2000` + : []; return { teams: [...teams].map(([name, galleries]) => ({ name, galleries })).sort((a, b) => b.galleries - a.galleries || a.name.localeCompare(b.name)), players: players.map((p) => ({ name: p.name, club: p.club, photos: Number(p.photos) })), }; }); - /** One gallery's photos (the viewer must see its folder). */ + /** One page of a gallery (the viewer must see its folder). Faces are not in the page; a photo asks for its own. */ app.get("/v1/archive/galleries/:folderId", async (req) => { const { folderId } = FolderParams.parse(req.params); + const query = GalleryQuery.parse(req.query); const v = viewerOf(req); const visible = await visibleFolders(v); if (visible !== "all" && !visible.includes(folderId)) throw notFound("gallery_not_found"); const folder = await db.cloudFolder.findFirst({ where: { id: folderId, sourceId: v.s }, include: { event: true, source: { select: { baseUrl: true } } } }); if (!folder) throw notFound("gallery_not_found"); - const player = typeof (req.query as { player?: unknown }).player === "string" ? (req.query as { player: string }).player : undefined; - const files = await db.cloudFile.findMany({ - where: { folderId, status: "DONE", photoId: { not: null }, ...(player && { photo: { players: { has: player } } }) }, - include: { photo: { select: { id: true, width: true, height: true, players: true, capturedAt: true, renderedSeq: true, developSnapshot: true } } }, - orderBy: { path: "asc" }, + const where = { + folderId, + status: "DONE" as const, + photoId: { not: null }, + ...(query.player && { photo: { players: { has: query.player } } }), + ...(query.person && { photo: { faces: { some: { group: { personId: query.person, ignoredAt: null } } } } }), + }; + const [total, files, named, sharpest] = await Promise.all([ + db.cloudFile.count({ where }), + db.cloudFile.findMany({ + where, + include: { photo: { select: { id: true, width: true, height: true, players: true, capturedAt: true, renderedSeq: true } } }, + orderBy: { path: "asc" }, + skip: query.offset, + take: query.limit, + }), + db.$queryRaw<{ id: string; name: string; count: number }[]>` + SELECT p.id, p.name, count(DISTINCT f.photo_id)::int AS count + FROM faces f + JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL + JOIN people p ON p.id = g.person_id + JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ${folderId}::uuid AND cf.status = 'DONE' + GROUP BY p.id + ORDER BY count(DISTINCT f.photo_id) DESC, p.name`, + db.$queryRaw<{ person_id: string; photo_id: string; x0: number; y0: number; x1: number; y1: number }[]>` + SELECT DISTINCT ON (g.person_id) g.person_id, f.photo_id, f.x0, f.y0, f.x1, f.y1 + FROM faces f + JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL + JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ${folderId}::uuid AND cf.status = 'DONE' + ORDER BY g.person_id, f.sharpness DESC NULLS LAST, f.score DESC`, + ]); + const facePhotos = await db.photo.findMany({ + where: { id: { in: sharpest.map((f) => f.photo_id) } }, + select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true }, }); - // The faces in each photo: a click finds more photos of that face. - const faces = await facesOfPhotos(db, files.map((f) => f.photo!)); + const photoById = new Map(facePhotos.map((p) => [p.id, p])); + const faceOf = new Map( + sharpest.flatMap((f) => { + const p = photoById.get(f.photo_id); + if (!p) return []; + return [[f.person_id, { src: signer.url(f.photo_id, "preview", p.renderedSeq), box: faceBox(f, p), aspect: p.width && p.height ? p.width / p.height : 1.5 }] as const]; + }), + ); const base = folder.source.baseUrl.replace(/\/+$/, ""); return { id: folder.id, @@ -292,6 +366,8 @@ export async function registerArchiveViewerRoutes( startsAt: folder.event?.startsAt ?? null, /** The folder on the cloud (opens for those it is shared with). */ cloudUrl: `${base}/f/${folder.fileId}`, + total, + people: named.map((p) => ({ id: p.id, name: p.name, count: Number(p.count), face: faceOf.get(p.id) ?? null })), photos: files.map((f) => ({ id: f.photo!.id, name: f.path.split("/").pop(), @@ -302,11 +378,25 @@ export async function registerArchiveViewerRoutes( thumb: signer.url(f.photo!.id, "thumb", f.photo!.renderedSeq), preview: signer.url(f.photo!.id, "preview", f.photo!.renderedSeq), cloudUrl: `${base}/f/${f.fileId}`, - faces: faces.get(f.photo!.id) ?? [], })), }; }); + /** The faces of one photo, when it is opened. The grid does not carry them. */ + app.get("/v1/archive/photos/:photoId", async (req) => { + const { photoId } = PhotoParams.parse(req.params); + const v = viewerOf(req); + const file = await db.cloudFile.findFirst({ + where: { photoId, sourceId: v.s, status: "DONE" }, + include: { photo: { select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true } } }, + }); + if (!file?.photo) throw notFound("photo_not_found"); + const visible = await visibleFolders(v); + if (visible !== "all" && !visible.includes(file.folderId)) throw notFound("photo_not_found"); + const faces = await facesOfPhotos(db, [file.photo]); + return { id: file.photo.id, faces: faces.get(file.photo.id) ?? [] }; + }); + await registerArchivePeopleRoutes(app, { db, signer, viewerOf, visibleFolders }); } diff --git a/apps/api/test/archive.test.ts b/apps/api/test/archive.test.ts index 0f57a23..c378266 100644 --- a/apps/api/test/archive.test.ts +++ b/apps/api/test/archive.test.ts @@ -681,12 +681,18 @@ describe("archive from a Nextcloud", () => { // The gallery says where the faces are. const folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "SCP x ABC" } } }); - res = await get(owner, `/v1/archive/galleries/${folder.id}`); - const withFaces = (res.json().photos as { id: string; faces: { person: { name: string } | null; level: string | null }[] }[]).find((p) => p.id === p2.id)!; - expect(withFaces.faces.map((f) => f.person?.name ?? null).sort()).toEqual(["Martim Costa", null].sort()); + res = await get(owner, `/v1/archive/galleries/${folder.id}?limit=1`); + expect(res.json().photos).toHaveLength(1); + expect(res.json().total).toBe(2); + expect(res.json().photos[0].faces).toBeUndefined(); + expect(res.json().people).toEqual([expect.objectContaining({ name: "Martim Costa", count: 2 })]); + res = await get(owner, `/v1/archive/photos/${p2.id}`); + expect((res.json().faces as { person: { name: string } | null }[]).map((f) => f.person?.name ?? null).sort()).toEqual(["Martim Costa", null].sort()); - // The club sees the game but not the gala: no look-alike from there. + // The club sees the game but not the gala: no look-alike from there, and not that photo. const club = await signIn("abc"); + res = await get(club, `/v1/archive/photos/${gala.id}`); + expect(res.statusCode).toBe(404); res = await get(club, `/v1/archive/${source.id}/people/${martim.id}`); expect(res.json().counts).toEqual({ confirmed: 2, probable: 0, similar: 0 }); res = await get(club, `/v1/archive/${source.id}/faces/${f1.id}/similar`); diff --git a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx index bf83190..1db15e3 100644 --- a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx +++ b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx @@ -1,6 +1,7 @@ "use client"; import { useCallback, useEffect, useMemo, useState } from "react"; +import { useRouter } from "next/navigation"; import type { ArchiveInfo } from "./page"; interface GalleryCard { @@ -60,6 +61,13 @@ interface PersonCard { 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; +} + interface GalleryDetail { id: string; title: string; @@ -67,6 +75,8 @@ interface GalleryDetail { competition: string | null; startsAt: string | null; cloudUrl: string; + total?: number; + people?: GalleryPerson[]; photos: ArchivePhoto[]; } @@ -107,7 +117,7 @@ async function call(path: string, token: string | null, init: RequestInit = { return { status: res.status, body: (await res.json()) as T }; } -export function ArchiveView({ info }: { info: ArchiveInfo }) { +export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View }) { const [token, setToken] = useState(null); const [viewer, setViewer] = useState(null); const [ready, setReady] = useState(false); @@ -162,7 +172,7 @@ export function ArchiveView({ info }: { info: ArchiveInfo }) { )} {token ? ( - + ) : ( } /** Where the viewer is: browsing, in a gallery, on a person's photos, or on "more of this face". */ -type View = { kind: "browse" } | { kind: "gallery"; id: string } | { kind: "person"; id: string } | { kind: "face"; id: string }; +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" }; @@ -329,8 +339,9 @@ function PersonFace({ p, size }: { p: Pick void }) { - const [view, setView] = useState({ kind: "browse" }); +function Browse({ info, token, onExpired, start }: { info: ArchiveInfo; token: string; onExpired: () => void; start?: View }) { + const router = useRouter(); + const view = start ?? { kind: "browse" as const }; const [tab, setTab] = useState("galleries"); const [q, setQ] = useState(""); const [team, setTeam] = useState(null); @@ -348,10 +359,15 @@ function Browse({ info, token, onExpired }: { info: ArchiveInfo; token: string; [onExpired], ); - const go = useCallback((v: View) => { - setView(v); - window.scrollTo({ top: 0 }); - }, []); + const go = useCallback( + (v: View) => { + const base = `/arquivo/${info.id}`; + const href = v.kind === "browse" ? base : 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 }); + }, + [info.id, router], + ); const fetchPage = useCallback( (offset: number) => { @@ -661,6 +677,7 @@ function PhotosOf({ index={index} onIndex={setIndex} token={token} + onLoaded={(photoId, faces) => setData((cur) => (cur ? { ...cur, photos: cur.photos.map((p) => (p.id === photoId ? { ...p, faces } : p)) } : cur))} onFace={onFace} onPerson={onPerson} extra={(p) => @@ -686,6 +703,8 @@ function Lightbox({ photos, index, onIndex, + token, + onLoaded, onFace, onPerson, extra, @@ -694,12 +713,28 @@ function Lightbox({ index: number; onIndex: (i: number | null) => void; token: string; + onLoaded: (photoId: string, faces: PhotoFace[]) => void; onFace: (faceId: string) => void; onPerson: (personId: string) => void; extra?: (p: ArchivePhoto) => React.ReactNode; }) { const current = photos[index]!; const [showFaces, setShowFaces] = useState(true); + useEffect(() => { + if (current.faces) return; + let cancel = false; + call<{ faces: PhotoFace[] }>(`/v1/archive/photos/${current.id}`, token).then( + ({ body }) => { + if (!cancel) onLoaded(current.id, body.faces); + }, + () => { + if (!cancel) onLoaded(current.id, []); + }, + ); + return () => { + cancel = true; + }; + }, [current.id, current.faces, token, onLoaded]); useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onIndex(null); @@ -807,26 +842,46 @@ function Gallery({ const [error, setError] = useState(false); const [attempt, setAttempt] = useState(0); + const fetchPage = useCallback( + (offset: number, person: string | null) => { + const params = new URLSearchParams({ offset: String(offset), limit: "48" }); + if (person) params.set("person", person); + return call(`/v1/archive/galleries/${id}?${params}`, token).then(({ body }) => body); + }, + [id, token], + ); + const applyPage = useCallback((offset: number, body: GalleryDetail) => { + setG((cur) => { + const people = body.people ?? cur?.people; + const photos = offset === 0 ? body.photos : [...(cur?.photos ?? []), ...body.photos]; + return { ...body, people, photos, total: body.total ?? photos.length }; + }); + }, []); useEffect(() => { - call(`/v1/archive/galleries/${id}`, token).then( - ({ body }) => setG(body), - (err) => (err instanceof Unauthorised ? onExpired() : setError(true)), + let cancel = false; + setError(false); + setIndex(null); + fetchPage(0, only).then( + (body) => { + if (!cancel) applyPage(0, body); + }, + (err) => { + if (cancel) return; + if (err instanceof Unauthorised) onExpired(); + else setError(true); + }, ); - }, [id, token, onExpired, attempt]); + return () => { + cancel = true; + }; + }, [fetchPage, applyPage, only, onExpired, attempt]); - // Who is in this gallery: named faces first (with a face to show), then names written on the photos. - const people = useMemo(() => { - const byId = new Map(); - for (const p of g?.photos ?? []) - for (const f of p.faces ?? []) { - if (!f.person || f.level !== "confirmed") continue; - const cur = byId.get(f.person.id); - if (cur) cur.count++; - else byId.set(f.person.id, { id: f.person.id, name: f.person.name, count: 1, face: { src: p.preview, box: f.box, aspect: p.width && p.height ? p.width / p.height : 1.5 } }); - } - return [...byId.values()].sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)); - }, [g]); - const photos = useMemo(() => (g ? (only ? g.photos.filter((p) => (p.faces ?? []).some((f) => f.person?.id === only && f.level === "confirmed")) : g.photos) : []), [g, only]); + const people = g?.people ?? []; + const photos = g?.photos ?? []; + const total = g?.total ?? photos.length; + const rememberFaces = useCallback((photoId: string, faces: PhotoFace[]) => { + setG((cur) => (cur ? { ...cur, photos: cur.photos.map((p) => (p.id === photoId ? { ...p, faces } : p)) } : cur)); + }, []); if (error) return ( @@ -852,7 +907,7 @@ function Gallery({ ← Galerias - {[g.competition, g.startsAt ? day.format(new Date(g.startsAt)) : null].filter(Boolean).join(" · ")} · {photos.length} fotos + {[g.competition, g.startsAt ? day.format(new Date(g.startsAt)) : null].filter(Boolean).join(" · ")} · {total} fotos Abrir a pasta na cloud @@ -867,7 +922,13 @@ function Gallery({ {people.map((p) => (
  • @@ -883,7 +944,14 @@ function Gallery({ ))} - {index !== null && photos[index] && } + {photos.length < total && ( +

    + +

    + )} + {index !== null && photos[index] && } ); } diff --git a/apps/site/src/app/arquivo/[id]/f/[faceId]/page.tsx b/apps/site/src/app/arquivo/[id]/f/[faceId]/page.tsx new file mode 100644 index 0000000..e9a73f0 --- /dev/null +++ b/apps/site/src/app/arquivo/[id]/f/[faceId]/page.tsx @@ -0,0 +1,20 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { ArchiveFrame } from "../../frame"; +import { load } from "../../load"; + +type Params = { params: Promise<{ id: string; faceId: string }> }; + +const UUID = /^[0-9a-f-]{36}$/i; + +export async function generateMetadata({ params }: Params): Promise { + const { id } = await params; + const info = await load(id); + return { title: `Cara · ${info.name}`, robots: { index: false } }; +} + +export default async function FacePage({ params }: Params) { + const { id, faceId } = await params; + if (!UUID.test(faceId)) notFound(); + return ; +} diff --git a/apps/site/src/app/arquivo/[id]/frame.tsx b/apps/site/src/app/arquivo/[id]/frame.tsx new file mode 100644 index 0000000..72e54f9 --- /dev/null +++ b/apps/site/src/app/arquivo/[id]/frame.tsx @@ -0,0 +1,14 @@ +import { ArchiveView, type View } from "./ArchiveView"; +import { load } from "./load"; + +/** The archive shell: the owner's look, then the page the URL asked for. */ +export async function ArchiveFrame({ id, start }: { id: string; start?: View }) { + const info = await load(id); + const view = ; + if (!info.look) return view; + return ( +
    + {view} +
    + ); +} diff --git a/apps/site/src/app/arquivo/[id]/g/[folderId]/page.tsx b/apps/site/src/app/arquivo/[id]/g/[folderId]/page.tsx new file mode 100644 index 0000000..d24e1e0 --- /dev/null +++ b/apps/site/src/app/arquivo/[id]/g/[folderId]/page.tsx @@ -0,0 +1,20 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { ArchiveFrame } from "../../frame"; +import { load } from "../../load"; + +type Params = { params: Promise<{ id: string; folderId: string }> }; + +const UUID = /^[0-9a-f-]{36}$/i; + +export async function generateMetadata({ params }: Params): Promise { + const { id } = await params; + const info = await load(id); + return { title: `Galeria · ${info.name}`, robots: { index: false } }; +} + +export default async function GalleryPage({ params }: Params) { + const { id, folderId } = await params; + if (!UUID.test(folderId)) notFound(); + return ; +} diff --git a/apps/site/src/app/arquivo/[id]/layout.tsx b/apps/site/src/app/arquivo/[id]/layout.tsx new file mode 100644 index 0000000..ed87c34 --- /dev/null +++ b/apps/site/src/app/arquivo/[id]/layout.tsx @@ -0,0 +1,15 @@ +import type { ReactNode } from "react"; +import "@fontsource/bebas-neue/400.css"; +import "@fontsource/source-sans-3/400.css"; +import "@fontsource/source-sans-3/600.css"; +import "@fontsource/source-sans-3/700.css"; +import "@fontsource/open-sans/400.css"; +import "@fontsource/open-sans/600.css"; +import "@fontsource/open-sans/700.css"; +import "@fontsource/open-sans/800.css"; + +export const dynamic = "force-dynamic"; + +export default function ArchiveLayout({ children }: { children: ReactNode }) { + return children; +} diff --git a/apps/site/src/app/arquivo/[id]/load.ts b/apps/site/src/app/arquivo/[id]/load.ts new file mode 100644 index 0000000..a84ea24 --- /dev/null +++ b/apps/site/src/app/arquivo/[id]/load.ts @@ -0,0 +1,20 @@ +import { notFound } from "next/navigation"; + +const API = process.env.API_URL ?? "http://localhost:3000"; + +export interface ArchiveInfo { + id: string; + name: string; + cloud: string; + organization: string; + /** The owner's colours and type (Liga Portugal, FPA), or PhotoReport's. */ + look?: "liga" | "fpa" | null; +} + +export async function load(id: string): Promise { + if (!/^[0-9a-f-]{36}$/i.test(id)) notFound(); + const res = await fetch(`${API}/v1/archive/${id}`, { cache: "no-store" }); + if (res.status === 404 || res.status === 400) notFound(); + if (!res.ok) throw new Error(`archive ${id}: ${res.status}`); + return (await res.json()) as ArchiveInfo; +} diff --git a/apps/site/src/app/arquivo/[id]/p/[personId]/page.tsx b/apps/site/src/app/arquivo/[id]/p/[personId]/page.tsx new file mode 100644 index 0000000..a7ff1db --- /dev/null +++ b/apps/site/src/app/arquivo/[id]/p/[personId]/page.tsx @@ -0,0 +1,20 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { ArchiveFrame } from "../../frame"; +import { load } from "../../load"; + +type Params = { params: Promise<{ id: string; personId: string }> }; + +const UUID = /^[0-9a-f-]{36}$/i; + +export async function generateMetadata({ params }: Params): Promise { + const { id } = await params; + const info = await load(id); + return { title: `Pessoa · ${info.name}`, robots: { index: false } }; +} + +export default async function PersonPage({ params }: Params) { + const { id, personId } = await params; + if (!UUID.test(personId)) notFound(); + return ; +} diff --git a/apps/site/src/app/arquivo/[id]/page.tsx b/apps/site/src/app/arquivo/[id]/page.tsx index d77c34d..11fead1 100644 --- a/apps/site/src/app/arquivo/[id]/page.tsx +++ b/apps/site/src/app/arquivo/[id]/page.tsx @@ -1,38 +1,11 @@ import type { Metadata } from "next"; -import { notFound } from "next/navigation"; -import "@fontsource/bebas-neue/400.css"; -import "@fontsource/source-sans-3/400.css"; -import "@fontsource/source-sans-3/600.css"; -import "@fontsource/source-sans-3/700.css"; -import "@fontsource/open-sans/400.css"; -import "@fontsource/open-sans/600.css"; -import "@fontsource/open-sans/700.css"; -import "@fontsource/open-sans/800.css"; -import { ArchiveView } from "./ArchiveView"; +import { ArchiveFrame } from "./frame"; +import { load } from "./load"; -export const dynamic = "force-dynamic"; - -const API = process.env.API_URL ?? "http://localhost:3000"; +export type { ArchiveInfo } from "./load"; type Params = { params: Promise<{ id: string }> }; -export interface ArchiveInfo { - id: string; - name: string; - cloud: string; - organization: string; - /** The owner's colours and type (Liga Portugal, FPA), or PhotoReport's. */ - look?: "liga" | "fpa" | null; -} - -async function load(id: string): Promise { - if (!/^[0-9a-f-]{36}$/i.test(id)) notFound(); - const res = await fetch(`${API}/v1/archive/${id}`, { cache: "no-store" }); - if (res.status === 404 || res.status === 400) notFound(); - if (!res.ok) throw new Error(`archive ${id}: ${res.status}`); - return (await res.json()) as ArchiveInfo; -} - export async function generateMetadata({ params }: Params): Promise { const info = await load((await params).id); return { title: `Arquivo · ${info.name}`, robots: { index: false } }; @@ -43,11 +16,5 @@ export async function generateMetadata({ params }: Params): Promise { * authorise), and see the galleries of the folders shared with them. */ export default async function ArchivePage({ params }: Params) { - const info = await load((await params).id); - if (!info.look) return ; - return ( -
    - -
    - ); + return ; } diff --git a/docs/archive.md b/docs/archive.md index 72bdcef..6f194f7 100644 --- a/docs/archive.md +++ b/docs/archive.md @@ -125,10 +125,16 @@ 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 gives the page a 12 h signed session (`Authorization: Archive `) listing the archive folders shared -with them; 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. Galleries, a team list and a player list (from the photos' players) -search within what they may see; originals open on the cloud itself (`/f/`). +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, +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 +link survives refresh. A gallery page is 48 thumbs; the faces of a photo load when that photo is opened. The row +of people in a gallery is one query on that folder. People, similar faces and the player directory join +`cloud_files` for the source (and the viewer's folders when they do not see everything) instead of loading every +photo id. Originals still open on the cloud itself (`/f/`). ### People and faces (viewers too) -- 2.47.3