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
+1272 -9

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

@@ -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>;
}
+4 -6
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,8 +27,7 @@ export default async function EditorialProfilePage() {
.limit(1);
return (
<main className="portal-shell">
<section className="content-section" aria-labelledby="profile-title">
<section className="editorial-section" aria-labelledby="profile-title">
<p className="eyebrow">Redaktionskonto</p>
<h1 id="profile-title">Profil</h1>
<dl>
@@ -56,6 +55,5 @@ export default async function EditorialProfilePage() {
</dd>
</dl>
</section>
</main>
);
}
+19
View File
@@ -0,0 +1,19 @@
/* eslint-disable @next/next/no-img-element */
type BrandLogoProps = {
variant: "black" | "white";
};
export function BrandLogo({ variant }: Readonly<BrandLogoProps>) {
const source = variant === "white" ? "/brand/logo-white.png" : "/brand/logo-black.png";
return (
<img
alt="Leon Tonhäuser Sportfotografie"
className="brand-logo"
height="64"
src={source}
width="250"
/>
);
}
+25
View File
@@ -0,0 +1,25 @@
import type { ReactNode } from "react";
import Link from "next/link";
import { BrandLogo } from "@/components/brand/logo";
export function PortalShell({ children }: Readonly<{ children: ReactNode }>) {
return (
<div className="editorial-shell">
<header className="portal-masthead">
<Link aria-label="Zur Albenübersicht" className="portal-brand" href="/redaktion/alben">
<BrandLogo variant="white" />
</Link>
<div className="portal-masthead-meta">
<span>Redaktionsarchiv</span>
<nav aria-label="Redaktion">
<Link href="/redaktion/alben">Alben</Link>
<Link href="/redaktion/profil">Profil</Link>
</nav>
</div>
</header>
<main className="editorial-work-surface">{children}</main>
</div>
);
}
@@ -0,0 +1,62 @@
// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import { expect, test } from "vitest";
import { AlbumContactSheet, PhotoContactSheet } from "./catalog-content";
test("renders granted albums as labelled contact-sheet links", () => {
render(
<AlbumContactSheet
albums={[
{
id: "heimspiel",
albumName: "Heimspiel gegen Nord",
description: null,
albumThumbnailAssetId: "cover-1",
assetCount: 24,
},
]}
/>,
);
const album = screen.getByRole("link", { name: /heimspiel gegen nord/i });
expect(album.getAttribute("href")).toBe("/redaktion/alben/heimspiel");
expect(screen.getByText("24 Fotos")).not.toBeNull();
expect(screen.getByAltText("Titelbild: Heimspiel gegen Nord").getAttribute("src")).toBe(
"/api/assets/cover-1/thumbnail",
);
});
test("renders a labelled photo search and descriptive contact-sheet metadata", () => {
render(
<PhotoContactSheet
albumName="Heimspiel gegen Nord"
page={{
items: [
{
id: "asset-1",
type: "IMAGE",
originalFileName: "tor-des-sieges.jpg",
originalMimeType: "image/jpeg",
localDateTime: "2026-08-08T18:42:00.000Z",
fileCreatedAt: null,
albums: [{ id: "heimspiel" }],
},
],
total: 1,
nextPage: null,
previousPage: null,
}}
query="Tor"
/>,
);
expect(screen.getByRole("search", { name: /fotos in heimspiel gegen nord durchsuchen/i })).not.toBeNull();
expect((screen.getByRole("searchbox", { name: /suchbegriff/i }) as HTMLInputElement).value).toBe("Tor");
expect(screen.getByAltText("tor-des-sieges.jpg").getAttribute("src")).toBe(
"/api/assets/asset-1/thumbnail",
);
expect(screen.getByText("tor-des-sieges.jpg")).not.toBeNull();
expect(screen.getByText(/1 foto gefunden/i)).not.toBeNull();
});
+136
View File
@@ -0,0 +1,136 @@
/* eslint-disable @next/next/no-img-element */
import Link from "next/link";
import type { ImmichSearchPage } from "@/modules/immich/types";
import type { VisibleAlbum } from "./catalog";
export function AlbumContactSheet({ albums }: Readonly<{ albums: VisibleAlbum[] }>) {
return (
<ul className="album-contact-sheet" aria-label="Freigegebene Fotoalben">
{albums.map((album) => (
<li key={album.id}>
<Link className="contact-sheet-link" href={`/redaktion/alben/${encodeURIComponent(album.id)}`}>
<article className="album-contact-frame">
{album.albumThumbnailAssetId ? (
<img
alt={`Titelbild: ${album.albumName}`}
className="contact-sheet-image"
height="480"
src={thumbnailUrl(album.albumThumbnailAssetId)}
width="720"
/>
) : (
<div aria-label={`Kein Titelbild für ${album.albumName}`} className="missing-contact-image" role="img">
Kein Titelbild
</div>
)}
<footer className="contact-strip">
<span className="contact-strip-name">{album.albumName}</span>
<span>{formatCount(album.assetCount, "Foto")}</span>
</footer>
</article>
</Link>
</li>
))}
</ul>
);
}
export function PhotoContactSheet({
albumId,
albumName,
page,
query,
}: Readonly<{
albumId?: string;
albumName: string;
page: ImmichSearchPage;
query: string;
}>) {
return (
<>
<form aria-label={`Fotos in ${albumName} durchsuchen`} className="photo-search" role="search">
<label htmlFor="photo-query">Suchbegriff</label>
<div className="photo-search-controls">
<input defaultValue={query} id="photo-query" name="suche" type="search" />
<button type="submit">Fotos suchen</button>
</div>
</form>
<p aria-live="polite" className="result-summary" role="status">
{formatCount(page.total, "Foto")} gefunden
</p>
{page.items.length === 0 ? (
<p className="catalog-empty">Keine Fotos passen zu dieser Suche. Ändern Sie den Suchbegriff oder wählen Sie ein anderes Album.</p>
) : (
<ul className="photo-contact-sheet" aria-label={`Fotos aus ${albumName}`}>
{page.items.map((asset) => (
<li key={asset.id}>
<figure className="photo-contact-frame">
<img
alt={asset.originalFileName}
className="contact-sheet-image"
height="600"
src={thumbnailUrl(asset.id)}
width="900"
/>
<figcaption className="contact-strip">
<span className="contact-strip-name">{asset.originalFileName}</span>
<span>{formatDate(asset.localDateTime ?? asset.fileCreatedAt)}</span>
</figcaption>
</figure>
</li>
))}
</ul>
)}
{albumId ? <PhotoPagination albumId={albumId} page={page} query={query} /> : null}
</>
);
}
function PhotoPagination({ albumId, page, query }: Readonly<{ albumId: string; page: ImmichSearchPage; query: string }>) {
if (page.previousPage === null && page.nextPage === null) {
return null;
}
return (
<nav aria-label="Suchergebnisseiten" className="photo-pagination">
{page.previousPage === null ? null : (
<Link href={pageHref(albumId, page.previousPage, query)}>Vorherige Seite</Link>
)}
{page.nextPage === null ? null : <Link href={pageHref(albumId, page.nextPage, query)}>Nächste Seite</Link>}
</nav>
);
}
function thumbnailUrl(assetId: string): string {
return `/api/assets/${encodeURIComponent(assetId)}/thumbnail`;
}
function pageHref(albumId: string, page: number, query: string): string {
const parameters = new URLSearchParams({ page: String(page) });
if (query) {
parameters.set("suche", query);
}
return `/redaktion/alben/${encodeURIComponent(albumId)}?${parameters.toString()}`;
}
function formatCount(count: number, noun: string): string {
return `${count} ${noun}${count === 1 ? "" : "s"}`;
}
function formatDate(value: string | null): string {
if (!value) {
return "Ohne Zeitangabe";
}
const date = new Date(value);
if (Number.isNaN(date.valueOf())) {
return "Ohne Zeitangabe";
}
return new Intl.DateTimeFormat("de-DE", { dateStyle: "medium" }).format(date);
}
+127
View File
@@ -0,0 +1,127 @@
import { expect, test, vi } from "vitest";
import {
AlbumCatalogError,
createAlbumCatalog,
} from "./catalog";
import type { ImmichClient } from "@/modules/immich/types";
const allowedAlbum = {
id: "allowed",
albumName: "Heimspiel gegen Nord",
description: null,
albumThumbnailAssetId: "cover-1",
assetCount: 12,
};
function createCatalog(options?: {
grantedAlbumIds?: string[];
searchError?: Error;
}) {
const grants = {
getGrantedAlbumIds: vi.fn().mockResolvedValue(options?.grantedAlbumIds ?? ["allowed"]),
};
const immich = {
listAlbums: vi.fn().mockResolvedValue([allowedAlbum, { ...allowedAlbum, id: "other" }]),
searchPhotos: vi.fn().mockImplementation(async () => {
if (options?.searchError) throw options.searchError;
return { items: [], total: 0, nextPage: null, previousPage: null };
}),
};
return {
catalog: createAlbumCatalog({ grants, immich }),
grants,
immich,
};
}
test("ignores a caller-supplied album outside the editorial grants", async () => {
const { catalog, immich } = createCatalog({ grantedAlbumIds: ["allowed"] });
await catalog.searchVisiblePhotos("editorial-1", {
requestedAlbumId: "forbidden",
description: "tor",
page: 1,
});
expect(immich.searchPhotos).toHaveBeenCalledWith(
expect.objectContaining({ albumIds: ["allowed"], description: "tor", type: "IMAGE" }),
);
});
test("uses a requested album only when it is in the current editorial grants", async () => {
const { catalog, immich } = createCatalog({ grantedAlbumIds: ["allowed", "also-allowed"] });
await catalog.searchVisiblePhotos("editorial-1", { requestedAlbumId: "also-allowed", page: 1 });
expect(immich.searchPhotos).toHaveBeenCalledWith(
expect.objectContaining({ albumIds: ["also-allowed"], type: "IMAGE" }),
);
});
test("does not call Immich when an editorial has no current album grants", async () => {
const { catalog, immich } = createCatalog({ grantedAlbumIds: [] });
await expect(catalog.searchVisiblePhotos("editorial-1", { page: 1 })).resolves.toEqual({
items: [],
total: 0,
nextPage: null,
previousPage: null,
});
expect(immich.searchPhotos).not.toHaveBeenCalled();
});
test("reads grants for every search so a revoked grant is immediately excluded", async () => {
const { catalog, grants, immich } = createCatalog({ grantedAlbumIds: ["allowed"] });
grants.getGrantedAlbumIds.mockResolvedValueOnce(["allowed"]).mockResolvedValueOnce([]);
await catalog.searchVisiblePhotos("editorial-1", { page: 1 });
await catalog.searchVisiblePhotos("editorial-1", { page: 1 });
expect(immich.searchPhotos).toHaveBeenCalledTimes(1);
});
test("normalizes descriptions and bounds invalid pagination before sending an upstream request", async () => {
const { catalog, immich } = createCatalog();
await catalog.searchVisiblePhotos("editorial-1", {
description: " Tor\n des\tSieges ",
page: Number.POSITIVE_INFINITY,
});
expect(immich.searchPhotos).toHaveBeenCalledWith({
albumIds: ["allowed"],
description: "Tor des Sieges",
type: "IMAGE",
page: 1,
size: 60,
});
await catalog.searchVisiblePhotos("editorial-1", { page: 100_000 });
expect(immich.searchPhotos).toHaveBeenLastCalledWith(
expect.objectContaining({ page: 1_000 }),
);
});
test("only returns the current editorial's albums from the Immich album list", async () => {
const { catalog } = createCatalog({ grantedAlbumIds: ["allowed"] });
await expect(catalog.getVisibleAlbums("editorial-1")).resolves.toEqual([allowedAlbum]);
});
test("maps an Immich search outage to the catalog's stable unavailable state", async () => {
const { catalog } = createCatalog({ searchError: new Error("upstream down") });
await expect(catalog.searchVisiblePhotos("editorial-1", { page: 1 })).rejects.toEqual(
new AlbumCatalogError("IMMICH_UNAVAILABLE"),
);
});
test("does not expose a caller-controlled asset type in the catalog contract", async () => {
const { catalog, immich } = createCatalog();
await catalog.searchVisiblePhotos("editorial-1", { page: 2, type: "VIDEO" } as never);
expect(immich.searchPhotos).toHaveBeenCalledWith(expect.objectContaining({ type: "IMAGE" }));
});
+115
View File
@@ -0,0 +1,115 @@
import "server-only";
import { albumGrantService } from "@/modules/albums/grants";
import { immichClient } from "@/modules/immich/client";
import type { ImmichAlbumSummary, ImmichClient, ImmichSearchPage } from "@/modules/immich/types";
export const PHOTO_PAGE_SIZE = 60;
export const MAX_PHOTO_PAGE = 1_000;
const MAX_DESCRIPTION_LENGTH = 200;
export type VisibleAlbum = ImmichAlbumSummary;
export type SearchVisiblePhotosInput = {
requestedAlbumId?: string;
description?: unknown;
page?: unknown;
};
export type AlbumCatalogDependencies = {
grants: Pick<typeof albumGrantService, "getGrantedAlbumIds">;
immich: Pick<ImmichClient, "listAlbums" | "searchPhotos">;
};
export class AlbumCatalogError extends Error {
readonly name = "AlbumCatalogError";
constructor(readonly code: "IMMICH_UNAVAILABLE") {
super(code);
}
}
export function createAlbumCatalog({ grants, immich }: AlbumCatalogDependencies) {
return {
async getVisibleAlbums(editorialId: string): Promise<VisibleAlbum[]> {
const [grantedAlbumIds, albums] = await Promise.all([
currentGrantIds(grants, editorialId),
loadAlbums(immich),
]);
const granted = new Set(grantedAlbumIds);
return albums.filter((album) => granted.has(album.id));
},
async searchVisiblePhotos(
editorialId: string,
input: SearchVisiblePhotosInput,
): Promise<ImmichSearchPage> {
const grantedAlbumIds = await currentGrantIds(grants, editorialId);
const albumIds = authorizedSearchAlbums(grantedAlbumIds, input.requestedAlbumId);
if (albumIds.length === 0) {
return emptySearchPage();
}
const description = normalizeDescription(input.description);
try {
return await immich.searchPhotos({
albumIds,
...(description === undefined ? {} : { description }),
type: "IMAGE",
page: normalizePage(input.page),
size: PHOTO_PAGE_SIZE,
});
} catch {
throw new AlbumCatalogError("IMMICH_UNAVAILABLE");
}
},
};
}
function emptySearchPage(): ImmichSearchPage {
return { items: [], total: 0, nextPage: null, previousPage: null };
}
async function currentGrantIds(
grants: Pick<typeof albumGrantService, "getGrantedAlbumIds">,
editorialId: string,
): Promise<string[]> {
return [...new Set(await grants.getGrantedAlbumIds(editorialId))];
}
function authorizedSearchAlbums(grantedAlbumIds: string[], requestedAlbumId: string | undefined): string[] {
if (requestedAlbumId && grantedAlbumIds.includes(requestedAlbumId)) {
return [requestedAlbumId];
}
return grantedAlbumIds;
}
function normalizeDescription(description: unknown): string | undefined {
if (typeof description !== "string") {
return undefined;
}
const normalized = description.replace(/\s+/g, " ").trim().slice(0, MAX_DESCRIPTION_LENGTH);
return normalized || undefined;
}
function normalizePage(page: unknown): number {
if (typeof page !== "number" || !Number.isFinite(page) || !Number.isInteger(page)) {
return 1;
}
return Math.min(MAX_PHOTO_PAGE, Math.max(1, page));
}
async function loadAlbums(
immich: Pick<ImmichClient, "listAlbums">,
): Promise<ImmichAlbumSummary[]> {
try {
return await immich.listAlbums();
} catch {
throw new AlbumCatalogError("IMMICH_UNAVAILABLE");
}
}
export const albumCatalog = createAlbumCatalog({
grants: albumGrantService,
immich: immichClient,
});
+1 -1
View File
@@ -38,7 +38,7 @@ export interface ImmichClient {
listAlbums(signal?: AbortSignal): Promise<ImmichAlbumSummary[]>;
getAlbum(albumId: string, signal?: AbortSignal): Promise<ImmichAlbum>;
searchPhotos(
input: { albumIds: string[]; description?: string; page: number; size: number },
input: { albumIds: string[]; description?: string; page: number; size: number; type?: "IMAGE" },
signal?: AbortSignal,
): Promise<ImmichSearchPage>;
getThumbnail(assetId: string, signal?: AbortSignal): Promise<ImmichBinary>;