feat: add branded editorial photo catalog

This commit is contained in:
Leon Tonhäuser committed 2026-08-09 22:22:31 +02:00
1 parent f6e6018cc1
commit 66f0599653
20 files changed
+1299 -36

No files matched your search

@@ -0,0 +1,131 @@
import { expect, test, vi } from "vitest";
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
import { createThumbnailHandler } from "./thumbnail-handler";
const grantedAlbum = {
id: "allowed",
albumName: "Freigegebenes Heimspiel",
description: null,
albumThumbnailAssetId: "cover-1",
assetCount: 1,
};
function thumbnail() {
return {
body: new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array([1, 2, 3]));
controller.close();
},
}),
contentType: "image/jpeg",
contentLength: 3,
filename: "tor.jpg",
};
}
function createHandler(options?: {
editorialError?: Error;
grantedAlbumIds?: string[];
albumAssets?: Array<{ id: string; type: "IMAGE"; albums: Array<{ id: string }> }>;
albumError?: Error;
adminAlbums?: typeof grantedAlbum[];
}) {
const dependencies = {
requireActiveEditorial: vi
.fn()
.mockImplementation(async () => {
if (options?.editorialError) throw options.editorialError;
return { editorialId: "editorial-1" };
}),
requireAdmin: vi.fn().mockResolvedValue({ userId: "admin-1" }),
getGrantedAlbumIds: vi.fn().mockResolvedValue(options?.grantedAlbumIds ?? ["allowed"]),
immich: {
listAlbums: vi.fn().mockResolvedValue(options?.adminAlbums ?? [grantedAlbum]),
getAlbum: vi.fn().mockImplementation(async () => {
if (options?.albumError) throw options.albumError;
return {
...grantedAlbum,
assets: options?.albumAssets ?? [
{ id: "asset-1", type: "IMAGE", albums: [{ id: "allowed" }] },
],
};
}),
getThumbnail: vi.fn().mockResolvedValue(thumbnail()),
},
};
return { handler: createThumbnailHandler(dependencies), dependencies };
}
function call(handler: ReturnType<typeof createThumbnailHandler>, assetId = "asset-1") {
return handler(new Request("http://portal.test/api/assets/asset-1/thumbnail"), {
params: Promise.resolve({ assetId }),
});
}
test("streams a thumbnail when the requested asset belongs to any current grant", async () => {
const { handler, dependencies } = createHandler({
albumAssets: [{ id: "asset-1", type: "IMAGE", albums: [{ id: "other" }, { id: "allowed" }] }],
});
const response = await call(handler);
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("private, no-store");
await expect(response.arrayBuffer()).resolves.toEqual(new Uint8Array([1, 2, 3]).buffer);
expect(dependencies.immich.getThumbnail).toHaveBeenCalledWith("asset-1");
});
test("refuses a thumbnail immediately after its last grant is revoked", async () => {
const { handler, dependencies } = createHandler({ grantedAlbumIds: [] });
const response = await call(handler);
expect(response.status).toBe(404);
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled();
});
test("uses an identical generic 404 for forbidden and missing assets", async () => {
const forbidden = createHandler({ albumAssets: [{ id: "different", type: "IMAGE", albums: [{ id: "allowed" }] }] });
const missing = createHandler({ albumError: new Error("IMMICH_NOT_FOUND") });
const [forbiddenResponse, missingResponse] = await Promise.all([
call(forbidden.handler),
call(missing.handler),
]);
expect({ status: forbiddenResponse.status, body: await forbiddenResponse.text() }).toEqual({
status: missingResponse.status,
body: await missingResponse.text(),
});
expect(forbidden.dependencies.immich.getThumbnail).not.toHaveBeenCalled();
expect(missing.dependencies.immich.getThumbnail).not.toHaveBeenCalled();
});
test("allows an admin only to load an existing Immich album cover", async () => {
const { handler, dependencies } = createHandler({
editorialError: new PrincipalAuthorizationError("ADMIN_REQUIRED"),
adminAlbums: [grantedAlbum],
});
const response = await call(handler, "cover-1");
expect(response.status).toBe(200);
expect(dependencies.requireAdmin).toHaveBeenCalledTimes(1);
expect(dependencies.getGrantedAlbumIds).not.toHaveBeenCalled();
expect(dependencies.immich.getThumbnail).toHaveBeenCalledWith("cover-1");
});
test("does not let an admin proxy an arbitrary non-cover asset", async () => {
const { handler, dependencies } = createHandler({
editorialError: new PrincipalAuthorizationError("ADMIN_REQUIRED"),
adminAlbums: [grantedAlbum],
});
const response = await call(handler, "asset-not-a-cover");
expect(response.status).toBe(404);
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled();
});
@@ -0,0 +1,3 @@
import { authorizedThumbnailHandler } from "./thumbnail-handler";
export const GET = authorizedThumbnailHandler;
@@ -0,0 +1,115 @@
import "server-only";
import { requireActiveEditorial, requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
import { albumGrantService } from "@/modules/albums/grants";
import { immichClient } from "@/modules/immich/client";
import type { ImmichBinary } from "@/modules/immich/types";
type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
type ThumbnailImmich = {
listAlbums(): Promise<Array<{ albumThumbnailAssetId: string | null }>>;
getAlbum(albumId: string): Promise<{ assets: Array<{ id: string; type: "IMAGE" }> }>;
getThumbnail(assetId: string): Promise<ImmichBinary>;
};
export type ThumbnailHandlerDependencies = {
requireActiveEditorial: typeof requireActiveEditorial;
requireAdmin: typeof requireAdmin;
getGrantedAlbumIds: typeof albumGrantService.getGrantedAlbumIds;
immich: ThumbnailImmich;
};
type Access = { kind: "admin" } | { kind: "editorial"; editorialId: string };
export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencies) {
return async function GET(request: Request, context: ThumbnailRouteContext): Promise<Response> {
try {
const { assetId } = await context.params;
if (!isSafeAssetId(assetId)) {
return genericNotFound();
}
const access = await authorizeRequest(dependencies, request.headers);
const authorized =
access.kind === "admin"
? await isAdminAlbumCover(dependencies.immich, assetId)
: await isGrantedEditorialAsset(dependencies, access.editorialId, assetId);
if (!authorized) {
return genericNotFound();
}
const thumbnail = await dependencies.immich.getThumbnail(assetId);
return thumbnailResponse(thumbnail);
} catch {
return genericNotFound();
}
};
}
async function authorizeRequest(
dependencies: ThumbnailHandlerDependencies,
requestHeaders: Headers,
): Promise<Access> {
try {
const principal = await dependencies.requireActiveEditorial(requestHeaders);
return { kind: "editorial", editorialId: principal.editorialId };
} catch (error) {
if (!(error instanceof PrincipalAuthorizationError) || error.code !== "ADMIN_REQUIRED") {
throw error;
}
}
await dependencies.requireAdmin(requestHeaders);
return { kind: "admin" };
}
async function isGrantedEditorialAsset(
dependencies: ThumbnailHandlerDependencies,
editorialId: string,
assetId: string,
): Promise<boolean> {
const grantedAlbumIds = [...new Set(await dependencies.getGrantedAlbumIds(editorialId))];
if (grantedAlbumIds.length === 0) {
return false;
}
const grantedAlbums = await Promise.all(
grantedAlbumIds.map((albumId) => dependencies.immich.getAlbum(albumId)),
);
return grantedAlbums.some((album) =>
album.assets.some((asset) => asset.id === assetId && asset.type === "IMAGE"),
);
}
async function isAdminAlbumCover(immich: ThumbnailImmich, assetId: string): Promise<boolean> {
const albums = await immich.listAlbums();
return albums.some((album) => album.albumThumbnailAssetId === assetId);
}
function thumbnailResponse(thumbnail: ImmichBinary): Response {
const responseHeaders = new Headers({
"cache-control": "private, no-store",
"content-type": thumbnail.contentType,
"x-content-type-options": "nosniff",
});
if (thumbnail.contentLength !== null) {
responseHeaders.set("content-length", String(thumbnail.contentLength));
}
return new Response(thumbnail.body, { headers: responseHeaders });
}
function genericNotFound(): Response {
return new Response(null, { status: 404 });
}
function isSafeAssetId(assetId: string): boolean {
return /^[A-Za-z0-9_-]{1,200}$/.test(assetId);
}
export const authorizedThumbnailHandler = createThumbnailHandler({
requireActiveEditorial,
requireAdmin,
getGrantedAlbumIds: albumGrantService.getGrantedAlbumIds,
immich: immichClient,
});
+343 -2
View File
@@ -2,8 +2,11 @@
:root {
--paper: #ffffff;
--ink: #0a0a0a;
--muted: #5f5f5f;
--ink: #050505;
--graphite: #242424;
--contact-sheet: #ececec;
--metadata: #6b6b6b;
--muted: var(--metadata);
--line: #d8d8d8;
--soft: #f3f3f3;
color-scheme: light;
@@ -276,3 +279,341 @@ a {
grid-template-columns: 1fr;
}
}
.editorial-shell {
min-height: 100vh;
background: var(--paper);
}
.portal-masthead {
display: flex;
align-items: center;
justify-content: space-between;
gap: 2rem;
min-height: 5.25rem;
padding: 0.9rem clamp(1.25rem, 4vw, 5rem);
background: var(--ink);
color: var(--paper);
}
.portal-brand {
display: inline-flex;
align-items: center;
min-width: 0;
}
.brand-logo {
display: block;
width: min(14rem, 48vw);
height: auto;
object-fit: contain;
}
.portal-masthead-meta,
.portal-masthead nav {
display: flex;
align-items: center;
gap: clamp(1rem, 2.2vw, 2.25rem);
}
.portal-masthead-meta {
color: #d4d4d4;
font-size: 0.6875rem;
font-weight: 600;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.portal-masthead nav a {
color: var(--paper);
text-decoration: none;
}
.portal-masthead nav a:hover {
text-decoration: underline;
text-underline-offset: 0.28em;
}
.editorial-work-surface {
width: min(100%, 108rem);
margin: 0 auto;
padding: clamp(2rem, 5vw, 5.5rem) clamp(1.25rem, 4vw, 5rem) 5rem;
}
.editorial-section {
max-width: 100%;
}
.editorial-kicker {
margin: 0 0 1rem;
color: var(--metadata);
font-size: 0.6875rem;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.editorial-title-row {
display: flex;
align-items: end;
justify-content: space-between;
gap: 2rem;
margin-bottom: clamp(2rem, 4vw, 3.5rem);
padding-bottom: 1.25rem;
border-bottom: 1px solid var(--ink);
}
.editorial-title-row h1,
.editorial-state h1,
.editorial-section > h1 {
max-width: 15ch;
margin: 0;
font-size: clamp(2.5rem, 5vw, 5.5rem);
font-weight: 600;
letter-spacing: -0.065em;
line-height: 0.9;
}
.editorial-title-row > p {
max-width: 27rem;
margin: 0;
color: var(--graphite);
font-size: 0.95rem;
line-height: 1.5;
}
.album-title-row {
align-items: center;
}
.quiet-link {
flex: none;
color: var(--graphite);
font-size: 0.8125rem;
font-weight: 650;
text-underline-offset: 0.2em;
}
.album-contact-sheet,
.photo-contact-sheet {
display: grid;
gap: clamp(1.25rem, 2.25vw, 2.5rem);
padding: 0;
list-style: none;
}
.album-contact-sheet {
grid-template-columns: repeat(auto-fill, minmax(min(100%, 18rem), 1fr));
}
.photo-contact-sheet {
grid-template-columns: repeat(auto-fill, minmax(min(100%, 13.5rem), 1fr));
}
.contact-sheet-link {
display: block;
color: inherit;
text-decoration: none;
}
.album-contact-frame,
.photo-contact-frame {
margin: 0;
background: var(--contact-sheet);
}
.album-contact-frame {
border: 1px solid var(--ink);
}
.photo-contact-frame {
border-top: 1px solid var(--ink);
}
.contact-sheet-image,
.missing-contact-image {
display: block;
width: 100%;
aspect-ratio: 3 / 2;
object-fit: cover;
background: var(--contact-sheet);
transition: transform 150ms ease-out;
}
.photo-contact-frame .contact-sheet-image {
aspect-ratio: 3 / 2;
}
.missing-contact-image {
display: grid;
place-items: center;
color: var(--metadata);
font-size: 0.75rem;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.contact-sheet-link:hover .contact-sheet-image,
.contact-sheet-link:focus-visible .contact-sheet-image {
transform: scale(1.015);
}
.album-contact-frame,
.photo-contact-frame {
overflow: hidden;
}
.contact-strip {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 0.75rem;
min-height: 2.35rem;
margin: 0;
padding: 0.5rem 0.625rem;
border-top: 1px solid var(--ink);
background: var(--contact-sheet);
color: var(--graphite);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 0.625rem;
letter-spacing: 0.035em;
line-height: 1.25;
text-transform: uppercase;
}
.contact-strip-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.photo-search {
display: grid;
gap: 0.55rem;
width: min(100%, 42rem);
margin-bottom: 1.25rem;
}
.photo-search label {
font-size: 0.75rem;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.photo-search-controls {
display: flex;
align-items: stretch;
}
.photo-search input {
min-width: 0;
flex: 1;
min-height: 3rem;
border: 1px solid var(--ink);
border-right: 0;
border-radius: 0;
background: var(--paper);
color: var(--ink);
font: inherit;
padding: 0.7rem 0.8rem;
}
.photo-search button {
min-height: 3rem;
border: 1px solid var(--ink);
border-radius: 0;
background: var(--ink);
color: var(--paper);
cursor: pointer;
font: inherit;
font-size: 0.8125rem;
font-weight: 700;
padding-inline: 1rem;
}
.photo-search button:hover {
background: var(--graphite);
}
.result-summary {
margin: 0 0 1.5rem;
color: var(--metadata);
font-size: 0.8125rem;
}
.catalog-empty,
.editorial-state > p:not(.editorial-kicker) {
max-width: 38rem;
color: var(--graphite);
font-size: 1rem;
line-height: 1.55;
}
.photo-pagination {
display: flex;
justify-content: space-between;
gap: 1rem;
margin-top: 2.5rem;
padding-top: 1rem;
border-top: 1px solid var(--ink);
font-size: 0.8125rem;
font-weight: 650;
}
.editorial-section dl {
display: grid;
grid-template-columns: minmax(10rem, 14rem) minmax(0, 1fr);
gap: 0.85rem 1.5rem;
max-width: 48rem;
margin: 2rem 0 0;
padding-top: 1.25rem;
border-top: 1px solid var(--ink);
}
.editorial-section dt {
color: var(--metadata);
font-size: 0.75rem;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.editorial-section dd {
margin: 0;
line-height: 1.45;
}
@media (max-width: 44rem) {
.portal-masthead {
align-items: flex-start;
flex-direction: column;
gap: 0.8rem;
}
.portal-masthead-meta {
width: 100%;
justify-content: space-between;
}
.editorial-title-row {
align-items: flex-start;
flex-direction: column;
gap: 1.25rem;
}
.editorial-section dl {
grid-template-columns: 1fr;
gap: 0.25rem;
}
.editorial-section dd {
margin-bottom: 0.75rem;
}
}
@media (prefers-reduced-motion: reduce) {
.contact-sheet-image {
transition: none;
}
}
+11
View File
@@ -0,0 +1,11 @@
import "server-only";
import { cache } from "react";
import { headers } from "next/headers";
import { requireActiveEditorial } from "@/modules/auth/principal";
export const requireEditorial = cache(async () =>
requireActiveEditorial(new Headers(await headers())),
);
@@ -0,0 +1,8 @@
export default function AlbumLoading() {
return (
<section className="editorial-section editorial-state" aria-busy="true" aria-live="polite">
<p className="editorial-kicker">Bildarchiv</p>
<p>Fotos werden geladen.</p>
</section>
);
}
+104
View File
@@ -0,0 +1,104 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { AlbumCatalogError, albumCatalog } from "@/modules/albums/catalog";
import { PhotoContactSheet } from "@/modules/albums/catalog-content";
import { requireEditorial } from "../../access";
type AlbumPageProps = Readonly<{
params: Promise<{ albumId: string }>;
searchParams: Promise<{ page?: string | string[]; suche?: string | string[] }>;
}>;
export default async function AlbumPage({ params, searchParams }: AlbumPageProps) {
const [{ albumId }, rawSearchParams, principal] = await Promise.all([
params,
searchParams,
requireEditorial(),
]);
const query = normalizedQuery(singleValue(rawSearchParams.suche));
const result = await loadAlbumPage({
editorialId: principal.editorialId,
albumId,
query,
page: singleValue(rawSearchParams.page),
});
if (result.unavailable) {
return <ImmichUnavailable />;
}
if (!result.album) {
notFound();
}
return (
<section className="editorial-section" aria-labelledby="album-title">
<p className="editorial-kicker">Bildarchiv · {result.album.assetCount} freigegebene Fotos</p>
<div className="editorial-title-row album-title-row">
<h1 id="album-title">{result.album.albumName}</h1>
<Link className="quiet-link" href="/redaktion/alben">
Alle Alben
</Link>
</div>
<PhotoContactSheet
albumId={result.album.id}
albumName={result.album.albumName}
page={result.page}
query={query}
/>
</section>
);
}
async function loadAlbumPage({
editorialId,
albumId,
query,
page,
}: {
editorialId: string;
albumId: string;
query: string;
page: string | undefined;
}) {
try {
const albums = await albumCatalog.getVisibleAlbums(editorialId);
const album = albums.find((candidate) => candidate.id === albumId);
if (!album) {
return { album: null, page: null, unavailable: false as const };
}
const results = await albumCatalog.searchVisiblePhotos(editorialId, {
requestedAlbumId: album.id,
description: query,
page,
});
return { album, page: results, unavailable: false as const };
} catch (error) {
if (error instanceof AlbumCatalogError && error.code === "IMMICH_UNAVAILABLE") {
return { album: null, page: null, unavailable: true as const };
}
throw error;
}
}
function singleValue(value: string | string[] | undefined): string | undefined {
return typeof value === "string" ? value : undefined;
}
function normalizedQuery(value: string | undefined): string {
return (value ?? "").replace(/\s+/g, " ").trim().slice(0, 200);
}
function ImmichUnavailable() {
return (
<section className="editorial-section editorial-state" aria-labelledby="album-title">
<p className="editorial-kicker">Bildarchiv</p>
<h1 id="album-title">Fotos momentan nicht erreichbar</h1>
<p role="status">Bitte laden Sie diese Seite in wenigen Minuten erneut.</p>
<Link className="quiet-link" href="/redaktion/alben">
Zurück zu den Alben
</Link>
</section>
);
}
+8
View File
@@ -0,0 +1,8 @@
export default function AlbumsLoading() {
return (
<section className="editorial-section editorial-state" aria-busy="true" aria-live="polite">
<p className="editorial-kicker">Bildarchiv</p>
<p>Alben werden geladen.</p>
</section>
);
}
+49
View File
@@ -0,0 +1,49 @@
import { AlbumCatalogError, albumCatalog } from "@/modules/albums/catalog";
import { AlbumContactSheet } from "@/modules/albums/catalog-content";
import { requireEditorial } from "../access";
export default async function AlbumsPage() {
const principal = await requireEditorial();
const result = await loadAlbums(principal.editorialId);
if (result.unavailable) {
return <ImmichUnavailable />;
}
return (
<section className="editorial-section" aria-labelledby="albums-title">
<p className="editorial-kicker">Bildarchiv · Freigaben</p>
<div className="editorial-title-row">
<h1 id="albums-title">Ihre Alben</h1>
<p>Wählen Sie ein Spiel oder eine Serie, um die freigegebenen Fotos zu durchsuchen.</p>
</div>
{result.albums.length === 0 ? (
<p className="catalog-empty">Für Ihre Redaktion sind noch keine Fotoalben freigegeben.</p>
) : (
<AlbumContactSheet albums={result.albums} />
)}
</section>
);
}
async function loadAlbums(editorialId: string) {
try {
return { albums: await albumCatalog.getVisibleAlbums(editorialId), unavailable: false as const };
} catch (error) {
if (error instanceof AlbumCatalogError && error.code === "IMMICH_UNAVAILABLE") {
return { albums: [], unavailable: true as const };
}
throw error;
}
}
function ImmichUnavailable() {
return (
<section className="editorial-section editorial-state" aria-labelledby="albums-title">
<p className="editorial-kicker">Bildarchiv</p>
<h1 id="albums-title">Alben momentan nicht erreichbar</h1>
<p role="status">Bitte laden Sie diese Seite in wenigen Minuten erneut. Ihre Freigaben bleiben unverändert.</p>
</section>
);
}
+11
View File
@@ -0,0 +1,11 @@
import type { ReactNode } from "react";
import { PortalShell } from "@/components/layout/portal-shell";
import { requireEditorial } from "./access";
export default async function EditorialLayout({ children }: Readonly<{ children: ReactNode }>) {
await requireEditorial();
return <PortalShell>{children}</PortalShell>;
}
+31 -33
View File
@@ -1,12 +1,12 @@
import { eq } from "drizzle-orm";
import { headers } from "next/headers";
import { db } from "@/db/client";
import { billingAddressVersions, editorialAccounts } from "@/db/schema";
import { requireActiveEditorial } from "@/modules/auth/principal";
import { requireEditorial } from "../access";
export default async function EditorialProfilePage() {
const principal = await requireActiveEditorial(new Headers(await headers()));
const principal = await requireEditorial();
const [editorial] = await db
.select({
name: editorialAccounts.name,
@@ -27,35 +27,33 @@ export default async function EditorialProfilePage() {
.limit(1);
return (
<main className="portal-shell">
<section className="content-section" aria-labelledby="profile-title">
<p className="eyebrow">Redaktionskonto</p>
<h1 id="profile-title">Profil</h1>
<dl>
<dt>Redaktion</dt>
<dd>{editorial?.name}</dd>
<dt>Ansprechperson</dt>
<dd>{editorial?.contactName}</dd>
<dt>Anmelde-E-Mail</dt>
<dd>{editorial?.loginEmail}</dd>
<dt>Rechnungsadresse</dt>
<dd>
{editorial?.addressLine1 ? (
<address>
{editorial.addressLine1}
{editorial.addressLine2 ? <br /> : null}
{editorial.addressLine2}
<br />
{editorial.postalCode} {editorial.city}
<br />
{editorial.countryCode}
</address>
) : (
"Keine Rechnungsadresse hinterlegt."
)}
</dd>
</dl>
</section>
</main>
<section className="editorial-section" aria-labelledby="profile-title">
<p className="eyebrow">Redaktionskonto</p>
<h1 id="profile-title">Profil</h1>
<dl>
<dt>Redaktion</dt>
<dd>{editorial?.name}</dd>
<dt>Ansprechperson</dt>
<dd>{editorial?.contactName}</dd>
<dt>Anmelde-E-Mail</dt>
<dd>{editorial?.loginEmail}</dd>
<dt>Rechnungsadresse</dt>
<dd>
{editorial?.addressLine1 ? (
<address>
{editorial.addressLine1}
{editorial.addressLine2 ? <br /> : null}
{editorial.addressLine2}
<br />
{editorial.postalCode} {editorial.city}
<br />
{editorial.countryCode}
</address>
) : (
"Keine Rechnungsadresse hinterlegt."
)}
</dd>
</dl>
</section>
);
}