feat: stream originals with download accounting
This commit is contained in:
1 parent
c400167b8f
commit
8871e4794a
28 files changed
+4081
-8
No files matched your search
@@ -0,0 +1,124 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { createRepeatDownload } from "@/modules/downloads/service";
|
||||
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { createNewUsage } from "@/modules/usages/service";
|
||||
import { UsageAccountingError } from "@/modules/usages/types";
|
||||
|
||||
const newUsagePayload = z
|
||||
.object({
|
||||
kind: z.literal("new_usage"),
|
||||
assetId: z.string(),
|
||||
albumId: z.string(),
|
||||
purpose: z.string(),
|
||||
reference: z.string().optional(),
|
||||
idempotencyKey: z.string(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const repeatDownloadPayload = z
|
||||
.object({
|
||||
kind: z.literal("repeat_download"),
|
||||
usageId: z.string(),
|
||||
note: z.string().optional(),
|
||||
idempotencyKey: z.string(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const intentPayload = z.discriminatedUnion("kind", [newUsagePayload, repeatDownloadPayload]);
|
||||
|
||||
type IntentHandlerDependencies = {
|
||||
requireActiveEditorial: typeof requireActiveEditorial;
|
||||
createNewUsage: typeof createNewUsage;
|
||||
createRepeatDownload: typeof createRepeatDownload;
|
||||
};
|
||||
|
||||
export function createDownloadIntentHandler(dependencies: IntentHandlerDependencies) {
|
||||
return async function POST(request: Request): Promise<Response> {
|
||||
try {
|
||||
const principal = await dependencies.requireActiveEditorial(request.headers);
|
||||
const payload = intentPayload.safeParse(await readJson(request));
|
||||
if (!payload.success) return errorResponse(400, "INVALID_REQUEST");
|
||||
|
||||
const intent =
|
||||
payload.data.kind === "new_usage"
|
||||
? await dependencies.createNewUsage({
|
||||
editorialId: principal.editorialId,
|
||||
assetId: payload.data.assetId,
|
||||
albumId: payload.data.albumId,
|
||||
purpose: payload.data.purpose,
|
||||
...(payload.data.reference === undefined
|
||||
? {}
|
||||
: { reference: payload.data.reference }),
|
||||
idempotencyKey: payload.data.idempotencyKey,
|
||||
})
|
||||
: await dependencies.createRepeatDownload({
|
||||
editorialId: principal.editorialId,
|
||||
usageId: payload.data.usageId,
|
||||
...(payload.data.note === undefined ? {} : { note: payload.data.note }),
|
||||
idempotencyKey: payload.data.idempotencyKey,
|
||||
});
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
downloadId: intent.id,
|
||||
fileUrl: `/api/downloads/${encodeURIComponent(intent.id)}/file`,
|
||||
priceCents: intent.priceCents,
|
||||
billable: intent.billable,
|
||||
},
|
||||
{ status: 201, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
} catch (error) {
|
||||
return mappedError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function readJson(request: Request): Promise<unknown> {
|
||||
try {
|
||||
return await request.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function mappedError(error: unknown): Response {
|
||||
if (error instanceof PrincipalAuthorizationError) {
|
||||
return errorResponse(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||
}
|
||||
if (error instanceof UsageAccountingError) {
|
||||
switch (error.code) {
|
||||
case "INVALID_INPUT":
|
||||
return errorResponse(400, "INVALID_REQUEST");
|
||||
case "IDEMPOTENCY_CONFLICT":
|
||||
return errorResponse(409, "IDEMPOTENCY_CONFLICT");
|
||||
case "ALBUM_NOT_GRANTED":
|
||||
case "ASSET_NOT_FOUND":
|
||||
case "ASSET_NOT_IN_ALBUM":
|
||||
case "USAGE_NOT_FOUND":
|
||||
return errorResponse(404, "NOT_FOUND");
|
||||
case "IMMICH_UNAVAILABLE":
|
||||
return errorResponse(503, "UPSTREAM_UNAVAILABLE");
|
||||
case "ASSET_NOT_IMAGE":
|
||||
return errorResponse(422, "INVALID_ASSET");
|
||||
case "EDITORIAL_NOT_ACTIVE":
|
||||
return errorResponse(403, "FORBIDDEN");
|
||||
case "INVALID_PRICE":
|
||||
return errorResponse(409, "ACCOUNTING_UNAVAILABLE");
|
||||
}
|
||||
}
|
||||
return errorResponse(500, "REQUEST_FAILED");
|
||||
}
|
||||
|
||||
function errorResponse(status: number, code: string): Response {
|
||||
return Response.json(
|
||||
{ code },
|
||||
{ status, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
}
|
||||
|
||||
export const authorizedDownloadIntentHandler = createDownloadIntentHandler({
|
||||
requireActiveEditorial,
|
||||
createNewUsage,
|
||||
createRepeatDownload,
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { createDownloadIntentHandler } from "./intent-handler";
|
||||
|
||||
const editorialId = "11111111-1111-4111-8111-111111111111";
|
||||
const assetId = "22222222-2222-4222-8222-222222222222";
|
||||
const albumId = "33333333-3333-4333-8333-333333333333";
|
||||
const usageId = "44444444-4444-4444-8444-444444444444";
|
||||
const idempotencyKey = "55555555-5555-4555-8555-555555555555";
|
||||
const downloadId = "66666666-6666-4666-8666-666666666666";
|
||||
|
||||
function dependencies() {
|
||||
return {
|
||||
requireActiveEditorial: vi.fn().mockResolvedValue({ editorialId }),
|
||||
createNewUsage: vi.fn().mockResolvedValue({
|
||||
id: downloadId,
|
||||
usageId,
|
||||
assetId,
|
||||
priceCents: 1_500,
|
||||
billable: true,
|
||||
status: "authorized",
|
||||
authorizedAt: new Date("2026-08-10T10:00:00.000Z"),
|
||||
}),
|
||||
createRepeatDownload: vi.fn().mockResolvedValue({
|
||||
id: downloadId,
|
||||
usageId,
|
||||
assetId,
|
||||
priceCents: 0,
|
||||
billable: false,
|
||||
status: "authorized",
|
||||
authorizedAt: new Date("2026-08-10T10:00:00.000Z"),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function post(handler: ReturnType<typeof createDownloadIntentHandler>, body: unknown) {
|
||||
return handler(
|
||||
new Request("http://portal.test/api/download-intents", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
test("derives editorial scope and billable price exclusively on the server", async () => {
|
||||
const deps = dependencies();
|
||||
const response = await post(createDownloadIntentHandler(deps), {
|
||||
kind: "new_usage",
|
||||
assetId,
|
||||
albumId,
|
||||
purpose: "Titelgeschichte",
|
||||
idempotencyKey,
|
||||
});
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
downloadId,
|
||||
fileUrl: `/api/downloads/${downloadId}/file`,
|
||||
priceCents: 1_500,
|
||||
billable: true,
|
||||
});
|
||||
expect(deps.createNewUsage).toHaveBeenCalledWith({
|
||||
editorialId,
|
||||
assetId,
|
||||
albumId,
|
||||
purpose: "Titelgeschichte",
|
||||
idempotencyKey,
|
||||
});
|
||||
});
|
||||
|
||||
test("creates a zero-cost repeat intent scoped to the authenticated editorial", async () => {
|
||||
const deps = dependencies();
|
||||
const response = await post(createDownloadIntentHandler(deps), {
|
||||
kind: "repeat_download",
|
||||
usageId,
|
||||
note: "erneuter Abruf",
|
||||
idempotencyKey,
|
||||
});
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(deps.createRepeatDownload).toHaveBeenCalledWith({
|
||||
editorialId,
|
||||
usageId,
|
||||
note: "erneuter Abruf",
|
||||
idempotencyKey,
|
||||
});
|
||||
await expect(response.json()).resolves.toMatchObject({ priceCents: 0, billable: false });
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ field: "editorialId", value: "77777777-7777-4777-8777-777777777777" },
|
||||
{ field: "priceCents", value: 1 },
|
||||
])("rejects a client-controlled $field before any accounting side effect", async ({ field, value }) => {
|
||||
const deps = dependencies();
|
||||
const response = await post(createDownloadIntentHandler(deps), {
|
||||
kind: "new_usage",
|
||||
assetId,
|
||||
albumId,
|
||||
purpose: "Titelgeschichte",
|
||||
idempotencyKey,
|
||||
[field]: value,
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(deps.createNewUsage).not.toHaveBeenCalled();
|
||||
expect(deps.createRepeatDownload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("rejects mixed new and repeat fields as an invalid discriminated payload", async () => {
|
||||
const deps = dependencies();
|
||||
const response = await post(createDownloadIntentHandler(deps), {
|
||||
kind: "repeat_download",
|
||||
usageId,
|
||||
assetId,
|
||||
idempotencyKey,
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(deps.createRepeatDownload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("passes one submitted idempotency key through unchanged", async () => {
|
||||
const deps = dependencies();
|
||||
const handler = createDownloadIntentHandler(deps);
|
||||
const body = {
|
||||
kind: "new_usage",
|
||||
assetId,
|
||||
albumId,
|
||||
purpose: "Titelgeschichte",
|
||||
idempotencyKey,
|
||||
};
|
||||
|
||||
const [first, retry] = await Promise.all([post(handler, body), post(handler, body)]);
|
||||
|
||||
expect(first.status).toBe(201);
|
||||
expect(retry.status).toBe(201);
|
||||
expect(deps.createNewUsage).toHaveBeenNthCalledWith(1, expect.objectContaining({ idempotencyKey }));
|
||||
expect(deps.createNewUsage).toHaveBeenNthCalledWith(2, expect.objectContaining({ idempotencyKey }));
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
import { authorizedDownloadIntentHandler } from "./intent-handler";
|
||||
|
||||
export const POST = authorizedDownloadIntentHandler;
|
||||
@@ -0,0 +1,162 @@
|
||||
import { downloadDeliveryRepository, streamWithAccounting } from "@/modules/downloads/stream";
|
||||
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import type { ImmichBinary } from "@/modules/immich/types";
|
||||
import { normalizeUuid } from "@/modules/usages/types";
|
||||
|
||||
type DownloadFileRouteContext = Readonly<{ params: Promise<{ downloadId: string }> }>;
|
||||
|
||||
type DownloadFileHandlerDependencies = {
|
||||
requireActiveEditorial: typeof requireActiveEditorial;
|
||||
repository: typeof downloadDeliveryRepository;
|
||||
immich: { getOriginal(assetId: string, signal?: AbortSignal): Promise<ImmichBinary> };
|
||||
};
|
||||
|
||||
export function createDownloadFileHandler(dependencies: DownloadFileHandlerDependencies) {
|
||||
return async function GET(
|
||||
request: Request,
|
||||
context: DownloadFileRouteContext,
|
||||
): Promise<Response> {
|
||||
try {
|
||||
const principal = await dependencies.requireActiveEditorial(request.headers);
|
||||
const downloadId = safeDownloadId((await context.params).downloadId);
|
||||
if (!downloadId) return genericNotFound();
|
||||
|
||||
const claim = await dependencies.repository.claimAuthorized(
|
||||
principal.editorialId,
|
||||
downloadId,
|
||||
);
|
||||
if (claim.outcome === "not_found") return genericNotFound();
|
||||
if (claim.outcome === "not_authorized") {
|
||||
return jsonError(409, "DOWNLOAD_NOT_AVAILABLE");
|
||||
}
|
||||
|
||||
let original: ImmichBinary;
|
||||
try {
|
||||
original = await dependencies.immich.getOriginal(
|
||||
claim.download.assetId,
|
||||
request.signal,
|
||||
);
|
||||
} catch {
|
||||
await failClaimBeforeDelivery(dependencies, downloadId, claim.download.intentKind);
|
||||
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
|
||||
}
|
||||
|
||||
try {
|
||||
const body = streamWithAccounting({
|
||||
downloadId,
|
||||
upstream: original.body,
|
||||
voidNewUsageOnFailure: claim.download.intentKind === "new_usage",
|
||||
repository: dependencies.repository,
|
||||
});
|
||||
return new Response(body, {
|
||||
headers: downloadHeaders(original, claim.download.filename),
|
||||
});
|
||||
} catch {
|
||||
const cancellation = Promise.resolve().then(() => original.body.cancel());
|
||||
await Promise.allSettled([
|
||||
cancellation,
|
||||
failClaimBeforeDelivery(dependencies, downloadId, claim.download.intentKind),
|
||||
]);
|
||||
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof PrincipalAuthorizationError) {
|
||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||
}
|
||||
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function failClaimBeforeDelivery(
|
||||
dependencies: DownloadFileHandlerDependencies,
|
||||
downloadId: string,
|
||||
intentKind: "new_usage" | "repeat_download" | "legacy",
|
||||
) {
|
||||
await dependencies.repository
|
||||
.failBeforeDelivery(downloadId, { voidNewUsage: intentKind === "new_usage" })
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
function safeDownloadId(value: string): string | null {
|
||||
try {
|
||||
return normalizeUuid(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function downloadHeaders(original: ImmichBinary, snapshotFilename: string): Headers {
|
||||
const headers = new Headers({
|
||||
"cache-control": "private, no-store",
|
||||
"content-disposition": contentDisposition(original.filename || snapshotFilename),
|
||||
"content-type": safeContentType(original.contentType),
|
||||
"x-content-type-options": "nosniff",
|
||||
});
|
||||
if (
|
||||
original.contentLength !== null &&
|
||||
Number.isSafeInteger(original.contentLength) &&
|
||||
original.contentLength >= 0
|
||||
) {
|
||||
headers.set("content-length", String(original.contentLength));
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
export function contentDisposition(filename: string): string {
|
||||
const cleaned = cleanFilename(filename);
|
||||
const fallback = asciiFilename(cleaned);
|
||||
const encoded = encodeURIComponent(cleaned).replace(/[!'()*]/g, (character) =>
|
||||
`%${character.charCodeAt(0).toString(16).toUpperCase()}`,
|
||||
);
|
||||
return `attachment; filename="${fallback}"; filename*=UTF-8''${encoded}`;
|
||||
}
|
||||
|
||||
function cleanFilename(filename: string): string {
|
||||
const cleaned = [...filename.normalize("NFC").replace(/[\uD800-\uDFFF]/gu, "_")]
|
||||
.slice(0, 180)
|
||||
.join("")
|
||||
.replace(/[\\/]/g, "_")
|
||||
.replace(/[\u0000-\u001f\u007f-\u009f]/g, "")
|
||||
.trim();
|
||||
return cleaned && cleaned !== "." && cleaned !== ".." ? cleaned : "download";
|
||||
}
|
||||
|
||||
function asciiFilename(filename: string): string {
|
||||
const fallback = filename
|
||||
.normalize("NFKD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.replace(/[^A-Za-z0-9._ ()+-]/g, "_")
|
||||
.replace(/[";]/g, "_")
|
||||
.trim();
|
||||
return fallback && fallback !== "." && fallback !== ".." ? fallback : "download";
|
||||
}
|
||||
|
||||
function safeContentType(value: string): string {
|
||||
return /^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+(?:[ \t]*;[ \t]*[A-Za-z0-9!#$&^_.+-]+=[A-Za-z0-9!#$&^_.+"'()-]+)*$/.test(
|
||||
value,
|
||||
)
|
||||
? value
|
||||
: "application/octet-stream";
|
||||
}
|
||||
|
||||
function genericNotFound(): Response {
|
||||
return new Response(null, {
|
||||
status: 404,
|
||||
headers: { "cache-control": "private, no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
function jsonError(status: number, code: string): Response {
|
||||
return Response.json(
|
||||
{ code },
|
||||
{ status, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
}
|
||||
|
||||
export const authorizedDownloadFileHandler = createDownloadFileHandler({
|
||||
requireActiveEditorial,
|
||||
repository: downloadDeliveryRepository,
|
||||
immich: immichClient,
|
||||
});
|
||||
@@ -0,0 +1,228 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { contentDisposition, createDownloadFileHandler } from "./download-handler";
|
||||
|
||||
const editorialId = "11111111-1111-4111-8111-111111111111";
|
||||
const otherEditorialId = "22222222-2222-4222-8222-222222222222";
|
||||
const downloadId = "33333333-3333-4333-8333-333333333333";
|
||||
const usageId = "44444444-4444-4444-8444-444444444444";
|
||||
const assetId = "55555555-5555-4555-8555-555555555555";
|
||||
|
||||
function binary(overrides: Partial<{
|
||||
body: ReadableStream<Uint8Array>;
|
||||
contentType: string;
|
||||
contentLength: number | null;
|
||||
filename: string;
|
||||
}> = {}) {
|
||||
return {
|
||||
body: new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array([1, 2, 3]));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
contentType: "image/jpeg",
|
||||
contentLength: 3,
|
||||
filename: "heimspiel.jpg",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function dependencies(options: {
|
||||
claim?: "claimed" | "not_found" | "not_authorized";
|
||||
editorialError?: Error;
|
||||
original?: ReturnType<typeof binary>;
|
||||
originalError?: Error;
|
||||
intentKind?: "new_usage" | "repeat_download";
|
||||
} = {}) {
|
||||
const repository = {
|
||||
claimAuthorized: vi.fn().mockResolvedValue(
|
||||
options.claim === "not_found"
|
||||
? { outcome: "not_found" }
|
||||
: options.claim === "not_authorized"
|
||||
? { outcome: "not_authorized" }
|
||||
: {
|
||||
outcome: "claimed",
|
||||
download: {
|
||||
id: downloadId,
|
||||
usageId,
|
||||
assetId,
|
||||
filename: "snapshot.jpg",
|
||||
intentKind: options.intentKind ?? "new_usage",
|
||||
},
|
||||
},
|
||||
),
|
||||
failBeforeDelivery: vi.fn().mockResolvedValue(true),
|
||||
markCompleted: vi.fn().mockResolvedValue(true),
|
||||
markInterrupted: vi.fn().mockResolvedValue(true),
|
||||
};
|
||||
const values = {
|
||||
requireActiveEditorial: vi.fn().mockImplementation(async () => {
|
||||
if (options.editorialError) throw options.editorialError;
|
||||
return { editorialId };
|
||||
}),
|
||||
repository,
|
||||
immich: {
|
||||
getOriginal: vi.fn().mockImplementation(async () => {
|
||||
if (options.originalError) throw options.originalError;
|
||||
return options.original ?? binary();
|
||||
}),
|
||||
},
|
||||
};
|
||||
return values;
|
||||
}
|
||||
|
||||
function call(
|
||||
handler: ReturnType<typeof createDownloadFileHandler>,
|
||||
id = downloadId,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
return handler(new Request(`http://portal.test/api/downloads/${id}/file`, { signal }), {
|
||||
params: Promise.resolve({ downloadId: id }),
|
||||
});
|
||||
}
|
||||
|
||||
test("claims an owned authorized event before requesting and streaming the original", async () => {
|
||||
const deps = dependencies();
|
||||
const handler = createDownloadFileHandler(deps);
|
||||
|
||||
const response = await call(handler);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(deps.repository.claimAuthorized).toHaveBeenCalledWith(editorialId, downloadId);
|
||||
expect(deps.immich.getOriginal).toHaveBeenCalledWith(assetId, expect.any(AbortSignal));
|
||||
expect(await response.arrayBuffer()).toEqual(new Uint8Array([1, 2, 3]).buffer);
|
||||
expect(deps.repository.markCompleted).toHaveBeenCalledWith(downloadId, 3);
|
||||
});
|
||||
|
||||
test("returns the same generic 404 for an invalid id, missing event, and another editorial's event", async () => {
|
||||
const invalid = dependencies();
|
||||
const missing = dependencies({ claim: "not_found" });
|
||||
const foreign = dependencies({ claim: "not_found" });
|
||||
foreign.requireActiveEditorial.mockResolvedValue({ editorialId: otherEditorialId });
|
||||
|
||||
const responses = await Promise.all([
|
||||
call(createDownloadFileHandler(invalid), "not-a-uuid"),
|
||||
call(createDownloadFileHandler(missing)),
|
||||
call(createDownloadFileHandler(foreign)),
|
||||
]);
|
||||
const results = await Promise.all(
|
||||
responses.map(async (response) => ({ status: response.status, body: await response.text() })),
|
||||
);
|
||||
|
||||
expect(results[1]).toEqual(results[0]);
|
||||
expect(results[2]).toEqual(results[0]);
|
||||
expect(invalid.repository.claimAuthorized).not.toHaveBeenCalled();
|
||||
expect(foreign.immich.getOriginal).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test.each(["streaming", "completed", "interrupted", "failed_before_delivery"])(
|
||||
"denies reuse of a %s attempt before reaching Immich",
|
||||
async () => {
|
||||
const deps = dependencies({ claim: "not_authorized" });
|
||||
const response = await call(createDownloadFileHandler(deps));
|
||||
|
||||
expect(response.status).toBe(409);
|
||||
await expect(response.json()).resolves.toEqual({ code: "DOWNLOAD_NOT_AVAILABLE" });
|
||||
expect(deps.immich.getOriginal).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
test("marks a pre-response Immich failure failed and voids a new usage", async () => {
|
||||
const deps = dependencies({ originalError: new Error("IMMICH_UNAVAILABLE") });
|
||||
|
||||
const response = await call(createDownloadFileHandler(deps));
|
||||
|
||||
expect(response.status).toBe(503);
|
||||
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||
voidNewUsage: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("a repeat pre-response failure retains the original usage", async () => {
|
||||
const deps = dependencies({
|
||||
originalError: new Error("IMMICH_UNAVAILABLE"),
|
||||
intentKind: "repeat_download",
|
||||
});
|
||||
|
||||
await call(createDownloadFileHandler(deps));
|
||||
|
||||
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||
voidNewUsage: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("accounts for a claimed attempt when the upstream body cannot be consumed", async () => {
|
||||
const original = binary();
|
||||
const lock = original.body.getReader();
|
||||
const deps = dependencies({ original });
|
||||
|
||||
const response = await call(createDownloadFileHandler(deps));
|
||||
|
||||
expect(response.status).toBe(503);
|
||||
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||
voidNewUsage: true,
|
||||
});
|
||||
lock.releaseLock();
|
||||
});
|
||||
|
||||
test("emits only safe download headers for an injected Unicode filename", async () => {
|
||||
const deps = dependencies({
|
||||
original: binary({
|
||||
filename: "../München\r\nX-Internal: secret\\final.jpg",
|
||||
contentType: "image/jpeg",
|
||||
contentLength: 3,
|
||||
}),
|
||||
});
|
||||
|
||||
const response = await call(createDownloadFileHandler(deps));
|
||||
const disposition = response.headers.get("content-disposition") ?? "";
|
||||
|
||||
expect(response.headers.get("cache-control")).toBe("private, no-store");
|
||||
expect(response.headers.get("content-type")).toBe("image/jpeg");
|
||||
expect(response.headers.get("content-length")).toBe("3");
|
||||
expect(response.headers.has("x-api-key")).toBe(false);
|
||||
expect(disposition).not.toMatch(/[\r\n\\/]/);
|
||||
expect(disposition).toContain("filename*=UTF-8''");
|
||||
expect(disposition).toContain("M%C3%BCnchen");
|
||||
});
|
||||
|
||||
test("falls back from an untrustworthy media type and length without forwarding header injection", async () => {
|
||||
const deps = dependencies({
|
||||
original: binary({
|
||||
contentType: "image/jpeg;\r\nx-api-key=secret",
|
||||
contentLength: -1,
|
||||
}),
|
||||
});
|
||||
|
||||
const response = await call(createDownloadFileHandler(deps));
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("content-type")).toBe("application/octet-stream");
|
||||
expect(response.headers.has("content-length")).toBe(false);
|
||||
expect(response.headers.has("x-api-key")).toBe(false);
|
||||
});
|
||||
|
||||
test("builds a standards-safe disposition for malformed Unicode", () => {
|
||||
expect(() => contentDisposition("foto-\ud800.jpg")).not.toThrow();
|
||||
expect(contentDisposition("foto-\ud800.jpg")).toContain("filename*=UTF-8''foto-_.jpg");
|
||||
});
|
||||
|
||||
test("returns stable authentication semantics without exposing guard details", async () => {
|
||||
const unauthenticated = dependencies({
|
||||
editorialError: new PrincipalAuthorizationError("AUTHENTICATION_REQUIRED"),
|
||||
});
|
||||
const inactive = dependencies({
|
||||
editorialError: new PrincipalAuthorizationError("ACCOUNT_SUSPENDED"),
|
||||
});
|
||||
|
||||
const [first, second] = await Promise.all([
|
||||
call(createDownloadFileHandler(unauthenticated)),
|
||||
call(createDownloadFileHandler(inactive)),
|
||||
]);
|
||||
|
||||
expect(first.status).toBe(401);
|
||||
expect(second.status).toBe(403);
|
||||
expect(await second.text()).not.toContain("SUSPENDED");
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
import { authorizedDownloadFileHandler } from "./download-handler";
|
||||
|
||||
export const GET = authorizedDownloadFileHandler;
|
||||
@@ -621,3 +621,308 @@ a {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
.download-trigger {
|
||||
width: 100%;
|
||||
min-height: 2.45rem;
|
||||
border: 0;
|
||||
border-top: 1px solid var(--ink);
|
||||
border-radius: 0;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 750;
|
||||
letter-spacing: 0.07em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.download-trigger:hover {
|
||||
background: var(--ink);
|
||||
color: var(--paper);
|
||||
}
|
||||
|
||||
.usage-dialog {
|
||||
width: min(calc(100% - 2rem), 46rem);
|
||||
max-height: calc(100vh - 2rem);
|
||||
padding: 0;
|
||||
border: 1px solid var(--ink);
|
||||
border-radius: 0;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.usage-dialog::backdrop {
|
||||
background: rgb(0 0 0 / 70%);
|
||||
}
|
||||
|
||||
.usage-dialog form {
|
||||
display: grid;
|
||||
gap: 1.5rem;
|
||||
padding: clamp(1.25rem, 4vw, 2.5rem);
|
||||
}
|
||||
|
||||
.usage-dialog-heading {
|
||||
padding-bottom: 1.25rem;
|
||||
border-bottom: 1px solid var(--ink);
|
||||
}
|
||||
|
||||
.usage-dialog-heading h2 {
|
||||
margin: 0;
|
||||
font-size: clamp(2rem, 6vw, 4rem);
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.055em;
|
||||
line-height: 0.95;
|
||||
}
|
||||
|
||||
.usage-dialog-heading > p:last-child {
|
||||
max-width: 38rem;
|
||||
margin: 1rem 0 0;
|
||||
color: var(--graphite);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.usage-options {
|
||||
display: grid;
|
||||
gap: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.usage-options legend,
|
||||
.usage-purpose {
|
||||
margin-bottom: 0.6rem;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 750;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.usage-option {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 0.9rem;
|
||||
padding: 0.9rem 0;
|
||||
border-top: 1px solid var(--line);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.usage-option:last-child {
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.usage-option input {
|
||||
width: 1.05rem;
|
||||
height: 1.05rem;
|
||||
accent-color: var(--ink);
|
||||
}
|
||||
|
||||
.usage-option span {
|
||||
display: grid;
|
||||
gap: 0.2rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.usage-option strong,
|
||||
.usage-option b {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.usage-option small {
|
||||
overflow: hidden;
|
||||
color: var(--metadata);
|
||||
font-size: 0.7rem;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.usage-purpose {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.usage-purpose textarea {
|
||||
width: 100%;
|
||||
resize: vertical;
|
||||
border: 1px solid var(--ink);
|
||||
border-radius: 0;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
font: inherit;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.usage-purpose textarea:disabled {
|
||||
border-color: var(--line);
|
||||
background: var(--soft);
|
||||
}
|
||||
|
||||
.usage-dialog [role="alert"] {
|
||||
margin: 0;
|
||||
color: #8d1010;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.usage-dialog-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.usage-dialog-actions button {
|
||||
min-height: 2.8rem;
|
||||
border: 1px solid var(--ink);
|
||||
border-radius: 0;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
padding-inline: 1rem;
|
||||
}
|
||||
|
||||
.usage-dialog-actions .download-confirm {
|
||||
background: var(--ink);
|
||||
color: var(--paper);
|
||||
}
|
||||
|
||||
.usage-dialog-actions button:disabled {
|
||||
cursor: wait;
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.usage-history-empty {
|
||||
max-width: 38rem;
|
||||
}
|
||||
|
||||
.usage-history-empty p {
|
||||
color: var(--graphite);
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.usage-ledger,
|
||||
.usage-attempts {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.usage-ledger {
|
||||
display: grid;
|
||||
gap: 2.5rem;
|
||||
}
|
||||
|
||||
.usage-ledger-entry {
|
||||
border-top: 2px solid var(--ink);
|
||||
}
|
||||
|
||||
.usage-ledger-entry > header {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 0.8rem 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.usage-ledger-entry > header p {
|
||||
margin: 0;
|
||||
color: var(--metadata);
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
font-size: 0.65rem;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.usage-ledger-entry h2 {
|
||||
overflow-wrap: anywhere;
|
||||
margin: 0;
|
||||
font-size: clamp(1.35rem, 3vw, 2.25rem);
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.035em;
|
||||
}
|
||||
|
||||
.usage-snapshot {
|
||||
display: grid !important;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr)) !important;
|
||||
gap: 1rem !important;
|
||||
max-width: none !important;
|
||||
margin: 0 !important;
|
||||
padding: 1rem 0 !important;
|
||||
border-top: 0 !important;
|
||||
}
|
||||
|
||||
.usage-snapshot div {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.usage-snapshot dd {
|
||||
overflow-wrap: anywhere;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
.usage-attempts {
|
||||
border-top: 1px solid var(--ink);
|
||||
}
|
||||
|
||||
.usage-attempts li {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(9rem, 1.2fr) minmax(11rem, 1.5fr) minmax(8rem, 1fr) 0.7fr 0.7fr;
|
||||
gap: 1rem;
|
||||
align-items: baseline;
|
||||
padding: 0.7rem 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.usage-attempts time,
|
||||
.usage-attempts span {
|
||||
color: var(--metadata);
|
||||
}
|
||||
|
||||
.usage-attempts b {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.usage-attempt-empty {
|
||||
margin: 0;
|
||||
padding: 1rem 0;
|
||||
border-top: 1px solid var(--line);
|
||||
color: var(--metadata);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
@media (max-width: 52rem) {
|
||||
.usage-snapshot {
|
||||
grid-template-columns: 1fr !important;
|
||||
}
|
||||
|
||||
.usage-attempts li {
|
||||
grid-template-columns: 1fr auto;
|
||||
}
|
||||
|
||||
.usage-attempts li > :nth-child(3),
|
||||
.usage-attempts li > :nth-child(4) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 40rem) {
|
||||
.usage-dialog-actions {
|
||||
flex-direction: column-reverse;
|
||||
}
|
||||
|
||||
.usage-dialog-actions button {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.usage-ledger-entry > header {
|
||||
align-items: flex-start;
|
||||
flex-direction: column-reverse;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { notFound } from "next/navigation";
|
||||
|
||||
import { AlbumCatalogError, albumCatalog } from "@/modules/albums/catalog";
|
||||
import { PhotoContactSheet } from "@/modules/albums/catalog-content";
|
||||
import { loadEditorialDownloadOptions } from "@/modules/downloads/stream";
|
||||
|
||||
import { requireEditorial } from "../../access";
|
||||
|
||||
@@ -44,6 +45,7 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
|
||||
<PhotoContactSheet
|
||||
albumId={result.album.id}
|
||||
albumName={result.album.albumName}
|
||||
downloadOptions={result.downloadOptions}
|
||||
page={result.page}
|
||||
query={query}
|
||||
/>
|
||||
@@ -73,7 +75,11 @@ async function loadAlbumPage({
|
||||
description: query,
|
||||
page,
|
||||
});
|
||||
return { album, page: results, unavailable: false as const };
|
||||
const downloadOptions = await loadEditorialDownloadOptions(
|
||||
editorialId,
|
||||
results.items.map((asset) => asset.id),
|
||||
);
|
||||
return { album, page: results, downloadOptions, unavailable: false as const };
|
||||
} catch (error) {
|
||||
if (error instanceof AlbumCatalogError && error.code === "IMMICH_UNAVAILABLE") {
|
||||
return { album: null, page: null, unavailable: true as const };
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
|
||||
import { UsageHistoryContent } from "./usage-history-content";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
test("renders every terminal attempt with its immutable usage snapshot", () => {
|
||||
render(
|
||||
<UsageHistoryContent
|
||||
history={{
|
||||
items: [
|
||||
{
|
||||
usageId: "usage-1",
|
||||
filename: "tor-des-monats.jpg",
|
||||
albumName: "Heimspiel gegen Nord",
|
||||
purpose: "Titelgeschichte",
|
||||
reference: "Ausgabe 8/26",
|
||||
createdAt: new Date("2026-08-09T10:00:00.000Z"),
|
||||
billingStatus: "open",
|
||||
billableCents: 1_500,
|
||||
attempts: [
|
||||
{
|
||||
downloadId: "download-3",
|
||||
status: "failed_before_delivery",
|
||||
requestedAt: new Date("2026-08-10T12:00:00.000Z"),
|
||||
finishedAt: new Date("2026-08-10T12:00:01.000Z"),
|
||||
transferredBytes: 0,
|
||||
repeat: true,
|
||||
billableCents: 0,
|
||||
},
|
||||
{
|
||||
downloadId: "download-2",
|
||||
status: "interrupted",
|
||||
requestedAt: new Date("2026-08-10T11:00:00.000Z"),
|
||||
finishedAt: new Date("2026-08-10T11:00:02.000Z"),
|
||||
transferredBytes: 40,
|
||||
repeat: true,
|
||||
billableCents: 0,
|
||||
},
|
||||
{
|
||||
downloadId: "download-1",
|
||||
status: "completed",
|
||||
requestedAt: new Date("2026-08-09T10:00:00.000Z"),
|
||||
finishedAt: new Date("2026-08-09T10:00:03.000Z"),
|
||||
transferredBytes: 100,
|
||||
repeat: false,
|
||||
billableCents: 1_500,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
hasNext: true,
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("heading", { name: /tor-des-monats\.jpg/i })).not.toBeNull();
|
||||
expect(screen.getByText("Heimspiel gegen Nord")).not.toBeNull();
|
||||
expect(screen.getByText("Titelgeschichte")).not.toBeNull();
|
||||
expect(screen.getByText("Abgeschlossen")).not.toBeNull();
|
||||
expect(screen.getByText("Unterbrochen")).not.toBeNull();
|
||||
expect(screen.getByText("Vor Auslieferung fehlgeschlagen")).not.toBeNull();
|
||||
expect(screen.getByText(/15,00\s*€/)).not.toBeNull();
|
||||
expect(screen.getAllByText(/0,00\s*€/)).toHaveLength(2);
|
||||
expect(screen.getByRole("link", { name: /nächste seite/i }).getAttribute("href")).toBe(
|
||||
"/redaktion/nutzungen?page=2",
|
||||
);
|
||||
});
|
||||
|
||||
test("renders a directional empty state", () => {
|
||||
render(
|
||||
<UsageHistoryContent
|
||||
history={{ items: [], page: 1, pageSize: 20, hasNext: false }}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByText(/noch keine nutzungen/i)).not.toBeNull();
|
||||
expect(screen.getByRole("link", { name: /zu den alben/i })).not.toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { listEditorialUsageHistory } from "@/modules/downloads/stream";
|
||||
|
||||
import { requireEditorial } from "../access";
|
||||
import { UsageHistoryContent } from "./usage-history-content";
|
||||
|
||||
type UsageHistoryPageProps = Readonly<{
|
||||
searchParams: Promise<{ page?: string | string[] }>;
|
||||
}>;
|
||||
|
||||
export default async function UsagesPage({ searchParams }: UsageHistoryPageProps) {
|
||||
const [principal, parameters] = await Promise.all([requireEditorial(), searchParams]);
|
||||
const result = await loadHistory(principal.editorialId, singleValue(parameters.page));
|
||||
if (result.unavailable) return <HistoryUnavailable />;
|
||||
return <UsageHistoryContent history={result.history} />;
|
||||
}
|
||||
|
||||
async function loadHistory(editorialId: string, page: string | undefined) {
|
||||
try {
|
||||
return {
|
||||
history: await listEditorialUsageHistory(editorialId, page),
|
||||
unavailable: false as const,
|
||||
};
|
||||
} catch {
|
||||
return { history: null, unavailable: true as const };
|
||||
}
|
||||
}
|
||||
|
||||
function HistoryUnavailable() {
|
||||
return (
|
||||
<section className="editorial-section editorial-state" aria-labelledby="usage-history-title">
|
||||
<p className="editorial-kicker">Abrechnung</p>
|
||||
<h1 id="usage-history-title">Nutzungen momentan nicht erreichbar</h1>
|
||||
<p role="status">Bitte laden Sie diese Seite in wenigen Minuten erneut.</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function singleValue(value: string | string[] | undefined): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import type { UsageHistoryAttempt, UsageHistoryPage } from "@/modules/downloads/stream";
|
||||
|
||||
const dateTimeFormatter = new Intl.DateTimeFormat("de-DE", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
});
|
||||
const priceFormatter = new Intl.NumberFormat("de-DE", {
|
||||
style: "currency",
|
||||
currency: "EUR",
|
||||
});
|
||||
const byteFormatter = new Intl.NumberFormat("de-DE", {
|
||||
style: "unit",
|
||||
unit: "byte",
|
||||
unitDisplay: "short",
|
||||
maximumFractionDigits: 0,
|
||||
});
|
||||
|
||||
export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistoryPage }>) {
|
||||
return (
|
||||
<section className="editorial-section usage-history" aria-labelledby="usage-history-title">
|
||||
<p className="editorial-kicker">Abrechnung · Downloadprotokoll</p>
|
||||
<div className="editorial-title-row">
|
||||
<h1 id="usage-history-title">Ihre Nutzungen</h1>
|
||||
<p>Verwendungszwecke, Kosten und Auslieferungsversuche Ihrer Redaktion.</p>
|
||||
</div>
|
||||
|
||||
{history.items.length === 0 ? (
|
||||
<div className="usage-history-empty">
|
||||
<p>Noch keine Nutzungen erfasst. Wählen Sie ein Foto aus einem freigegebenen Album.</p>
|
||||
<Link className="quiet-link" href="/redaktion/alben">
|
||||
Zu den Alben
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<ol className="usage-ledger">
|
||||
{history.items.map((usage) => (
|
||||
<li key={usage.usageId}>
|
||||
<article className="usage-ledger-entry">
|
||||
<header>
|
||||
<p>{formatDateTime(usage.createdAt)}</p>
|
||||
<h2>{usage.filename}</h2>
|
||||
</header>
|
||||
<dl className="usage-snapshot">
|
||||
<div>
|
||||
<dt>Album</dt>
|
||||
<dd>{usage.albumName}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Verwendungszweck</dt>
|
||||
<dd>{usage.purpose}</dd>
|
||||
</div>
|
||||
{usage.reference ? (
|
||||
<div>
|
||||
<dt>Interne Referenz</dt>
|
||||
<dd>{usage.reference}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
</dl>
|
||||
{usage.attempts.length === 0 ? (
|
||||
<p className="usage-attempt-empty">Noch kein abgeschlossener Auslieferungsversuch.</p>
|
||||
) : (
|
||||
<ol className="usage-attempts" aria-label={`Auslieferungen für ${usage.filename}`}>
|
||||
{usage.attempts.map((attempt) => (
|
||||
<AttemptRow attempt={attempt} key={attempt.downloadId} />
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
</article>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
|
||||
<HistoryPagination history={history} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) {
|
||||
return (
|
||||
<li>
|
||||
<time dateTime={attempt.finishedAt.toISOString()}>{formatDateTime(attempt.finishedAt)}</time>
|
||||
<strong>{statusLabel(attempt.status)}</strong>
|
||||
<span>{attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"}</span>
|
||||
<span>{byteFormatter.format(attempt.transferredBytes)}</span>
|
||||
<b>{priceFormatter.format(attempt.billableCents / 100)}</b>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function HistoryPagination({ history }: Readonly<{ history: UsageHistoryPage }>) {
|
||||
if (history.page === 1 && !history.hasNext) return null;
|
||||
return (
|
||||
<nav aria-label="Seiten der Nutzungshistorie" className="photo-pagination">
|
||||
{history.page > 1 ? (
|
||||
<Link href={`/redaktion/nutzungen?page=${history.page - 1}`}>Vorherige Seite</Link>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
{history.hasNext ? (
|
||||
<Link href={`/redaktion/nutzungen?page=${history.page + 1}`}>Nächste Seite</Link>
|
||||
) : null}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
function statusLabel(status: UsageHistoryAttempt["status"]): string {
|
||||
const labels: Record<UsageHistoryAttempt["status"], string> = {
|
||||
completed: "Abgeschlossen",
|
||||
interrupted: "Unterbrochen",
|
||||
failed_before_delivery: "Vor Auslieferung fehlgeschlagen",
|
||||
};
|
||||
return labels[status];
|
||||
}
|
||||
|
||||
function formatDateTime(value: Date): string {
|
||||
return dateTimeFormatter.format(value);
|
||||
}
|
||||
Reference in new issue
Block a user