Let archive viewers download at web size, keep the cloud for editors, and serve an archive at its own address.
ci / rust (pull_request) Failing after 37s
ci / typescript (pull_request) Failing after 2m51s

- Downloads: one photo, a selection (up to 100) or a whole gallery (ZIP, up to 1000) at 2048 px with
  metadata, through a short-lived signed link. Gallery and large view get the buttons.
- The cloud is named only to those who edit the folder there (a small "originals" link); sign-in no
  longer mentions it.
- cloud_sources.hostname: the site's middleware serves that archive at the root of its own host;
  Caddy asks /v1/archive/host before getting a certificate. Set in the app (Endereço próprio).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1
This commit is contained in:
sparkandClaude Opus 5.5 committed 2026-10-18 23:27:33 +00:00
1 parent 16c23c3eb8
commit 56f8660667
22 files changed
+556 -45

No files matched your search

@@ -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");
+2
View File
@@ -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")
+1 -1
View File
@@ -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 });
+168
View File
@@ -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<string[] | "all">;
}
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<Ticket, "exp">) => {
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)}`;
}
+22 -1
View File
@@ -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));
+25 -5
View File
@@ -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). */
+45
View File
@@ -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<string, unknown>) => 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<string, unknown>) => 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;
+5
View File
@@ -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<string, string>,
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).",
+27 -1
View File
@@ -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<CloudSource | void>) => {
setBusy(true);
@@ -210,6 +212,30 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
</select>
</label>
)}
{isAdmin && (
<form
className="flex w-full flex-wrap items-center gap-2"
onSubmit={(e) => {
e.preventDefault();
void run(() => api.updateCloudSource(source.id, { hostname: hostname.trim() || null }));
}}
>
<span className="text-muted">{A.hostname}:</span>
<input
value={hostname}
onChange={(e) => 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 ?? "") && (
<button type="submit" disabled={busy} className="h-6 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on disabled:opacity-40">
{A.hostnameSave}
</button>
)}
<span className="w-full text-faint">{A.hostnameHelp}</span>
</form>
)}
</div>
)}
+15 -15
View File
@@ -40,7 +40,8 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View }
const [reviewPerson, setReviewPerson] = useState<string | null>(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 = (
<a className="arq-brand" href={base} onClick={(e) => (e.preventDefault(), openTab("galleries"))}>
<a className="arq-brand" href={home} onClick={(e) => (e.preventDefault(), openTab("galleries"))}>
{template ? <img src={template.logo} alt={template.owner} width={168} height={43} /> : <span className="arq-org">{info.organization}</span>}
<span className="arq-name">Arquivo</span>
</a>
@@ -158,7 +159,6 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View }
{t === "review" && !!me?.pending && <span className="arq-count">{me.pending}</span>}
</button>
))}
<span className="arq-note">Mostra só o que podes ver em {info.cloud}</span>
</div>
</nav>
</header>
@@ -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
<span className="arq-badge">Arquivo fotográfico</span>
<h1 className="arq-disp">Todas as fotos, num só sítio</h1>
<p>
As fotografias estão em <strong>{info.cloud}</strong>. 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.
</p>
</div>
{state ? (
<p className="arq-notice">
A aguardar a autorização em {info.cloud}…{" "}
A aguardar que autorizes a entrada na outra janela…{" "}
{loginUrl && (
<a href={loginUrl} target="_blank" rel="noreferrer">
Abrir a página de autorização
@@ -287,7 +287,7 @@ function SignIn({ info, logo, owner, onDone }: { info: ArchiveInfo; logo: string
) : (
<>
<button type="button" className="arq-btn accent" disabled={busy} onClick={start}>
Entrar com {info.cloud}
Entrar
<Icon name="next" size={18} />
</button>
<label className="arq-keep">
@@ -298,10 +298,10 @@ function SignIn({ info, logo, owner, onDone }: { info: ArchiveInfo; logo: string
)}
{error && <p className="arq-error">{error}</p>}
<p style={{ fontSize: 14 }}>
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."}
</p>
</div>
</div>
+82 -12
View File
@@ -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<Set<string> | null>(null);
const [saving, setSaving] = useState<string | null>(null);
const [note, setNote] = useState<string | null>(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({
</>
)}
<div className="arq-actions">
<a className="arq-btn accent" href={g.cloudUrl} target="_blank" rel="noreferrer">
<Icon name="cloud" size={18} />
Abrir a pasta na cloud
</a>
{total <= MAX_ZIP && (
<button type="button" className="arq-btn accent" disabled={!!saving} onClick={() => save({ folderId: g.id }, "all")}>
<Icon name="download" size={18} />
{saving === "all" ? "A preparar…" : `Descarregar tudo (${total})`}
</button>
)}
<button type="button" className="arq-btn ghost on-hero" aria-pressed={picked !== null} onClick={() => setPicked(picked ? null : new Set())}>
<Icon name="check" size={18} />
{picked ? "Cancelar seleção" : "Selecionar fotos"}
</button>
</div>
{note && <p className="arq-hero-note">{note}</p>}
{g.cloudUrl && (
<a className="arq-cloud-link" href={g.cloudUrl} target="_blank" rel="noreferrer">
<Icon name="cloud" size={14} />
Originais em alta qualidade na cloud
</a>
)}
</div>
</section>
@@ -209,9 +245,9 @@ export function Gallery({
</select>
</label>
)}
{picked && (
<button type="button" className="arq-link" onClick={() => onPerson(picked.id)} style={{ flexShrink: 0 }}>
Todas as fotos de {picked.name}
{chosen && (
<button type="button" className="arq-link" onClick={() => onPerson(chosen.id)} style={{ flexShrink: 0 }}>
Todas as fotos de {chosen.name}
</button>
)}
</div>
@@ -219,11 +255,26 @@ export function Gallery({
)}
<div className="arq-wrap arq-body">
{picked && photos.length === 0 && <p className="arq-empty">Sem fotos de {picked.name} nesta parte do jogo.</p>}
<div className="arq-grid">
{chosen && photos.length === 0 && <p className="arq-empty">Sem fotos de {chosen.name} nesta parte do jogo.</p>}
<div className={`arq-grid${picked ? " picking" : ""}`}>
{photos.map((p, i) => (
<button key={p.id} type="button" className="arq-tile" onClick={() => setIndex(i)} aria-label={p.players.join(", ") || p.name}>
<button
key={p.id}
type="button"
className={`arq-tile${picked?.has(p.id) ? " on" : ""}`}
aria-pressed={picked ? picked.has(p.id) : undefined}
onClick={() => {
if (!picked) return setIndex(i);
const next = new Set(picked);
if (next.has(p.id)) next.delete(p.id);
else if (next.size < MAX_PICKED) next.add(p.id);
else return setNote(`Podes escolher até ${MAX_PICKED} fotos de cada vez.`);
setPicked(next);
}}
aria-label={p.players.join(", ") || p.name}
>
<img src={p.thumb} alt="" loading={i < 12 ? "eager" : "lazy"} decoding="async" />
{picked && <span className="arq-check">{picked.has(p.id) ? <Icon name="check" size={16} /> : null}</span>}
{p.players.length > 0 && (
<span className="arq-names">
<span>{p.players.join(", ")}</span>
@@ -232,6 +283,24 @@ export function Gallery({
</button>
))}
</div>
{picked && (
<div className="arq-bulk">
<span>{picked.size ? `${picked.size} ${picked.size === 1 ? "foto" : "fotos"}` : "Toca nas fotos que queres"}</span>
<span className="arq-grow" />
{picked.size < Math.min(photos.length, MAX_PICKED) && (
<button type="button" className="arq-btn ghost" onClick={() => setPicked(new Set(photos.slice(0, MAX_PICKED).map((p) => p.id)))}>
Todas as visíveis
</button>
)}
<button type="button" className="arq-btn accent" disabled={!picked.size || !!saving} onClick={() => save({ photoIds: [...picked] }, "picked")}>
<Icon name="download" size={18} />
{saving === "picked" ? "A preparar…" : "Descarregar"}
</button>
<button type="button" className="arq-round" aria-label="Cancelar seleção" onClick={() => setPicked(null)}>
<Icon name="close" size={18} />
</button>
</div>
)}
{photos.length < total && (
<div className="arq-more">
<button type="button" className="arq-btn" disabled={more} onClick={loadMore}>
@@ -253,6 +322,7 @@ export function Gallery({
onFace={onFace}
onPerson={onPerson}
review={me?.canReview ? { sourceId, onDone: () => forget(`/v1/archive/${sourceId}/`) } : undefined}
onDownload={(photoId) => save({ photoIds: [photoId] }, "one")}
/>
)}
</>
+10 -2
View File
@@ -18,6 +18,7 @@ export function Lightbox({
onPerson,
extra,
review,
onDownload,
}: {
photos: ArchivePhoto[];
index: number;
@@ -30,6 +31,8 @@ export function Lightbox({
onFace: (faceId: string) => void;
onPerson: (personId: string) => void;
extra?: (p: ArchivePhoto) => ReactNode;
/** Saves this photo at web size. */
onDownload?: (photoId: string) => void;
}) {
const current = photos[index]!;
const [showFaces, setShowFaces] = useState(true);
@@ -98,10 +101,15 @@ export function Lightbox({
{index + 1} / {photos.length}
</strong>
<span className="arq-grow" />
{onDownload && (
<button type="button" className="arq-btn accent" onClick={() => onDownload(current.id)}>
<Icon name="download" size={18} />
<span className="arq-hide-sm">Descarregar</span>
</button>
)}
{current.cloudUrl && (
<a className="arq-btn accent" href={current.cloudUrl} target="_blank" rel="noreferrer">
<a className="arq-round" href={current.cloudUrl} target="_blank" rel="noreferrer" title="Original em alta qualidade (cloud)" aria-label="Original em alta qualidade (cloud)">
<Icon name="cloud" size={18} />
Original na cloud
</a>
)}
<button type="button" className="arq-round" onClick={() => onIndex(null)} aria-label="Fechar">
+2 -1
View File
@@ -1,7 +1,7 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { cached, call, day, forget, Forbidden, LEVEL, Unauthorised, type Level, type Me, type PersonHistory, type PhotoFace, type PhotosOfResult } from "./api";
import { cached, call, day, download, forget, Forbidden, LEVEL, Unauthorised, type Level, type Me, type PersonHistory, type PhotoFace, type PhotosOfResult } from "./api";
import { Lightbox } from "./Lightbox";
import { FaceCrop, Icon, Loading, PersonFace } from "./parts";
@@ -189,6 +189,7 @@ export function PhotosOf({
onFace={onFace}
onPerson={onPerson}
review={me?.canReview ? { sourceId, onDone: () => forget(`/v1/archive/${sourceId}/`) } : undefined}
onDownload={(photoId) => void download(sourceId, token, { photoIds: [photoId] }).catch((err) => (err instanceof Unauthorised ? onExpired() : undefined))}
extra={(p) =>
p.gallery ? (
<>
+21 -1
View File
@@ -94,7 +94,8 @@ export interface GalleryDetail {
awayShort?: string | null;
competition: string | null;
startsAt: string | null;
cloudUrl: string;
/** Only for those who edit this folder on the cloud: the full-size originals are there. */
cloudUrl?: string;
total?: number;
people?: GalleryPerson[];
/** People named anywhere in this game. */
@@ -276,3 +277,22 @@ export function forget(prefix?: string) {
if (!prefix) return cache.clear();
for (const k of [...cache.keys()]) if (k.includes(prefix)) cache.delete(k);
}
/** Most photos picked one by one for one download (a whole gallery goes by its folder). */
export const MAX_PICKED = 100;
/**
* Downloads photos at web size (2048 px, with credits and names): one as a JPEG, several as a ZIP. The API gives
* a short-lived link; the browser saves what it sends (no page change).
*/
export async function download(sourceId: string, token: string, ask: { photoIds: string[] } | { folderId: string }): Promise<number> {
const { body } = await call<{ url: string; photos: number }>(`/v1/archive/${sourceId}/downloads`, token, { method: "POST", body: JSON.stringify(ask) });
const a = document.createElement("a");
a.href = body.url;
a.download = "";
a.rel = "noopener";
document.body.appendChild(a);
a.click();
a.remove();
return body.photos;
}
@@ -928,6 +928,41 @@
top: 8px;
right: 8px;
}
.arq-grid.picking .arq-tile {
cursor: pointer;
}
.arq-grid.picking .arq-tile img {
transition: transform 0.15s ease, opacity 0.15s ease;
}
.arq-tile.on {
box-shadow: 0 0 0 3px var(--primary);
}
.arq-tile.on img {
transform: scale(0.94);
border-radius: 6px;
}
.arq-tile.on .arq-check {
background: var(--primary);
}
.arq-hero-note {
margin: 0;
text-align: center;
font-size: 14px;
color: var(--hero-muted);
}
.arq-cloud-link {
align-self: center;
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 13px;
color: var(--hero-muted);
text-decoration: underline;
text-underline-offset: 3px;
}
.arq-cloud-link:hover {
color: var(--hero-ink);
}
/* People */
.arq-split {
@@ -2015,3 +2050,9 @@
transform: none;
}
}
@media (max-width: 639px) {
.arq-hide-sm {
display: none;
}
}
+4 -1
View File
@@ -1,8 +1,11 @@
import { headers } from "next/headers";
import { ArchiveView, type View } from "./ArchiveView";
import { load } from "./load";
/** The archive shell: the page the URL asked for, in its owner's template (`data-look`, archive.css). */
export async function ArchiveFrame({ id, start }: { id: string; start?: View }) {
const info = await load(id);
return <ArchiveView info={info} start={start} />;
// On the archive's own address (the middleware rewrote `/g/…` to here) its links stay at the root.
const atRoot = (await headers()).get("x-arquivo-root") === "1";
return <ArchiveView info={{ ...info, base: atRoot ? "" : `/arquivo/${info.id}` }} start={start} />;
}
+4
View File
@@ -9,6 +9,10 @@ export interface ArchiveInfo {
organization: string;
/** The owner's colours and type (Liga Portugal, FPA), or PhotoReport's. */
look?: "liga" | "fpa" | null;
/** Its own address ("arquivo.ligaportugal.pt"), where it is served at the root. */
hostname?: string | null;
/** Where its pages are on this request's host: "" on its own address, else `/arquivo/<id>`. */
base?: string;
}
export async function load(id: string): Promise<ArchiveInfo> {
+40 -3
View File
@@ -1,12 +1,49 @@
import { type NextRequest, NextResponse } from "next/server";
const API = process.env.API_URL ?? "http://localhost:3000";
const FOUND_MS = 5 * 60_000;
const MISSING_MS = 60_000;
/** Which archive each host shows at its root (null: none), as the API said a moment ago. */
const hosts = new Map<string, { id: string | null; until: number }>();
/** The archive with this address of its own, if any (asked once every few minutes per host). */
async function archiveAt(host: string): Promise<string | null> {
const known = hosts.get(host);
if (known && known.until > Date.now()) return known.id;
let id: string | null = null;
try {
const res = await fetch(`${API}/v1/archive/host?host=${encodeURIComponent(host)}`, { cache: "no-store", signal: AbortSignal.timeout(2000) });
if (res.ok) id = ((await res.json()) as { id: string }).id;
else if (res.status !== 404) return known?.id ?? null;
} catch {
// The API is down: keep what was known, ask again next time.
return known?.id ?? null;
}
if (hosts.size > 500) hosts.clear();
hosts.set(host, { id, until: Date.now() + (id ? FOUND_MS : MISSING_MS) });
return id;
}
/**
* An affiliate link (`?ref=CODE`) is remembered for 30 days; the order sends it and the API credits the affiliate.
* The path is passed on to the layout (`x-pr-path`): the event pages (`/e/…`) work on a domain without a site.
* An archive's own address (`arquivo.ligaportugal.pt`) shows that archive at its root: `/g/…` there is
* `/arquivo/<id>/g/…`.
*/
export function middleware(req: NextRequest) {
export async function middleware(req: NextRequest) {
const headers = new Headers(req.headers);
headers.set("x-pr-path", req.nextUrl.pathname);
const host = (req.headers.get("x-forwarded-host") ?? req.headers.get("host") ?? "").split(",")[0]!.trim().toLowerCase().replace(/:\d+$/, "");
const path = req.nextUrl.pathname;
const archive = host && !path.startsWith("/arquivo/") && !path.startsWith("/e/") ? await archiveAt(host) : null;
if (archive) {
const url = req.nextUrl.clone();
url.pathname = `/arquivo/${archive}${path === "/" ? "" : path}`;
headers.set("x-pr-path", url.pathname);
headers.set("x-arquivo-root", "1");
return NextResponse.rewrite(url, { request: { headers } });
}
headers.set("x-pr-path", path);
headers.delete("x-arquivo-root");
const ref = req.nextUrl.searchParams.get("ref")?.trim();
if (!ref || !/^[A-Za-z0-9_-]{3,40}$/.test(ref)) return NextResponse.next({ request: { headers } });
const res = NextResponse.next({ request: { headers } });
@@ -14,4 +51,4 @@ export function middleware(req: NextRequest) {
return res;
}
export const config = { matcher: ["/((?!_next/|v1/|favicon).*)"] };
export const config = { matcher: ["/((?!_next/|v1/|favicon).*)"], runtime: "nodejs" };
+18 -1
View File
@@ -150,7 +150,24 @@ link survives refresh. A gallery page is 48 thumbs; the faces of a photo load wh
of faces is the people named in that folder. "Pessoas do jogo" lists everyone named in the game (every part
the viewer may see); choosing one shows their photos in this part, or all of their photos. People, similar faces and the player directory join
`cloud_files` for the source (and the viewer's folders when they do not see everything) instead of loading every
photo id. Originals still open on the cloud itself (`/f/<fileid>`).
photo id. Normal viewers never see the cloud named: the full-size originals (`cloudUrl` on a gallery and its
photos) are given only to those who edit that folder on the cloud, as a small link.
### Downloads
Every viewer downloads at web size: 2048 px on the long side, with the photo's metadata (credits, caption, names);
the grid shows 480 px thumbs. One photo from the large view, a selection (up to 100) or a whole gallery (up to
1000) as a ZIP. `POST /v1/archive/:source/downloads` (`{photoIds}` or `{folderId}`, checked against what the viewer
may see) answers a link, `/v1/archive/dl?t=<ticket>`, signed (HMAC with `JWT_SECRET`) and valid 10 minutes; the
browser follows it. Photos kept at full size are made 2048 px on the way out.
### Own address
An archive can have its own host (`cloud_sources.hostname`, app → Arquivo → "Endereço próprio"), e.g.
`arquivo.ligaportugal.pt`: the site's middleware asks the API (`GET /v1/archive/host?host=`, kept 5 minutes) and
serves that archive at the root (`/g/…`, `/p/…`, `/f/…`); links stay at the root. The host's DNS points at the
proxy; Caddy gets its certificate on demand, after asking the same endpoint (`?domain=`, 200 only for an archive's
host; `infra/proxy/Caddyfile.example`). A host can be one archive's or one public site's, never both.
### People and faces (viewers too)
+18
View File
@@ -1,6 +1,13 @@
# Reverse proxy for the `next` environment (Caddy obtains the certificates). Adjust the upstream addresses
# to the containers (docs/ARCHITECTURE.md, Infrastructure).
{
# Archives' own addresses (docs/archive.md): a certificate only for a host the API knows.
on_demand_tls {
ask http://pr-api:3000/v1/archive/host
}
}
app.next.photoreport.pt {
# The SPA (static build in /var/www/photoreport-app/current); the engine's WASM needs its media type.
root * /var/www/photoreport-app/current
@@ -25,3 +32,14 @@ next.photoreport.pt, shootyourmove.next.photoreport.pt, events.next.photoreport.
header_up X-Forwarded-Host {host}
}
}
# An archive's own address ("arquivo.ligaportugal.pt", set in the app): any other host whose DNS points here.
# The site looks the host up and serves that archive at the root.
https:// {
tls {
on_demand
}
reverse_proxy pr-site:3100 {
header_up X-Forwarded-Host {host}
}
}
+1 -1
View File
@@ -779,7 +779,7 @@ export class ApiClient {
return this.request<CloudSource>("POST", `/v1/cloud-sources/${sourceId}/login`);
}
updateCloudSource(sourceId: string, input: { name?: string; rootPath?: string; paused?: boolean; look?: "liga" | "fpa" | null }) {
updateCloudSource(sourceId: string, input: { name?: string; rootPath?: string; paused?: boolean; look?: "liga" | "fpa" | null; hostname?: string | null }) {
return this.request<CloudSource>("PATCH", `/v1/cloud-sources/${sourceId}`, input);
}
+2
View File
@@ -436,6 +436,8 @@ export interface CloudSource {
rootPath: string;
/** How the archive's site looks: Liga Portugal's or FPA's colours and type, or PhotoReport's (null). */
look?: "liga" | "fpa" | null;
/** The archive's own address ("arquivo.ligaportugal.pt"): the site serves it at the root there. */
hostname?: string | null;
/** The cloud account (once authorised). */
account: string | null;
status: "LOGIN" | "READY" | "SCANNING" | "ERROR" | "PAUSED";