diff --git a/apps/api/prisma/migrations/20261019090000_archive_hostname/migration.sql b/apps/api/prisma/migrations/20261019090000_archive_hostname/migration.sql new file mode 100644 index 0000000..e473115 --- /dev/null +++ b/apps/api/prisma/migrations/20261019090000_archive_hostname/migration.sql @@ -0,0 +1,3 @@ +-- The archive's own address: the public site serves it at the root of that host. +ALTER TABLE "cloud_sources" ADD COLUMN "hostname" TEXT; +CREATE UNIQUE INDEX "cloud_sources_hostname_key" ON "cloud_sources"("hostname"); diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 24f3bfa..36475e7 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -1621,6 +1621,8 @@ model CloudSource { status String @default("LOGIN") /// How the archive's site looks: "liga" (Liga Portugal), "fpa" (Federação de Andebol), or null (PhotoReport). look String? + /// The archive's own address ("arquivo.ligaportugal.pt"): the site serves this archive at its root there. + hostname String? @unique /// Nextcloud login flow v2: where to poll for the app password while status is LOGIN (sealed token). loginPoll String? @map("login_poll") loginExpires DateTime? @map("login_expires") diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index ac52867..34bcb16 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -145,7 +145,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give await registerArchiveRoutes(app, { db, sessions, archive, storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9 }); // The API never runs the face engine: it confirms and merges groups; the worker detects and groups. const faces = new FaceService({ db, storage, broadcaster, log: app.log }); - await registerArchiveViewerRoutes(app, { db, secrets, signer, archive, tokens: new ViewerTokens(config.JWT_SECRET), faces, fetchImpl }); + await registerArchiveViewerRoutes(app, { db, secrets, signer, archive, tokens: new ViewerTokens(config.JWT_SECRET), faces, storage, secret: config.JWT_SECRET, fetchImpl }); await registerCompositionRoutes(app, { db, sessions, storage, storageRoot: config.STORAGE_ROOT }); await registerSearchRoutes(app, { db, sessions, signer }); await registerFtpRoutes(app, { db, sessions, ingestRoot: config.INGEST_ROOT, hookSecret: config.SFTPGO_HOOK_KEY }); diff --git a/apps/api/src/archive/downloads.ts b/apps/api/src/archive/downloads.ts new file mode 100644 index 0000000..5984411 --- /dev/null +++ b/apps/api/src/archive/downloads.ts @@ -0,0 +1,168 @@ +import { createHmac, timingSafeEqual } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { createReadStream } from "node:fs"; +import type { FastifyInstance, FastifyRequest } from "fastify"; +import sharp from "sharp"; +import { eventName } from "@photoreport/metadata"; +import { z } from "zod"; +import type { Db } from "../db.js"; +import { AppError, badRequest, notFound } from "../lib/errors.js"; +import { zipStream, ZipTooLarge, type ZipEntry } from "../lib/zip.js"; +import type { LocalStorage } from "../storage/storage.js"; +import type { Viewer } from "./viewer.js"; + +/** + * Downloads for archive viewers: photos at web size (2048 px on the long side, with their metadata: credits, + * caption, names), one as a JPEG, several as a ZIP. Never the full-size original: whoever needs it edits on the + * cloud and has its link there. + * + * The browser fetches a download by a plain link, so the page first asks for one (`POST …/downloads`, with the + * viewer's session); the link carries a short-lived signed ticket naming the photos, checked when it is used. + */ +const WEB_SIZE = 2048; +const TICKET_TTL_SEC = 10 * 60; +/** A gallery at once (named by its folder in the link), or up to this many photos picked one by one. */ +const MAX_PHOTOS = 1000; +const MAX_PICKED = 100; + +interface Deps { + db: Db; + storage: LocalStorage; + secret: string; + viewerOf: (req: FastifyRequest, sourceId?: string) => Viewer; + visibleFolders: (v: Viewer) => Promise; +} + +const SourceParams = z.object({ sourceId: z.uuid() }); +const Ask = z.union([z.object({ photoIds: z.array(z.uuid()).min(1).max(MAX_PICKED) }), z.object({ folderId: z.uuid() })]); +const TicketQuery = z.object({ t: z.string().min(10).max(20_000) }); + +interface Ticket { + s: string; + /** Photos picked, or (`f`) every photo of a gallery folder. */ + ids?: string[]; + f?: string; + /** Name of the ZIP (a gallery's title). */ + n: string | null; + exp: number; +} + +export async function registerArchiveDownloadRoutes(app: FastifyInstance, deps: Deps) { + const { db, storage, viewerOf, visibleFolders } = deps; + const key = createHmac("sha256", deps.secret).update("photoreport:archive-download").digest(); + const mac = (body: string) => createHmac("sha256", key).update(body).digest("base64url"); + const sign = (t: Omit) => { + const body = Buffer.from(JSON.stringify({ ...t, exp: Math.floor(Date.now() / 1000) + TICKET_TTL_SEC })).toString("base64url"); + return `${body}.${mac(body)}`; + }; + const open = (ticket: string): Ticket | null => { + const [body, sig] = ticket.split("."); + if (!body || !sig) return null; + const want = Buffer.from(mac(body), "base64url"); + const got = Buffer.from(sig, "base64url"); + if (got.length !== want.length || !timingSafeEqual(got, want)) return null; + try { + const t = JSON.parse(Buffer.from(body, "base64url").toString("utf8")) as Ticket; + return t.exp * 1000 > Date.now() ? t : null; + } catch { + return null; + } + }; + + /** A link to download photos the viewer may see: some photos, or a whole gallery. */ + app.post("/v1/archive/:sourceId/downloads", { config: { rateLimit: { max: 60, timeWindow: "1 minute" } } }, async (req) => { + const { sourceId } = SourceParams.parse(req.params); + const v = viewerOf(req, sourceId); + const ask = Ask.parse(req.body); + const visible = await visibleFolders(v); + const scope = visible === "all" ? {} : { folderId: { in: visible } }; + let name: string | null = null; + let ids: string[] = []; + if ("folderId" in ask) { + if (visible !== "all" && !visible.includes(ask.folderId)) throw notFound("gallery_not_found"); + const folder = await db.cloudFolder.findFirst({ where: { id: ask.folderId, sourceId }, include: { event: true } }); + if (!folder) throw notFound("gallery_not_found"); + name = folder.event ? eventName(folder.event) : (folder.path.split("/").pop() ?? null); + const n = await db.cloudFile.count({ where: { folderId: folder.id, status: "DONE", photoId: { not: null } } }); + if (n > MAX_PHOTOS) throw new AppError(413, "too_many_photos"); + if (!n) throw notFound("photo_not_found"); + return { url: `/v1/archive/dl?t=${sign({ s: sourceId, f: folder.id, n: name })}`, photos: n }; + } else { + const files = await db.cloudFile.findMany({ where: { sourceId, status: "DONE", photoId: { in: ask.photoIds }, ...scope }, select: { photoId: true }, distinct: ["photoId"] }); + ids = ask.photoIds.filter((id) => files.some((f) => f.photoId === id)); + } + if (!ids.length) throw notFound("photo_not_found"); + return { url: `/v1/archive/dl?t=${sign({ s: sourceId, ids, n: name })}`, photos: ids.length }; + }); + + /** The download itself: one JPEG, or a ZIP. */ + app.get("/v1/archive/dl", async (req, reply) => { + const { t: ticket } = TicketQuery.parse(req.query); + const t = open(ticket); + if (!t) throw notFound("download_expired"); + const ids = t.f + ? (await db.cloudFile.findMany({ where: { folderId: t.f, sourceId: t.s, status: "DONE", photoId: { not: null } }, orderBy: { path: "asc" }, select: { photoId: true }, take: MAX_PHOTOS })).map((f) => f.photoId!) + : (t.ids ?? []); + const photos = await db.photo.findMany({ + where: { id: { in: ids }, cloudFiles: { some: { sourceId: t.s } } }, + select: { id: true, storageKey: true, originalName: true, originalStored: true, width: true, height: true, capturedAt: true }, + }); + if (!photos.length) throw notFound("photo_not_found"); + const order = new Map(ids.map((id, i) => [id, i])); + photos.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0)); + const dir = await mkdtemp(path.join(tmpdir(), "pr-archive-dl-")); + const cleanup = () => void rm(dir, { recursive: true, force: true }); + try { + // The archive keeps a 2048 px copy with its metadata; a photo with its full original is made web size here. + const files: ZipEntry[] = []; + for (const p of photos) { + const kept = storage.resolve(p.storageKey); + const big = p.originalStored || Math.max(p.width ?? 0, p.height ?? 0) > WEB_SIZE; + let file = kept; + if (big) { + file = path.join(dir, `${p.id}.jpg`); + await sharp(kept).resize(WEB_SIZE, WEB_SIZE, { fit: "inside", withoutEnlargement: true }).keepMetadata().jpeg({ quality: 90 }).toFile(file); + } + const name = p.originalName.replace(/\.[^.]+$/, "") + ".jpg"; + files.push({ name, path: file, ...(p.capturedAt && { modified: p.capturedAt }) }); + } + if (files.length === 1) { + const [only] = files; + const stream = createReadStream(only!.path); + stream.on("close", cleanup); + return reply + .header("content-type", "image/jpeg") + .header("content-disposition", disposition(only!.name)) + .header("cache-control", "private, no-store") + .send(stream); + } + let zip; + try { + zip = await zipStream(files); + } catch (err) { + if (err instanceof ZipTooLarge) throw new AppError(413, "zip_too_large"); + throw err; + } + zip.stream.on("close", cleanup); + zip.stream.on("end", cleanup); + return reply + .header("content-type", "application/zip") + .header("content-length", String(zip.size)) + .header("content-disposition", disposition(`${t.n ?? "fotografias"}.zip`)) + .header("cache-control", "private, no-store") + .send(zip.stream); + } catch (err) { + cleanup(); + if (err instanceof AppError) throw err; + throw badRequest("download_failed", (err as Error).message); + } + }); +} + +/** `attachment` with a plain ASCII name and the real one (accents) for browsers that read it. */ +function disposition(name: string): string { + const ascii = name.normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^\w.\- ]+/g, "_"); + return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`; +} diff --git a/apps/api/src/archive/routes.ts b/apps/api/src/archive/routes.ts index 55187ff..4ce4d9b 100644 --- a/apps/api/src/archive/routes.ts +++ b/apps/api/src/archive/routes.ts @@ -6,7 +6,7 @@ import type { SessionService } from "../auth/sessions.js"; import type { Db } from "../db.js"; import { NextcloudError } from "../delivery/nextcloud.js"; import type { CloudSource } from "../generated/prisma/client.js"; -import { AppError, badRequest, notFound } from "../lib/errors.js"; +import { AppError, badRequest, conflict, notFound } from "../lib/errors.js"; import { ARCHIVE_LOOKS, ArchiveRejected, BYTES_PER_PHOTO, diskSpace, normalisePath, type ArchiveService, type RematchReport } from "./service.js"; const OrgParams = z.object({ orgId: z.uuid() }); @@ -23,6 +23,16 @@ const Update = z.object({ rootPath: z.string().trim().min(1).max(500).optional(), paused: z.boolean().optional(), look: z.enum(ARCHIVE_LOOKS).nullable().optional(), + /** The archive's own address (a host name, no scheme or path); empty or null takes it away. */ + hostname: z + .string() + .trim() + .toLowerCase() + .max(253) + .transform((h) => h.replace(/^https?:\/\//, "").replace(/\/.*$/, "").replace(/\.$/, "")) + .refine((h) => h === "" || /^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(h), "host name") + .nullable() + .optional(), }); const FolderQuery = z.object({ /** games: official games; named: games known only by their folder; events (or folders): not games. */ @@ -78,6 +88,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db baseUrl: s.baseUrl, rootPath: s.rootPath, look: s.look, + hostname: s.hostname, account: s.username || null, status: s.status, lastScanAt: s.lastScanAt, @@ -137,6 +148,15 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db const body = Update.parse(req.body); const current = await loadSource(req, sourceId, "ADMIN"); const status = body.paused === undefined ? undefined : body.paused ? "PAUSED" : current.secretEnc ? "READY" : "LOGIN"; + const hostname = body.hostname === undefined ? undefined : body.hostname || null; + if (hostname) { + // One address, one thing: not another archive's, nor a public site's (the site would not know which to show). + const [archiveThere, siteThere] = await Promise.all([ + db.cloudSource.findFirst({ where: { hostname, id: { not: sourceId } }, select: { id: true } }), + db.site.findUnique({ where: { domain: hostname }, select: { id: true } }), + ]); + if (archiveThere || siteThere) throw conflict("hostname_taken"); + } const source = await db.cloudSource.update({ where: { id: sourceId }, data: { @@ -145,6 +165,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db ...(status && { status }), ...(status === "READY" && { nextScanAt: new Date() }), ...(body.look !== undefined && { look: body.look }), + ...(hostname !== undefined && { hostname }), }, }); return serialize(source, (await counts([source.id])).get(source.id)); diff --git a/apps/api/src/archive/viewer.ts b/apps/api/src/archive/viewer.ts index 763128b..e288650 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -7,11 +7,12 @@ import type { Db } from "../db.js"; import { NextcloudError } from "../delivery/nextcloud.js"; import type { SecretBox } from "../delivery/secrets.js"; import { AppError, badRequest, notFound, unauthorized } from "../lib/errors.js"; -import type { UrlSigner } from "../storage/storage.js"; +import type { LocalStorage, UrlSigner } from "../storage/storage.js"; import { CloudClient, pollLogin, startLogin } from "./nextcloud.js"; import { canonicalTeam, describeFolder } from "./match.js"; import type { FaceService } from "../faces/service.js"; import { faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js"; +import { registerArchiveDownloadRoutes } from "./downloads.js"; import { registerArchiveReviewRoutes } from "./review.js"; import type { ArchiveService } from "./service.js"; @@ -95,7 +96,7 @@ const ListQuery = z.object({ export async function registerArchiveViewerRoutes( app: FastifyInstance, - deps: { db: Db; secrets: SecretBox | undefined; signer: UrlSigner; archive: ArchiveService; tokens: ViewerTokens; faces: FaceService; fetchImpl?: typeof fetch | undefined }, + deps: { db: Db; secrets: SecretBox | undefined; signer: UrlSigner; archive: ArchiveService; tokens: ViewerTokens; faces: FaceService; storage: LocalStorage; secret: string; fetchImpl?: typeof fetch | undefined }, ) { const { db, signer, tokens } = deps; const fetchImpl = deps.fetchImpl ?? fetch; @@ -285,7 +286,22 @@ export async function registerArchiveViewerRoutes( const { sourceId } = SourceParams.parse(req.params); const source = await db.cloudSource.findUnique({ where: { id: sourceId }, include: { organization: { select: { name: true } } } }); if (!source || !source.secretEnc) throw notFound("archive_not_found"); - return { id: source.id, name: source.name, cloud: new URL(source.baseUrl).host, organization: source.organization.name, look: source.look }; + return { id: source.id, name: source.name, cloud: new URL(source.baseUrl).host, organization: source.organization.name, look: source.look, hostname: source.hostname }; + }); + + /** + * Which archive an address of its own shows (the site asks, to serve it at the root there). `?domain=` answers + * the proxy's question before it gets a certificate for a host (Caddy's on-demand TLS): 200 only for an + * archive's address. + */ + app.get("/v1/archive/host", { config: { rateLimit: { max: 600, timeWindow: "1 minute" } } }, async (req, reply) => { + const raw = (req.query as { domain?: string; host?: string }).domain ?? (req.query as { host?: string }).host ?? ""; + const hostname = raw.trim().toLowerCase().replace(/:\d+$/, "").replace(/\.$/, ""); + if (!hostname || hostname.length > 253) throw notFound("archive_not_found"); + const source = await db.cloudSource.findUnique({ where: { hostname }, select: { id: true, secretEnc: true } }); + if (!source || !source.secretEnc) throw notFound("archive_not_found"); + reply.header("cache-control", "public, max-age=60"); + return { id: source.id }; }); /** Starts the viewer's sign-in on the cloud: they open `loginUrl`, the page polls with `state`. */ @@ -483,6 +499,9 @@ export async function registerArchiveViewerRoutes( if (visible !== "all" && !visible.includes(folderId)) throw notFound("gallery_not_found"); const folder = await db.cloudFolder.findFirst({ where: { id: folderId, sourceId: v.s }, include: { event: true, source: { select: { baseUrl: true } } } }); if (!folder) throw notFound("gallery_not_found"); + // Links to the cloud only for those who edit there; the others need not know where the photos live. + const editable = await editableFolders(v); + const onCloud = editable === "all" || editable.includes(folderId); const where = { folderId, status: "DONE" as const, @@ -557,7 +576,7 @@ export async function registerArchiveViewerRoutes( competition: folder.event?.competition ?? null, startsAt: folder.event?.startsAt ?? null, /** The folder on the cloud (opens for those it is shared with). */ - cloudUrl: `${base}/f/${folder.fileId}`, + cloudUrl: onCloud ? `${base}/f/${folder.fileId}` : null, total, people: named.map((p) => ({ id: p.id, name: p.name, count: Number(p.count), face: faceOf.get(p.id) ?? null })), /** Everyone named in this game, so a gallery can offer them even when this part has only some. */ @@ -571,7 +590,7 @@ export async function registerArchiveViewerRoutes( capturedAt: f.photo!.capturedAt, thumb: signer.url(f.photo!.id, "thumb", f.photo!.renderedSeq), preview: signer.url(f.photo!.id, "preview", f.photo!.renderedSeq), - cloudUrl: `${base}/f/${f.fileId}`, + ...(onCloud && { cloudUrl: `${base}/f/${f.fileId}` }), })), }; }); @@ -593,6 +612,7 @@ export async function registerArchiveViewerRoutes( await registerArchivePeopleRoutes(app, { db, signer, viewerOf, visibleFolders }); await registerArchiveReviewRoutes(app, { db, signer, faces: deps.faces, viewerOf, editableFolders }); + await registerArchiveDownloadRoutes(app, { db, storage: deps.storage, secret: deps.secret, viewerOf, visibleFolders }); } /** File ids of a folder and of each folder above it ("/FPA/Fotos" → /FPA/Fotos, /FPA, and the account's root). */ diff --git a/apps/api/test/archive.test.ts b/apps/api/test/archive.test.ts index 557f4df..1d69d6e 100644 --- a/apps/api/test/archive.test.ts +++ b/apps/api/test/archive.test.ts @@ -821,6 +821,30 @@ describe("archive from a Nextcloud", () => { expect((await act(editor, gGala.id, { action: "confirm" })).statusCode).toBe(403); expect((await act(reader, g1.id, { action: "undo" })).statusCode).toBe(403); + // Downloads at web size for anyone who sees the photos; the cloud's links only for those who edit there. + const game = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "20250913 - SCP x ABC" } } }); + const seen = async (t: string) => (await ctx.app.inject({ method: "GET", url: `/v1/archive/galleries/${game.id}`, headers: as(t) })).json() as { cloudUrl: string | null; photos: { cloudUrl?: string }[] }; + expect((await seen(reader)).cloudUrl).toBeNull(); + expect((await seen(reader)).photos[0]!.cloudUrl).toBeUndefined(); + expect((await seen(editor)).cloudUrl).toMatch(/^https:\/\/cloud\.test\/f\//); + const ask = (t: string, payload: Record) => ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/downloads`, headers: as(t), payload }); + res = await ask(reader, { photoIds: [p1.id] }); + const one = res.json() as { url: string; photos: number }; + expect(one.photos).toBe(1); + res = await ctx.app.inject({ method: "GET", url: one.url }); + expect(res.statusCode).toBe(200); + expect(res.headers["content-type"]).toBe("image/jpeg"); + expect(res.headers["content-disposition"]).toContain('filename="PS_0001.jpg"'); + const meta = await sharp(res.rawPayload).metadata(); + expect(Math.max(meta.width!, meta.height!)).toBeLessThanOrEqual(2048); + expect((await ask(reader, { photoIds: [gala.id] })).statusCode).toBe(404); + res = await ask(reader, { folderId: game.id }); + expect(res.json()).toMatchObject({ photos: 2 }); + res = await ctx.app.inject({ method: "GET", url: (res.json() as { url: string }).url }); + expect(res.headers["content-type"]).toBe("application/zip"); + expect(res.rawPayload.subarray(0, 2).toString()).toBe("PK"); + expect((await ctx.app.inject({ method: "GET", url: one.url.slice(0, -3) + "abc" })).statusCode).toBe(404); + // A person as a whole: only the account that edits everything. const off = (t: string, payload: Record) => ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/people/${martim.id}/recognition`, headers: as(t), payload }); expect((await off(editor, { enabled: false })).statusCode).toBe(403); @@ -1003,6 +1027,27 @@ describe("archive from a Nextcloud", () => { expect((await ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { look: "benfica" } })).statusCode).toBe(400); }); + it("serves an archive at an address of its own, one archive per address", async () => { + const source = await connect(); + cloud.authorised = true; + await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); + const patch = (hostname: unknown) => ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { hostname } }); + let res = await patch("https://Arquivo.LigaPortugal.pt/"); + expect(res.json()).toMatchObject({ hostname: "arquivo.ligaportugal.pt" }); + expect((await ctx.app.inject({ method: "GET", url: "/v1/archive/host?host=arquivo.ligaportugal.pt" })).json()).toEqual({ id: source.id }); + // The proxy asks before a certificate: only an archive's address gets one. + expect((await ctx.app.inject({ method: "GET", url: "/v1/archive/host?domain=arquivo.ligaportugal.pt" })).statusCode).toBe(200); + expect((await ctx.app.inject({ method: "GET", url: "/v1/archive/host?domain=other.example.pt" })).statusCode).toBe(404); + expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}` })).json()).toMatchObject({ hostname: "arquivo.ligaportugal.pt" }); + expect((await patch("not a host")).statusCode).toBe(400); + // A public site's domain is taken. + await ctx.db.site.create({ data: { organizationId: orgId, domain: "fotos.example.pt", name: "Fotos" } }); + expect((await patch("fotos.example.pt")).statusCode).toBe(409); + res = await patch(""); + expect(res.json()).toMatchObject({ hostname: null }); + expect((await ctx.app.inject({ method: "GET", url: "/v1/archive/host?host=arquivo.ligaportugal.pt" })).statusCode).toBe(404); + }); + it("shares the worker between clouds: a big newer archive does not starve another", async () => { const source = await connect(); cloud.authorised = true; diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 328092c..c6de03f 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -453,6 +453,10 @@ export const t = { pause: "Pausar", look: "Aspeto do site", looks: { none: "PhotoReport", liga: "Liga Portugal", fpa: "Federação de Andebol" } as Record, + hostname: "Endereço próprio", + hostnamePlaceholder: "arquivo.ligaportugal.pt", + hostnameHelp: "Opcional. Aponta esse endereço (DNS, CNAME) para o mesmo servidor do arquivo: o arquivo abre na raiz e o certificado é pedido sozinho.", + hostnameSave: "Guardar", resume: "Retomar", remove: "Desligar", removeConfirm: "Desligar esta cloud? As fotos já indexadas ficam na biblioteca.", @@ -826,6 +830,7 @@ export const t = { slug_taken: "Já existe uma galeria com esse endereço.", gallery_empty: "Junta fotos antes de publicar.", domain_taken: "Esse domínio já está em uso.", + hostname_taken: "Esse endereço já está em uso por outro arquivo ou site.", invalid_stripe_key: "A chave da Stripe começa por sk_live_ ou sk_test_.", invalid_webhook_secret: "O segredo do webhook começa por whsec_.", secret_key_missing: "Falta configurar a chave de cifra do servidor (DELIVERY_SECRET_KEY).", diff --git a/apps/app/src/pages/ArchivePage.tsx b/apps/app/src/pages/ArchivePage.tsx index a129467..f36cf78 100644 --- a/apps/app/src/pages/ArchivePage.tsx +++ b/apps/app/src/pages/ArchivePage.tsx @@ -118,7 +118,9 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove const c = source.counts; const total = c.done + c.pending + c.failed; const pct = total ? Math.round((c.done / total) * 100) : 0; - const viewerUrl = `${VIEWER_BASE.replace(/\/+$/, "")}/arquivo/${source.id}`; + const viewerUrl = source.hostname ? `https://${source.hostname}` : `${VIEWER_BASE.replace(/\/+$/, "")}/arquivo/${source.id}`; + const [hostname, setHostname] = useState(source.hostname ?? ""); + useEffect(() => setHostname(source.hostname ?? ""), [source.hostname]); const run = (fn: () => Promise) => { setBusy(true); @@ -210,6 +212,30 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove )} + {isAdmin && ( +
{ + e.preventDefault(); + void run(() => api.updateCloudSource(source.id, { hostname: hostname.trim() || null })); + }} + > + {A.hostname}: + setHostname(e.target.value)} + placeholder={A.hostnamePlaceholder} + disabled={busy} + className="h-6 min-w-[220px] border border-black bg-cell px-2 font-mono text-[11px] text-ink" + /> + {hostname.trim() !== (source.hostname ?? "") && ( + + )} + {A.hostnameHelp} +
+ )} )} diff --git a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx index 40ebf0e..e60d49a 100644 --- a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx +++ b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx @@ -40,7 +40,8 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } const [reviewPerson, setReviewPerson] = useState(view.kind === "browse" ? (view.person ?? null) : null); const [meTick, setMeTick] = useState(0); const template = info.look ? TEMPLATE[info.look] : null; - const base = `/arquivo/${info.id}`; + const base = info.base ?? `/arquivo/${info.id}`; + const home = base || "/"; useEffect(() => { setToken(readStored(storageKey(info.id))); @@ -74,7 +75,7 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } (v: View) => { const href = v.kind === "browse" - ? `${base}${v.tab && TAB_PARAM[v.tab] ? `?t=${TAB_PARAM[v.tab]}${v.person ? `&p=${v.person}` : ""}` : ""}` + ? `${home}${v.tab && TAB_PARAM[v.tab] ? `?t=${TAB_PARAM[v.tab]}${v.person ? `&p=${v.person}` : ""}` : ""}` : v.kind === "gallery" ? `${base}/g/${v.id}` : v.kind === "person" @@ -83,7 +84,7 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } router.push(href); window.scrollTo({ top: 0 }); }, - [base, router], + [base, home, router], ); /** A tab of the lists: in place when they are on screen (no reload), else back to them. */ @@ -91,16 +92,16 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } (t: Tab) => { if (view.kind !== "browse") return go({ kind: "browse", tab: t }); setTab(t); - window.history.replaceState(null, "", `${base}${TAB_PARAM[t] ? `?t=${TAB_PARAM[t]}` : ""}`); + window.history.replaceState(null, "", `${home}${TAB_PARAM[t] ? `?t=${TAB_PARAM[t]}` : ""}`); window.scrollTo({ top: 0 }); }, - [view.kind, go, base], + [view.kind, go, home], ); const current: Tab | null = view.kind === "browse" ? tab : view.kind === "person" || view.kind === "face" ? "people" : "galleries"; const brand = ( - (e.preventDefault(), openTab("galleries"))}> + (e.preventDefault(), openTab("galleries"))}> {template ? {template.owner} : {info.organization}} Arquivo @@ -158,7 +159,6 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } {t === "review" && !!me?.pending && {me.pending}} ))} - Mostra só o que podes ver em {info.cloud} @@ -188,7 +188,7 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } person={reviewPerson} onPerson={(id) => { setReviewPerson(id); - window.history.replaceState(null, "", `${base}?t=rever${id ? `&p=${id}` : ""}`); + window.history.replaceState(null, "", `${home}?t=rever${id ? `&p=${id}` : ""}`); }} onExpired={expired} onChanged={() => setMeTick((n) => n + 1)} @@ -257,7 +257,7 @@ function SignIn({ info, logo, owner, onDone }: { info: ArchiveInfo; logo: string }, () => { win?.close(); - setError("Não foi possível falar com a cloud. Tenta daqui a pouco."); + setError("Não foi possível iniciar a entrada. Tenta daqui a pouco."); }, ) .finally(() => setBusy(false)); @@ -272,12 +272,12 @@ function SignIn({ info, logo, owner, onDone }: { info: ArchiveInfo; logo: string Arquivo fotográfico

Todas as fotos, num só sítio

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

{state ? (

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

{error}

}

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

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

{note}

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

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

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

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

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