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/migrations/20261018230000_archive_face_review/migration.sql b/apps/api/prisma/migrations/20261018230000_archive_face_review/migration.sql new file mode 100644 index 0000000..ccfb384 --- /dev/null +++ b/apps/api/prisma/migrations/20261018230000_archive_face_review/migration.sql @@ -0,0 +1,32 @@ +-- Archive viewers with edit rights on the cloud review faces; a person's recognition can be turned off. +ALTER TABLE "archive_grants" ADD COLUMN "edits_all" BOOLEAN NOT NULL DEFAULT false; +ALTER TABLE "archive_grant_folders" ADD COLUMN "can_edit" BOOLEAN NOT NULL DEFAULT false; + +ALTER TABLE "people" ADD COLUMN "recognition_off_at" TIMESTAMP(3); +ALTER TABLE "people" ADD COLUMN "recognition_off_by" TEXT; + +CREATE TABLE "face_group_rejections" ( + "group_id" UUID NOT NULL, + "person_id" UUID NOT NULL, + "by" TEXT NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "face_group_rejections_pkey" PRIMARY KEY ("group_id","person_id") +); +CREATE INDEX "face_group_rejections_person_id_idx" ON "face_group_rejections"("person_id"); +ALTER TABLE "face_group_rejections" ADD CONSTRAINT "face_group_rejections_group_id_fkey" FOREIGN KEY ("group_id") REFERENCES "face_groups"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "face_group_rejections" ADD CONSTRAINT "face_group_rejections_person_id_fkey" FOREIGN KEY ("person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +CREATE TABLE "archive_face_actions" ( + "id" UUID NOT NULL, + "source_id" UUID NOT NULL, + "person_id" UUID, + "group_id" UUID, + "viewer" TEXT NOT NULL, + "action" TEXT NOT NULL, + "faces" INTEGER NOT NULL DEFAULT 0, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "archive_face_actions_pkey" PRIMARY KEY ("id") +); +CREATE INDEX "archive_face_actions_person_id_created_at_idx" ON "archive_face_actions"("person_id", "created_at"); +CREATE INDEX "archive_face_actions_source_id_created_at_idx" ON "archive_face_actions"("source_id", "created_at"); +ALTER TABLE "archive_face_actions" ADD CONSTRAINT "archive_face_actions_source_id_fkey" FOREIGN KEY ("source_id") REFERENCES "cloud_sources"("id") ON DELETE CASCADE ON UPDATE CASCADE; 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 2afce18..36475e7 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -651,12 +651,17 @@ model Person { referenceEmbedding Float[] @default([]) @map("reference_embedding") /// The squad entry this person came from (kept in step when squads change). sportsPlayerId String? @map("sports_player_id") @db.Uuid + /// Face recognition turned off for this person (an archive editor): no centroid, no reference, never suggested; + /// still named by hand. + recognitionOffAt DateTime? @map("recognition_off_at") + recognitionOffBy String? @map("recognition_off_by") createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") - organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) - groups FaceGroup[] @relation("confirmed") - suggested FaceGroup[] @relation("suggested") + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + groups FaceGroup[] @relation("confirmed") + suggested FaceGroup[] @relation("suggested") + rejections FaceGroupRejection[] @@unique([organizationId, name]) @@unique([organizationId, sportsPlayerId]) @@ -683,9 +688,10 @@ model FaceGroup { organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) event Event @relation(fields: [eventId], references: [id], onDelete: Cascade) - person Person? @relation("confirmed", fields: [personId], references: [id], onDelete: SetNull) - suggested Person? @relation("suggested", fields: [suggestedPersonId], references: [id], onDelete: SetNull) + person Person? @relation("confirmed", fields: [personId], references: [id], onDelete: SetNull) + suggested Person? @relation("suggested", fields: [suggestedPersonId], references: [id], onDelete: SetNull) faces Face[] + rejections FaceGroupRejection[] @@index([eventId]) @@map("face_groups") @@ -1615,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") @@ -1628,6 +1636,7 @@ model CloudSource { folders CloudFolder[] files CloudFile[] grants ArchiveGrant[] + faceActions ArchiveFaceAction[] @@index([organizationId]) @@map("cloud_sources") @@ -1700,6 +1709,16 @@ model ArchiveGrant { sourceId String @map("source_id") @db.Uuid viewerName String @map("viewer_name") seesAll Boolean @default(false) @map("sees_all") + /// May review faces everywhere in the source (the indexing account, or a share of its root with edit rights), + /// and turn a person's recognition off. + editsAll Boolean @default(false) @map("edits_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") @@ -1711,8 +1730,11 @@ model ArchiveGrant { } model ArchiveGrantFolder { - grantId String @map("grant_id") @db.Uuid - folderId String @map("folder_id") @db.Uuid + grantId String @map("grant_id") @db.Uuid + folderId String @map("folder_id") @db.Uuid + /// Shared with edit rights on the cloud (update or create): its faces, and those of the folders below, may be + /// reviewed by this viewer. + canEdit Boolean @default(false) @map("can_edit") grant ArchiveGrant @relation(fields: [grantId], references: [id], onDelete: Cascade) folder CloudFolder @relation(fields: [folderId], references: [id], onDelete: Cascade) @@ -1721,3 +1743,37 @@ model ArchiveGrantFolder { @@index([folderId]) @@map("archive_grant_folders") } + +/// "Não é": a face group said not to be this person; never suggested as them again. +model FaceGroupRejection { + groupId String @map("group_id") @db.Uuid + personId String @map("person_id") @db.Uuid + /// Who said so (an archive viewer's name on the cloud, or a user). + by String + createdAt DateTime @default(now()) @map("created_at") + + group FaceGroup @relation(fields: [groupId], references: [id], onDelete: Cascade) + person Person @relation(fields: [personId], references: [id], onDelete: Cascade) + + @@id([groupId, personId]) + @@index([personId]) + @@map("face_group_rejections") +} + +/// What archive viewers did to faces (confirm, "não é", false positive, recognition off): the person's history. +model ArchiveFaceAction { + id String @id @default(uuid()) @db.Uuid + sourceId String @map("source_id") @db.Uuid + personId String? @map("person_id") @db.Uuid + groupId String? @map("group_id") @db.Uuid + viewer String + action String + faces Int @default(0) + createdAt DateTime @default(now()) @map("created_at") + + source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade) + + @@index([personId, createdAt]) + @@index([sourceId, createdAt]) + @@map("archive_face_actions") +} diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index bcb543c..34bcb16 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -143,15 +143,15 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give // Photos whose IPTC changes go again to where they went. await registerPhotoRoutes(app, { db, sessions, storage, signer, broadcaster, archive, resend: (orgId, ids) => delivery.resendPhotos(orgId, ids) }); await registerArchiveRoutes(app, { db, sessions, archive, storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9 }); - await registerArchiveViewerRoutes(app, { db, secrets, signer, archive, tokens: new ViewerTokens(config.JWT_SECRET), fetchImpl }); + // 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, 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 }); const ingest = new IngestService({ db, storage, signer, broadcaster, ingestRoot: config.INGEST_ROOT, log: app.log }); ingest.arrivals = (photo) => delivery.queueArrival(photo); await registerUploadRoutes(app, { db, sessions, ingest, storage, signer }); - // 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 }); // The worker writes the heartbeat. Tests have no worker, so they say the engine is on unless a case says otherwise. const facesOnline = engineOnline ?? (() => (config.NODE_ENV === "test" ? true : faceEnginePaths(config) !== null && faceWorkerLive(config.STORAGE_ROOT))); await registerFaceRoutes(app, { db, sessions, faces, signer, storage, engineOnline: facesOnline }); 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/nextcloud.ts b/apps/api/src/archive/nextcloud.ts index 2bff5dc..c074371 100644 --- a/apps/api/src/archive/nextcloud.ts +++ b/apps/api/src/archive/nextcloud.ts @@ -215,14 +215,24 @@ export class CloudClient { return res; } - /** The file ids of everything shared with this account (by person or group), and its own login. */ - async sharedWithMe(): Promise { + /** + * The file ids of everything shared with this account (by person or group), and whether it may change them + * there: a share's `permissions` with update (2) or create (4). The same file shared twice keeps the wider right. + */ + async sharedWithMe(): Promise<{ id: string; canEdit: boolean }[]> { const res = await this.call("GET", `${this.base}/ocs/v2.php/apps/files_sharing/api/v1/shares?shared_with_me=true&format=json`, { headers: { "OCS-APIRequest": "true", accept: "application/json" }, }); if (!res.ok) throw new NextcloudError(`shares failed: ${res.status}`, res.status); - const body = (await res.json()) as { ocs?: { data?: { item_source?: number | string; file_source?: number | string }[] } }; - return [...new Set((body.ocs?.data ?? []).map((s) => String(s.item_source ?? s.file_source ?? "")).filter(Boolean))]; + const body = (await res.json()) as { ocs?: { data?: { item_source?: number | string; file_source?: number | string; permissions?: number | string }[] } }; + const out = new Map(); + for (const s of body.ocs?.data ?? []) { + const id = String(s.item_source ?? s.file_source ?? ""); + if (!id) continue; + const canEdit = (Number(s.permissions ?? 1) & (2 | 4)) !== 0; + out.set(id, (out.get(id) ?? false) || canEdit); + } + return [...out].map(([id, canEdit]) => ({ id, canEdit })); } /** The account's display name (and checks the app password). */ diff --git a/apps/api/src/archive/people.ts b/apps/api/src/archive/people.ts index c639e20..3967da6 100644 --- a/apps/api/src/archive/people.ts +++ b/apps/api/src/archive/people.ts @@ -364,12 +364,12 @@ export async function facesOfPhotos( ) { const all = await db.face.findMany({ where: { photoId: { in: photos.map((p) => p.id) } }, - select: { id: true, photoId: true, x0: true, y0: true, x1: true, y1: true, sharpness: true, group: { select: { ignoredAt: true, person: { select: { id: true, name: true } }, suggested: { select: { id: true, name: true } } } } }, + select: { id: true, photoId: true, groupId: true, x0: true, y0: true, x1: true, y1: true, sharpness: true, group: { select: { ignoredAt: true, person: { select: { id: true, name: true } }, suggested: { select: { id: true, name: true } } } } }, orderBy: { x0: "asc" }, }); const byPhoto = new Map(); for (const f of all) byPhoto.set(f.photoId, [...(byPhoto.get(f.photoId) ?? []), f]); - const out = new Map; person: { id: string; name: string } | null; level: "confirmed" | "probable" | null }[]>(); + const out = new Map; person: { id: string; name: string } | null; level: "confirmed" | "probable" | null }[]>(); for (const p of photos) { const list = byPhoto.get(p.id) ?? []; const focused = new Set(inFocus(list).map((f) => f.id)); @@ -379,7 +379,7 @@ export async function facesOfPhotos( .filter((f) => !f.group?.ignoredAt && (focused.has(f.id) || f.group?.person)) .map((f) => { const who = f.group?.person ?? f.group?.suggested ?? null; - return { id: f.id, box: faceBox(f, p), person: who, level: f.group?.person ? "confirmed" : f.group?.suggested ? "probable" : null }; + return { id: f.id, groupId: f.groupId, box: faceBox(f, p), person: who, level: f.group?.person ? "confirmed" : f.group?.suggested ? "probable" : null }; }), ); } diff --git a/apps/api/src/archive/review.ts b/apps/api/src/archive/review.ts new file mode 100644 index 0000000..546c458 --- /dev/null +++ b/apps/api/src/archive/review.ts @@ -0,0 +1,279 @@ +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 { FaceRejected, type FaceService } from "../faces/service.js"; +import { AppError, forbidden, notFound } from "../lib/errors.js"; +import type { UrlSigner } from "../storage/storage.js"; +import { faceBox } from "./people.js"; +import type { Viewer } from "./viewer.js"; + +/** + * Face review for archive viewers who may edit on the cloud. Rights come from the cloud, never from here: + * + * - a folder shared with them with edit rights (update or create) lets them review the faces of its photos (and of + * the folders below): confirm a suggestion, say "não é", mark a false positive, name an unnamed face, undo; + * - the indexing account, or a share of the root with edit rights, may also act on a person as a whole: turn their + * recognition off, take back every suggestion, drop a wrong reference photo. + * + * A face group spans a whole event; it may be changed only when every photo of it is in folders the viewer edits. + */ +interface Deps { + db: Db; + signer: UrlSigner; + faces: FaceService; + viewerOf: (req: FastifyRequest, sourceId?: string) => Viewer; + editableFolders: (v: Viewer) => Promise; +} + +const SourceParams = z.object({ sourceId: z.uuid() }); +const GroupParams = SourceParams.extend({ groupId: z.uuid() }); +const PersonParams = SourceParams.extend({ personId: z.uuid() }); +const Status = z.enum(["suggested", "unnamed", "confirmed", "rejected", "ignored"]); +const ReviewQuery = z.object({ + status: Status.default("suggested"), + person: z.uuid().optional(), + offset: z.coerce.number().int().min(0).default(0), + limit: z.coerce.number().int().min(1).max(120).default(60), +}); +const Act = z.object({ action: z.enum(["confirm", "reject", "ignore", "undo"]), personId: z.uuid().optional() }); +const Recognition = z.object({ enabled: z.boolean(), removeConfirmed: z.boolean().default(false) }); + +export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: Deps) { + const { db, signer, faces, viewerOf, editableFolders } = deps; + + /** Indexed files of the source the viewer may edit, as a condition on `cf`; null when none. */ + const editScope = async (v: Viewer): Promise<{ sql: Prisma.Sql; all: boolean } | null> => { + const editable = await editableFolders(v); + if (editable !== "all" && !editable.length) return null; + const base = Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`; + return editable === "all" ? { sql: base, all: true } : { sql: Prisma.sql`${base} AND cf.folder_id = ANY(${editable}::uuid[])`, all: false }; + }; + + const log = (v: Viewer, action: string, data: { personId?: string | null; groupId?: string | null; faces?: number }) => + db.archiveFaceAction.create({ data: { sourceId: v.s, viewer: v.n, action, personId: data.personId ?? null, groupId: data.groupId ?? null, faces: data.faces ?? 0 } }); + + /** What this viewer may do: review faces (some folder with edit rights), act on people (edits everything). */ + app.get("/v1/archive/:sourceId/me", async (req) => { + const { sourceId } = SourceParams.parse(req.params); + const v = viewerOf(req, sourceId); + const editable = await editableFolders(v); + const canReview = editable === "all" || editable.length > 0; + const pending = canReview + ? await (async () => { + const scope = await editScope(v); + if (!scope) return 0; + const [row] = await db.$queryRaw<{ n: number }[]>` + SELECT count(DISTINCT g.id)::int AS n + FROM face_groups g JOIN faces f ON f.group_id = g.id JOIN cloud_files cf ON cf.photo_id = f.photo_id + WHERE g.person_id IS NULL AND g.suggested_person_id IS NOT NULL AND g.ignored_at IS NULL AND ${scope.sql}`; + return row?.n ?? 0; + })() + : 0; + return { name: v.n, canReview, canManagePeople: editable === "all", pending }; + }); + + /** + * Face groups to review in the viewer's editable folders, one card per group: its sharpest faces, who it is + * (named) or might be (suggested, with how sure), its event; and the people with suggestions waiting. + */ + app.get("/v1/archive/:sourceId/review", async (req) => { + const { sourceId } = SourceParams.parse(req.params); + const v = viewerOf(req, sourceId); + const query = ReviewQuery.parse(req.query); + const scope = await editScope(v); + if (!scope) throw forbidden("archive_edit_required"); + const condition: Record, Prisma.Sql> = { + suggested: Prisma.sql`g.person_id IS NULL AND g.suggested_person_id IS NOT NULL AND g.ignored_at IS NULL`, + unnamed: Prisma.sql`g.person_id IS NULL AND g.suggested_person_id IS NULL AND g.ignored_at IS NULL AND g.size >= 2`, + confirmed: Prisma.sql`g.person_id IS NOT NULL AND g.ignored_at IS NULL`, + rejected: Prisma.sql`g.person_id IS NULL AND g.ignored_at IS NULL AND EXISTS (SELECT 1 FROM face_group_rejections r WHERE r.group_id = g.id)`, + ignored: Prisma.sql`g.ignored_at IS NOT NULL`, + }; + const person = query.person ? Prisma.sql`AND (g.person_id = ${query.person}::uuid OR g.suggested_person_id = ${query.person}::uuid OR EXISTS (SELECT 1 FROM face_group_rejections r WHERE r.group_id = g.id AND r.person_id = ${query.person}::uuid))` : Prisma.empty; + const [groups, counts, queue] = await Promise.all([ + db.$queryRaw<{ id: string; event_id: string; person_id: string | null; suggested_person_id: string | null; suggestion_score: number | null; ignored_at: Date | null; size: number; photos: number }[]>` + SELECT g.id, g.event_id, g.person_id, g.suggested_person_id, g.suggestion_score, g.ignored_at, g.size, count(DISTINCT f.photo_id)::int AS photos + FROM face_groups g + JOIN faces f ON f.group_id = g.id + JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql} + WHERE ${condition[query.status]} ${person} + GROUP BY g.id + ORDER BY g.suggestion_score DESC NULLS LAST, g.size DESC, g.id + OFFSET ${query.offset} LIMIT ${query.limit}`, + db.$queryRaw<{ status: string; n: number }[]>` + SELECT s.status, count(*)::int AS n FROM ( + SELECT DISTINCT g.id, + CASE WHEN g.ignored_at IS NOT NULL THEN 'ignored' + WHEN g.person_id IS NOT NULL THEN 'confirmed' + WHEN g.suggested_person_id IS NOT NULL THEN 'suggested' + WHEN EXISTS (SELECT 1 FROM face_group_rejections r WHERE r.group_id = g.id) THEN 'rejected' + WHEN g.size >= 2 THEN 'unnamed' END AS status + FROM face_groups g JOIN faces f ON f.group_id = g.id JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql} + WHERE TRUE ${person} + ) s WHERE s.status IS NOT NULL GROUP BY s.status`, + db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; groups: number }[]>` + SELECT p.id, p.name, p.club, p.number, p.reference_key IS NOT NULL AS reference, count(DISTINCT g.id)::int AS groups + FROM face_groups g + JOIN faces f ON f.group_id = g.id + JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql} + JOIN people p ON p.id = g.suggested_person_id + WHERE g.person_id IS NULL AND g.ignored_at IS NULL + GROUP BY p.id ORDER BY count(DISTINCT g.id) DESC, p.name LIMIT 200`, + ]); + + // Up to four of each group's sharpest faces in the editable photos, for the card. + const ids = groups.map((g) => g.id); + const samples = ids.length + ? await db.$queryRaw<{ group_id: string; id: string; photo_id: string; x0: number; y0: number; x1: number; y1: number }[]>` + SELECT group_id, id, photo_id, x0, y0, x1, y1 FROM ( + SELECT f.group_id, f.id, f.photo_id, f.x0, f.y0, f.x1, f.y1, + row_number() OVER (PARTITION BY f.group_id ORDER BY f.sharpness DESC NULLS LAST, f.score DESC) AS rank + FROM faces f JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql} + WHERE f.group_id = ANY(${ids}::uuid[]) + ) s WHERE rank <= 4` + : []; + const photos = await db.photo.findMany({ + where: { id: { in: [...new Set(samples.map((s) => s.photo_id))] } }, + select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true }, + }); + const photoById = new Map(photos.map((p) => [p.id, p])); + const peopleIds = [...new Set(groups.flatMap((g) => [g.person_id, g.suggested_person_id]).filter((x): x is string => !!x))]; + const [people, events, rejections] = await Promise.all([ + db.person.findMany({ where: { id: { in: peopleIds } }, select: { id: true, name: true, club: true, number: true, referenceKey: true, recognitionOffAt: true } }), + db.event.findMany({ where: { id: { in: [...new Set(groups.map((g) => g.event_id))] } } }), + db.faceGroupRejection.findMany({ where: { groupId: { in: ids } }, include: { person: { select: { id: true, name: true } } } }), + ]); + const personById = new Map(people.map((p) => [p.id, p])); + const eventById = new Map(events.map((e) => [e.id, e])); + const personOut = (id: string | null) => { + const p = id ? personById.get(id) : null; + return p ? { id: p.id, name: p.name, club: p.club, number: p.number, reference: p.referenceKey ? signer.personUrl(p.id) : null, recognitionOff: !!p.recognitionOffAt } : null; + }; + return { + status: query.status, + counts: Object.fromEntries(Status.options.map((s) => [s, counts.find((c) => c.status === s)?.n ?? 0])), + people: queue.map((p) => ({ id: p.id, name: p.name, club: p.club, number: p.number, reference: p.reference ? signer.personUrl(p.id) : null, waiting: p.groups })), + groups: groups.map((g) => { + const e = eventById.get(g.event_id); + return { + id: g.id, + size: g.size, + photos: g.photos, + score: g.suggestion_score, + person: personOut(g.person_id), + suggested: personOut(g.suggested_person_id), + ignored: !!g.ignored_at, + notThem: rejections.filter((r) => r.groupId === g.id).map((r) => ({ id: r.person.id, name: r.person.name, by: r.by })), + event: e ? { title: eventName(e), startsAt: e.startsAt } : null, + faces: samples + .filter((s) => s.group_id === g.id) + .flatMap((s) => { + const p = photoById.get(s.photo_id); + if (!p) return []; + return [{ id: s.id, photoId: s.photo_id, src: signer.url(s.photo_id, "preview", p.renderedSeq), box: faceBox(s, p), aspect: p.width && p.height ? p.width / p.height : 1.5 }]; + }), + }; + }), + }; + }); + + /** Confirm, "não é", false positive or undo, on one face group. */ + app.post("/v1/archive/:sourceId/review/groups/:groupId", async (req) => { + const { sourceId, groupId } = GroupParams.parse(req.params); + const v = viewerOf(req, sourceId); + const body = Act.parse(req.body); + const scope = await editScope(v); + if (!scope) throw forbidden("archive_edit_required"); + const group = await db.faceGroup.findFirst({ where: { id: groupId, organization: { cloudSources: { some: { id: sourceId } } } } }); + if (!group) throw notFound("group_not_found"); + // Every photo of the group must be one the viewer may edit (in this source). + const [rights] = await db.$queryRaw<{ total: number; editable: number }[]>` + SELECT count(DISTINCT f.photo_id)::int AS total, + count(DISTINCT f.photo_id) FILTER (WHERE EXISTS (SELECT 1 FROM cloud_files cf WHERE cf.photo_id = f.photo_id AND ${scope.sql}))::int AS editable + FROM faces f WHERE f.group_id = ${groupId}::uuid`; + if (!rights || rights.total === 0 || rights.editable < rights.total) throw forbidden("archive_edit_required"); + try { + if (body.action === "confirm") { + const personId = body.personId ?? group.suggestedPersonId; + if (!personId) throw new AppError(400, "person_required"); + const person = await faces.confirm(groupId, { personId }, null); + await log(v, "confirm", { personId: person.id, groupId, faces: group.size }); + } else if (body.action === "reject") { + const personId = body.personId ?? group.personId ?? group.suggestedPersonId; + if (!personId) throw new AppError(400, "person_required"); + await faces.reject(groupId, personId, v.n); + await log(v, "reject", { personId, groupId, faces: group.size }); + } else if (body.action === "ignore") { + await faces.ignore(groupId, true); + await log(v, "false_positive", { personId: group.personId ?? group.suggestedPersonId, groupId, faces: group.size }); + } else { + // Undo what is on the group now: a false positive, a name, then a "não é". + if (group.ignoredAt) await faces.ignore(groupId, false); + else if (group.personId) await faces.unconfirm(groupId); + else await faces.unreject(groupId); + await log(v, "undo", { personId: group.personId ?? group.suggestedPersonId, groupId, faces: group.size }); + } + } catch (err) { + if (err instanceof FaceRejected) throw new AppError(400, err.message); + throw err; + } + const after = await db.faceGroup.findUniqueOrThrow({ where: { id: groupId }, select: { personId: true, suggestedPersonId: true, ignoredAt: true } }); + return { id: groupId, personId: after.personId, suggestedPersonId: after.suggestedPersonId, ignored: !!after.ignoredAt }; + }); + + /** A person as a whole: only for whoever edits the whole archive on the cloud. */ + const manager = async (req: FastifyRequest) => { + const { sourceId, personId } = PersonParams.parse(req.params); + const v = viewerOf(req, sourceId); + if ((await editableFolders(v)) !== "all") throw forbidden("archive_edit_all_required"); + const person = await db.person.findFirst({ where: { id: personId, organization: { cloudSources: { some: { id: sourceId } } } } }); + if (!person) throw notFound("person_not_found"); + return { v, person }; + }; + + /** Turns a person's face recognition off (with, optionally, the names already given) or on again. */ + app.post("/v1/archive/:sourceId/people/:personId/recognition", async (req) => { + const { v, person } = await manager(req); + const body = Recognition.parse(req.body); + const done = await faces.recognition(person.id, body.enabled, v.n, body.removeConfirmed); + await log(v, body.enabled ? "recognition_on" : body.removeConfirmed ? "recognition_off_all" : "recognition_off", { personId: person.id, faces: done.suggestions + done.confirmed }); + return { enabled: body.enabled, ...done }; + }); + + /** Takes back every open suggestion of a person (each becomes a "não é"). */ + app.post("/v1/archive/:sourceId/people/:personId/drop-suggestions", async (req) => { + const { v, person } = await manager(req); + const n = await faces.dropSuggestions(person.id, v.n); + await log(v, "drop_suggestions", { personId: person.id, faces: n }); + return { dropped: n }; + }); + + /** Drops a wrong reference photo. */ + app.delete("/v1/archive/:sourceId/people/:personId/reference", async (req) => { + const { v, person } = await manager(req); + await faces.dropReference(person.id); + await log(v, "drop_reference", { personId: person.id }); + return { ok: true }; + }); + + /** What was done to a person's faces in the archive, newest first (for editors). */ + app.get("/v1/archive/:sourceId/people/:personId/history", async (req) => { + const { sourceId, personId } = PersonParams.parse(req.params); + const v = viewerOf(req, sourceId); + const editable = await editableFolders(v); + if (editable !== "all" && !editable.length) throw forbidden("archive_edit_required"); + const [person, actions] = await Promise.all([ + db.person.findFirst({ where: { id: personId, organization: { cloudSources: { some: { id: sourceId } } } }, select: { recognitionOffAt: true, recognitionOffBy: true, referenceKey: true } }), + db.archiveFaceAction.findMany({ where: { sourceId, personId }, orderBy: { createdAt: "desc" }, take: 30 }), + ]); + if (!person) throw notFound("person_not_found"); + return { + recognitionOff: person.recognitionOffAt ? { at: person.recognitionOffAt, by: person.recognitionOffBy } : null, + hasReference: !!person.referenceKey, + canManage: editable === "all", + actions: actions.map((a) => ({ at: a.createdAt, viewer: a.viewer, action: a.action, faces: a.faces })), + }; + }); +} 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 5283889..e288650 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -7,19 +7,36 @@ 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"; /** * 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 +85,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(), @@ -79,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; 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; @@ -88,6 +105,113 @@ export async function registerArchiveViewerRoutes( return deps.secrets; }; + /** + * What a cloud account sees of a source, and where it may change things: everything (it indexes it, or a share + * of its root or above), or shared folders, each with whether it was shared with edit rights. + */ + type Shares = { all: boolean; editsAll: boolean; folders: { id: string; canEdit: boolean }[] }; + const readShares = async ( + source: { id: string; baseUrl: string; username: string; secretEnc: string | null; rootPath: string }, + viewer: CloudClient, + me: { id: string }, + ): Promise => { + if (me.id === source.username) return { all: true, editsAll: true, folders: [] }; + const shared = new Map((await viewer.sharedWithMe()).map((s) => [s.id, s.canEdit])); + const above = (await ancestorsOf(deps.archive.client(source), source.rootPath)).filter((id) => shared.has(id)); + if (above.length) { + const editsAll = above.some((id) => shared.get(id)); + // Seen whole, but edit rights may still come from a share further down. + const rows = editsAll ? [] : await db.cloudFolder.findMany({ where: { sourceId: source.id, fileId: { in: [...shared].filter(([, e]) => e).map(([id]) => id) } }, select: { id: true } }); + return { all: true, editsAll, folders: rows.map((r) => ({ id: r.id, canEdit: true })) }; + } + if (!shared.size) return { all: false, editsAll: false, folders: [] }; + const rows = await db.cloudFolder.findMany({ where: { sourceId: source.id, fileId: { in: [...shared.keys()] } }, select: { id: true, fileId: true } }); + return { all: false, editsAll: false, folders: rows.map((r) => ({ id: r.id, canEdit: !!shared.get(r.fileId) })) }; + }; + + /** 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 */ + } + }; + + /** + * 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. */ + type GrantAccess = { seesAll: boolean; editsAll: boolean; folders: { folderId: string; canEdit: boolean }[] }; + 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: GrantAccess & { id: string; sourceId: string; secretEnc: string; checkedAt: Date }): Promise => { + 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); + const folders = read.folders.map((f) => ({ folderId: f.id, canEdit: f.canEdit })); + await db.$transaction([ + db.archiveGrantFolder.deleteMany({ where: { grantId: grant.id } }), + ...(folders.length ? [db.archiveGrantFolder.createMany({ data: folders.map((f) => ({ grantId: grant.id, ...f })) })] : []), + db.archiveGrant.update({ where: { id: grant.id }, data: { seesAll: read.all, editsAll: read.editsAll, checkedAt: new Date() } }), + ]); + return { seesAll: read.all, editsAll: read.editsAll, 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, editsAll: grant.editsAll, folders: grant.folders }; + } + })().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; @@ -96,24 +220,12 @@ export async function registerArchiveViewerRoutes( return v; }; - /** - * 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 => { - 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"; + /** Shared folders and everything below them. */ + const below = async (sourceId: string, roots: string[]): Promise => { 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(${roots}::uuid[]) + SELECT id FROM cloud_folders WHERE source_id = ${sourceId}::uuid AND id = ANY(${roots}::uuid[]) UNION SELECT c.id FROM cloud_folders c JOIN tree t ON c.parent_id = t.id ) @@ -121,6 +233,41 @@ export async function registerArchiveViewerRoutes( return rows.map((r) => r.id); }; + /** A grant as it stands (read again from the cloud when due), its session slid forward when remembered. */ + const grantOf = async (v: Viewer): Promise => { + if (!v.g) return null; + const grant = await db.archiveGrant.findUnique({ where: { id: v.g }, include: { folders: { select: { folderId: true, canEdit: true } } } }); + const now = Date.now(); + if (!grant || grant.sourceId !== v.s || grant.expiresAt.getTime() <= now) throw unauthorized("archive_login_required"); + let access: GrantAccess = { seesAll: grant.seesAll, editsAll: grant.editsAll, folders: grant.folders }; + if (grant.secretEnc && now - grant.checkedAt.getTime() > RECHECK_MS) access = await recheck({ ...grant, secretEnc: grant.secretEnc }); + 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) } }); + return access; + }; + + /** + * 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 => { + const g = await grantOf(v); + if (!g) return v.all ? "all" : below(v.s, v.f ?? []); + if (g.seesAll) return "all"; + return below(v.s, g.folders.map((f) => f.folderId)); + }; + + /** + * Folders whose faces the viewer may review: those shared with them with edit rights on the cloud (and below), + * or all of them for the indexing account and a root share with edit rights. Sessions from before grants: none. + */ + const editableFolders = async (v: Viewer): Promise => { + const g = await grantOf(v); + if (!g) return []; + if (g.editsAll) return "all"; + return below(v.s, g.folders.filter((f) => f.canEdit).map((f) => f.folderId)); + }; + /** 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`; @@ -139,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`. */ @@ -156,7 +318,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 +333,49 @@ 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, editsAll, 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), - ...(!all && folders.length ? { folders: { create: folders.map((folderId) => ({ folderId })) } } : {}), + editsAll, + 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), + ...(folders.length ? { folders: { create: folders.map((f) => ({ folderId: f.id, canEdit: f.canEdit })) } } : {}), }, }); - 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: all ? 0 : 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"). @@ -275,21 +445,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 @@ -298,11 +485,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. */ @@ -314,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, @@ -380,10 +568,15 @@ 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). */ - 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. */ @@ -397,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}` }), })), }; }); @@ -418,6 +611,8 @@ 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/src/faces/service.ts b/apps/api/src/faces/service.ts index afa7513..07906d0 100644 --- a/apps/api/src/faces/service.ts +++ b/apps/api/src/faces/service.ts @@ -259,7 +259,12 @@ export class FaceService { await this.joinSamePerson(eventId); const groups = await db.faceGroup.findMany({ where: { eventId, personId: null, ignoredAt: null } }); if (!groups.length) return; - const everyone = await db.person.findMany({ where: { organizationId: groups[0]!.organizationId, NOT: { centroid: { isEmpty: true } } } }); + const everyone = await db.person.findMany({ where: { organizationId: groups[0]!.organizationId, recognitionOffAt: null, NOT: { centroid: { isEmpty: true } } } }); + // "Não é": a group is never suggested as someone it was said not to be. + const said = await db.faceGroupRejection.findMany({ where: { groupId: { in: groups.map((g) => g.id) } }, select: { groupId: true, personId: true } }); + const notThem = new Map>(); + for (const r of said) notThem.set(r.groupId, (notThem.get(r.groupId) ?? new Set()).add(r.personId)); + const off = new Set((await db.person.findMany({ where: { organizationId: groups[0]!.organizationId, recognitionOffAt: { not: null } }, select: { id: true } })).map((p) => p.id)); // Never someone of another sport (a footballer at a handball game): known by their squad's team. const sport = await eventSport(db, eventId); const sports = sport ? await peopleSports(db, everyone) : new Map(); @@ -280,8 +285,9 @@ export class FaceService { }; for (const g of groups) { const { match, margin } = this.thresholds(g.model); + const rejected = notThem.get(g.id); const ranked = candidates - .filter((p) => p.model === g.model) + .filter((p) => p.model === g.model && !rejected?.has(p.id)) .map((p) => ({ p, s: cosine(p.centroid, g.centroid) })) .sort((a, b) => b.s - a.s); const [first, second] = ranked; @@ -316,6 +322,10 @@ export class FaceService { if (byNumber) ({ personId: suggestedPersonId, score: suggestionScore } = byNumber); } } + if (suggestedPersonId && (rejected?.has(suggestedPersonId) || off.has(suggestedPersonId))) { + suggestedPersonId = null; + suggestionScore = null; + } if (g.suggestedPersonId !== suggestedPersonId || g.suggestionScore !== suggestionScore) { await db.faceGroup.update({ where: { id: g.id }, data: { suggestedPersonId, suggestionScore } }); } @@ -451,7 +461,7 @@ export class FaceService { } /** Names a group: an existing person, or a new one. Every photo with a face in the group gets the name. */ - async confirm(groupId: string, who: { personId: string } | { name: string; club?: string | undefined; number?: string | undefined }, userId: string): Promise { + async confirm(groupId: string, who: { personId: string } | { name: string; club?: string | undefined; number?: string | undefined }, userId: string | null): Promise { const { db } = this.deps; const group = await db.faceGroup.findUnique({ where: { id: groupId } }); if (!group) throw new FaceRejected("group_not_found"); @@ -491,6 +501,7 @@ export class FaceService { const person = await db.person.findUniqueOrThrow({ where: { id: personId } }); const groups = await db.faceGroup.findMany({ where: { personId } }); const model = groups[0]?.model ?? person.model ?? null; + if (person.recognitionOffAt) return db.person.update({ where: { id: personId }, data: { centroid: [], faceCount: groups.reduce((n, g) => n + g.size, 0) } }); const parts = groups.filter((g) => g.model === model).map((g) => ({ mean: g.centroid, count: g.size })); if (person.referenceEmbedding.length && person.model === model) parts.push({ mean: person.referenceEmbedding, count: 3 }); return db.person.update({ @@ -514,6 +525,10 @@ export class FaceService { try { if (!engine) throw new Error("face engine not configured"); const person = await db.person.findUniqueOrThrow({ where: { id: personId } }); + if (person.recognitionOffAt) { + await db.person.update({ where: { id: personId }, data: { referenceStatus: "NONE" } }); + return; + } if (!person.referenceKey) throw new Error("no reference photo"); const analysis = await engine.analyse(storage.resolve(person.referenceKey)); const best = analysis.faces @@ -568,6 +583,123 @@ export class FaceService { const group = await this.deps.db.faceGroup.update({ where: { id: groupId }, data: { ignoredAt: ignored ? new Date() : null } }); this.deps.broadcaster.library(group.organizationId, { type: "faces.updated", eventId: group.eventId }); } + + /** "Não é": the group is not this person; the next best guess (if any) is suggested instead. */ + async reject(groupId: string, personId: string, by: string): Promise { + const { db } = this.deps; + const group = await db.faceGroup.findUnique({ where: { id: groupId } }); + if (!group) throw new FaceRejected("group_not_found"); + const wasNamed = group.personId === personId; + await db.$transaction([ + db.faceGroupRejection.upsert({ where: { groupId_personId: { groupId, personId } }, create: { groupId, personId, by }, update: { by } }), + db.faceGroup.update({ + where: { id: groupId }, + data: { ...(group.suggestedPersonId === personId && { suggestedPersonId: null, suggestionScore: null }), ...(wasNamed && { personId: null, confirmedById: null }) }, + }), + ]); + if (wasNamed) await this.afterUnnamed(groupId, personId); + await this.refreshSuggestions(group.eventId); + this.deps.broadcaster.library(group.organizationId, { type: "faces.updated", eventId: group.eventId }); + } + + /** Takes a name off a group (back to unnamed, suggestions again). */ + async unconfirm(groupId: string): Promise { + const { db } = this.deps; + const group = await db.faceGroup.findUnique({ where: { id: groupId } }); + if (!group?.personId) return; + await db.faceGroup.update({ where: { id: groupId }, data: { personId: null, confirmedById: null } }); + await this.afterUnnamed(groupId, group.personId); + await this.refreshSuggestions(group.eventId); + this.deps.broadcaster.library(group.organizationId, { type: "faces.updated", eventId: group.eventId }); + } + + /** Undoes a "não é" for a group. */ + async unreject(groupId: string): Promise { + const { db } = this.deps; + const group = await db.faceGroup.findUnique({ where: { id: groupId } }); + if (!group) return; + await db.faceGroupRejection.deleteMany({ where: { groupId } }); + await this.refreshSuggestions(group.eventId); + this.deps.broadcaster.library(group.organizationId, { type: "faces.updated", eventId: group.eventId }); + } + + /** A group lost its name: the person's face is read again and the name leaves photos where nobody else is them. */ + private async afterUnnamed(groupId: string, personId: string): Promise { + const { db, broadcaster } = this.deps; + const person = await this.recomputePerson(personId); + const photoIds = [...new Set((await db.face.findMany({ where: { groupId }, select: { photoId: true } })).map((f) => f.photoId))]; + const photos = await db.photo.findMany({ + where: { id: { in: photoIds } }, + select: { id: true, organizationId: true, players: true, faces: { select: { group: { select: { personId: true } } } } }, + }); + for (const photo of photos) { + if (photo.faces.some((f) => f.group?.personId === personId) || !photo.players.includes(person.name)) continue; + const players = photo.players.filter((n) => n !== person.name); + await db.photo.update({ where: { id: photo.id }, data: { players } }); + broadcaster.library(photo.organizationId, { type: "photo.updated", ids: [photo.id], patch: { players } }); + } + } + + /** + * Turns a person's face recognition off: their face (centroid, reference photo) is dropped, every suggestion of + * them goes, and they are never suggested again; with `removeConfirmed`, the names already given go too. They + * can still be named by hand. Turning it on again starts from nothing: a reference photo or a confirmed face. + */ + async recognition(personId: string, on: boolean, by: string, removeConfirmed = false): Promise<{ suggestions: number; confirmed: number }> { + const { db, storage } = this.deps; + const person = await db.person.findUnique({ where: { id: personId } }); + if (!person) throw new FaceRejected("person_not_found"); + if (on) { + await db.person.update({ where: { id: personId }, data: { recognitionOffAt: null, recognitionOffBy: null } }); + await this.recomputePerson(personId); + return { suggestions: 0, confirmed: 0 }; + } + const suggested = await db.faceGroup.findMany({ where: { suggestedPersonId: personId }, select: { id: true, eventId: true } }); + const named = removeConfirmed ? await db.faceGroup.findMany({ where: { personId }, select: { id: true, eventId: true } }) : []; + await db.$transaction([ + db.person.update({ + where: { id: personId }, + data: { recognitionOffAt: new Date(), recognitionOffBy: by, centroid: [], referenceEmbedding: [], referenceKey: null, referenceStatus: "NONE" }, + }), + db.faceGroup.updateMany({ where: { suggestedPersonId: personId }, data: { suggestedPersonId: null, suggestionScore: null } }), + ...(named.length ? [db.faceGroup.updateMany({ where: { id: { in: named.map((g) => g.id) } }, data: { personId: null, confirmedById: null } })] : []), + ]); + if (person.referenceKey) await storage.remove(person.referenceKey).catch(() => undefined); + for (const g of named) await this.afterUnnamed(g.id, personId); + for (const eventId of new Set([...suggested, ...named].map((g) => g.eventId))) { + await this.refreshSuggestions(eventId); + this.deps.broadcaster.library(person.organizationId, { type: "faces.updated", eventId }); + } + return { suggestions: suggested.length, confirmed: named.length }; + } + + /** Every open suggestion of this person, taken back as "não é". */ + async dropSuggestions(personId: string, by: string): Promise { + const { db } = this.deps; + const groups = await db.faceGroup.findMany({ where: { suggestedPersonId: personId, personId: null }, select: { id: true, eventId: true, organizationId: true } }); + if (!groups.length) return 0; + await db.$transaction([ + db.faceGroupRejection.createMany({ data: groups.map((g) => ({ groupId: g.id, personId, by })), skipDuplicates: true }), + db.faceGroup.updateMany({ where: { id: { in: groups.map((g) => g.id) } }, data: { suggestedPersonId: null, suggestionScore: null } }), + ]); + for (const eventId of new Set(groups.map((g) => g.eventId))) { + await this.refreshSuggestions(eventId); + this.deps.broadcaster.library(groups[0]!.organizationId, { type: "faces.updated", eventId }); + } + return groups.length; + } + + /** Drops a wrong reference photo: the person's face is read again from what was confirmed. */ + async dropReference(personId: string): Promise { + const { db, storage } = this.deps; + const person = await db.person.findUnique({ where: { id: personId } }); + if (!person) throw new FaceRejected("person_not_found"); + await db.person.update({ where: { id: personId }, data: { referenceKey: null, referenceEmbedding: [], referenceStatus: "NONE" } }); + if (person.referenceKey) await storage.remove(person.referenceKey).catch(() => undefined); + await this.recomputePerson(personId); + const events = await db.faceGroup.findMany({ where: { suggestedPersonId: personId }, select: { eventId: true }, distinct: ["eventId"] }); + for (const e of events) await this.refreshSuggestions(e.eventId); + } } /** Keeps `processes` face engines busy. */ diff --git a/apps/api/test/archive.test.ts b/apps/api/test/archive.test.ts index a96fc68..1d69d6e 100644 --- a/apps/api/test/archive.test.ts +++ b/apps/api/test/archive.test.ts @@ -286,7 +286,7 @@ class FakeCloud { password = "app-pass-123"; /** Who authorises the next login flow, and the other accounts (viewers) with what is shared with them. */ loginAs = "peter"; - viewers = new Map(); + viewers = new Map(); revoked: string[] = []; idOf(p: string) { @@ -346,7 +346,8 @@ class FakeCloud { if (!who) return new Response(null, { status: 401 }); if (url.pathname === "/ocs/v2.php/cloud/user") return Response.json({ ocs: { data: { id: who, "display-name": who.toUpperCase() } } }); if (url.pathname === "/ocs/v2.php/apps/files_sharing/api/v1/shares") { - return Response.json({ ocs: { data: (this.viewers.get(who)?.shared ?? []).map((id) => ({ item_source: Number(id), share_type: 1 })) } }); + const v = this.viewers.get(who); + return Response.json({ ocs: { data: (v?.shared ?? []).map((id) => ({ item_source: Number(id), share_type: 1, permissions: v?.edit?.includes(id) ? 31 : 1 })) } }); } if (url.pathname === "/ocs/v2.php/core/apppassword" && method === "DELETE") { this.revoked.push(who); @@ -588,7 +589,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 +600,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 +612,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 +624,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 +637,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 () => { @@ -719,6 +742,125 @@ describe("archive from a Nextcloud", () => { expect(res.json().photos).toHaveLength(2); }); + it("lets those who edit on the cloud review faces, and only there", async () => { + const source = await connect(); + cloud.authorised = true; + await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); + await worker.scan(source.id); + for (const id of await worker.claim(10)) await worker.index(id); + + const unit = (v: number[]) => { + const n = Math.hypot(...v); + return v.map((x) => x / n); + }; + const martimVec = unit([1, 0.1, 0, 0]); + const photo = (name: string) => ctx.db.photo.findFirstOrThrow({ where: { originalName: name } }); + const [p1, p2, gala] = await Promise.all([photo("PS_0001.jpg"), photo("PS_0002.jpg"), photo("G_0001.jpg")]); + const martim = await ctx.db.person.create({ data: { organizationId: orgId, name: "Martim Costa", club: "Sporting CP", number: "21", centroid: martimVec, model: "auraface-v1" } }); + const group = (eventId: string, suggested: string | null) => + ctx.db.faceGroup.create({ data: { organizationId: orgId, eventId, centroid: unit([0, 1, 0, 0]), model: "auraface-v1", size: 1, suggestedPersonId: suggested, suggestionScore: suggested ? 0.8 : null } }); + const face = (photoId: string, groupId: string) => + ctx.db.face.create({ data: { organizationId: orgId, photoId, groupId, x0: 0.4, y0: 0.2, x1: 0.5, y1: 0.35, score: 0.9, sharpness: 120, embedding: unit([0, 1, 0, 0]), model: "auraface-v1" } }); + const g1 = await group(p1.eventId!, martim.id); + await face(p1.id, g1.id); + const g2 = await group(p2.eventId!, martim.id); + await face(p2.id, g2.id); + const gGala = await group(gala.eventId!, martim.id); + await face(gala.id, gGala.id); + + // A club editor (PO01 shared with edit rights) and a club reader (the same folder, read only). + const po01 = cloud.idOf("/FPA/Fotos/2025_2026/Competições Nacionais/PO01"); + cloud.viewers.set("abc", { password: "abc-pass", shared: [po01], edit: [po01] }); + cloud.viewers.set("leitor", { password: "l-pass", shared: [po01] }); + const signIn = async (who: string) => { + cloud.loginAs = who; + cloud.authorised = false; + const { state } = (await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` })).json() as { state: string }; + cloud.authorised = true; + return ((await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state } })).json() as { token: string }).token; + }; + const as = (t: string) => ({ authorization: `Archive ${t}` }); + const editor = await signIn("abc"); + const reader = await signIn("leitor"); + const owner = await signIn("peter"); + + let res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(editor) }); + expect(res.json()).toMatchObject({ canReview: true, canManagePeople: false, pending: 2 }); + res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(reader) }); + expect(res.json()).toMatchObject({ canReview: false, canManagePeople: false }); + res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(owner) }); + expect(res.json()).toMatchObject({ canReview: true, canManagePeople: true, pending: 3 }); + + // The editor sees the game's suggestions, not the gala's; the reader none. + res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/review`, headers: as(editor) }); + const review = res.json() as { counts: Record; groups: { id: string; suggested: { name: string } | null; faces: unknown[] }[] }; + expect(review.groups.map((g) => g.id).sort()).toEqual([g1.id, g2.id].sort()); + expect(review.groups[0]!.suggested?.name).toBe("Martim Costa"); + expect(review.groups[0]!.faces).toHaveLength(1); + expect(review.counts.suggested).toBe(2); + res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/review`, headers: as(reader) }); + expect(res.statusCode).toBe(403); + + const act = (t: string, groupId: string, payload: Record) => + ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/review/groups/${groupId}`, headers: as(t), payload }); + + // Confirm: the photo gets the name. + res = await act(editor, g1.id, { action: "confirm" }); + expect(res.json()).toMatchObject({ personId: martim.id, ignored: false }); + expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: p1.id } })).players).toContain("Martim Costa"); + // "Não é": never suggested as him again. + res = await act(editor, g2.id, { action: "reject" }); + expect(res.json()).toMatchObject({ suggestedPersonId: null }); + expect(await ctx.db.faceGroupRejection.count({ where: { groupId: g2.id, personId: martim.id } })).toBe(1); + // False positive, and undo. + res = await act(editor, g2.id, { action: "ignore" }); + expect(res.json()).toMatchObject({ ignored: true }); + res = await act(editor, g2.id, { action: "undo" }); + expect(res.json()).toMatchObject({ ignored: false }); + // Not in their folders, or read only: refused. + 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); + res = await off(owner, { enabled: false, removeConfirmed: true }); + expect(res.json()).toMatchObject({ enabled: false, confirmed: 1 }); + const after = await ctx.db.person.findUniqueOrThrow({ where: { id: martim.id } }); + expect(after.recognitionOffAt).not.toBeNull(); + expect(after.centroid).toEqual([]); + expect((await ctx.db.faceGroup.findUniqueOrThrow({ where: { id: g1.id } })).personId).toBeNull(); + expect((await ctx.db.faceGroup.findUniqueOrThrow({ where: { id: gGala.id } })).suggestedPersonId).toBeNull(); + expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: p1.id } })).players).not.toContain("Martim Costa"); + res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/people/${martim.id}/history`, headers: as(owner) }); + expect(res.json()).toMatchObject({ recognitionOff: { by: "PETER" }, canManage: true }); + expect((res.json().actions as { action: string }[]).map((a) => a.action)).toEqual(expect.arrayContaining(["confirm", "reject", "recognition_off_all"])); + }); + it("waits for disk space before indexing, and says how much the archive needs", async () => { const source = await connect(); cloud.authorised = true; @@ -885,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 c720863..e60d49a 100644 --- a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx +++ b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx @@ -1,221 +1,233 @@ "use client"; -import { useCallback, useEffect, useMemo, useState } from "react"; +import { useCallback, useEffect, useState } from "react"; import { useRouter } from "next/navigation"; +import { cached, call, readStored, storageKey, writeStored, type Me } 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 { Review } from "./Review"; 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; person?: string } | { 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" }; -const read = (k: string) => { - try { - return window.sessionStorage.getItem(k); - } catch { - 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 */ - } +/** 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" | "review"][] = [ + ["galleries", "Galerias", "galleries"], + ["people", "Pessoas", "people"], + ["teams", "Equipas", "teams"], + ["review", "Rever rostos", "review"], +]; +const TAB_PARAM: Record = { galleries: "", people: "pessoas", teams: "equipas", review: "rever" }; 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 [me, setMe] = useState(null); + 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 = info.base ?? `/arquivo/${info.id}`; + const home = base || "/"; 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]); + // What this viewer may do (from their rights on the cloud): read again after a review changes the count. + useEffect(() => { + if (!token) return; + cached(`/v1/archive/${info.id}/me`, token, setMe).catch(() => setMe(null)); + }, [token, info.id, meTick]); + + /** Ends the session here and on the server (which revokes the app password kept on the cloud). */ const signOut = useCallback(() => { - write(storageKey(info.id), null); - write(`${storageKey(info.id)}_name`, null); + const t = readStored(storageKey(info.id)); + if (t) void fetch("/v1/archive/logout", { method: "POST", headers: { authorization: `Archive ${t}` }, keepalive: true }).catch(() => undefined); + 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} · `} : ""} - - + /** The server ended the session (idle, a share or the app password taken away on the cloud). */ + const expired = useCallback(() => { + writeStored(storageKey(info.id), null); + writeStored(`${storageKey(info.id)}_name`, null); + setToken(null); + }, [info.id]); + + const go = useCallback( + (v: View) => { + const href = + v.kind === "browse" + ? `${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" + ? `${base}/p/${v.id}` + : `${base}/f/${v.id}`; + router.push(href); + window.scrollTo({ top: 0 }); + }, + [base, home, 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, "", `${home}${TAB_PARAM[t] ? `?t=${TAB_PARAM[t]}` : ""}`); + window.scrollTo({ top: 0 }); + }, + [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"))}> + {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); - write(`${storageKey(info.id)}_name`, name); + logo={template?.logo ?? null} + owner={template?.owner ?? info.organization} + onDone={(t, 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" ? ( + go({ kind: "browse", tab: "review", person: id })} + view={view} + onBack={() => (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 })} + /> + ) : tab === "review" && me?.canReview ? ( + { + setReviewPerson(id); + window.history.replaceState(null, "", `${home}?t=rever${id ? `&p=${id}` : ""}`); + }} + onExpired={expired} + onChanged={() => setMeTick((n) => n + 1)} + /> + ) : tab === "review" && !me ? ( +
+ ) : ( + go({ kind: "gallery", id })} onPerson={(id) => go({ kind: "person", id })} /> + )} +
+ + +
); } -function SignIn({ info, onDone }: { info: ArchiveInfo; onDone: (token: string, name: string) => 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 [loginUrl, setLoginUrl] = useState(null); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); + const [keep, setKeep] = useState(true); useEffect(() => { 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,773 +241,79 @@ function SignIn({ info, onDone }: { info: ArchiveInfo; onDone: (token: string, n live = false; clearInterval(timer); }; - }, [state, onDone]); + }, [state, onDone, keep]); const start = () => { setBusy(true); 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 iniciar a entrada. 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

+

+ 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 que autorizes a entrada na outra janela…{" "} + {loginUrl && ( + + Abrir a página de autorização + + )} +

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

{error}

} +

+ A tua palavra-passe só é escrita na página de entrada, nunca aqui.{" "} + {keep + ? '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."} +

- ) : ( - - )} - {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.

+
+
); } - -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 ( -