feat: stream originals with download accounting

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 13:10:13 +02:00
1 parent c400167b8f
commit 8871e4794a
28 files changed
+4081 -8

No files matched your search

+224
View File
@@ -0,0 +1,224 @@
"use client";
import { useRef, useState, type FormEvent } from "react";
import type { DownloadDialogUsage } from "@/modules/downloads/stream";
type UsageDialogProps = Readonly<{
albumId: string;
assetId: string;
filename: string;
newUsagePriceCents: number;
priorUsages: DownloadDialogUsage[];
}>;
type IntentResponse = {
downloadId: string;
fileUrl: string;
priceCents: number;
billable: boolean;
};
const priceFormatter = new Intl.NumberFormat("de-DE", {
style: "currency",
currency: "EUR",
});
const dateFormatter = new Intl.DateTimeFormat("de-DE", {
dateStyle: "medium",
});
export function UsageDialog({
albumId,
assetId,
filename,
newUsagePriceCents,
priorUsages,
}: UsageDialogProps) {
const dialogRef = useRef<HTMLDialogElement>(null);
const firstChoiceRef = useRef<HTMLInputElement>(null);
const idempotencyKeyRef = useRef<string | null>(null);
const initialChoice = priorUsages[0] ? `repeat:${priorUsages[0].id}` : "new_usage";
const [choice, setChoice] = useState(initialChoice);
const [purpose, setPurpose] = useState("");
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
function openDialog() {
setChoice(initialChoice);
setPurpose("");
setPending(false);
setError(null);
idempotencyKeyRef.current = null;
dialogRef.current?.showModal();
requestAnimationFrame(() => firstChoiceRef.current?.focus());
}
function closeDialog() {
if (!pending) dialogRef.current?.close();
}
function resetSubmission() {
idempotencyKeyRef.current = null;
setError(null);
}
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (pending) return;
setPending(true);
setError(null);
idempotencyKeyRef.current ??= crypto.randomUUID();
const payload = choice.startsWith("repeat:")
? {
kind: "repeat_download" as const,
usageId: choice.slice("repeat:".length),
idempotencyKey: idempotencyKeyRef.current,
}
: {
kind: "new_usage" as const,
assetId,
albumId,
purpose,
idempotencyKey: idempotencyKeyRef.current,
};
try {
const response = await fetch("/api/download-intents", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(payload),
});
if (!response.ok) throw new Error("intent failed");
const intent = (await response.json()) as IntentResponse;
if (!isLocalDownloadUrl(intent.fileUrl, intent.downloadId)) {
throw new Error("invalid download url");
}
const link = document.createElement("a");
link.href = intent.fileUrl;
link.download = filename;
link.click();
dialogRef.current?.close();
idempotencyKeyRef.current = null;
} catch {
setError(
"Der Download konnte nicht vorbereitet werden. Versuchen Sie dieselbe Anfrage erneut.",
);
} finally {
setPending(false);
}
}
const isNewUsage = choice === "new_usage";
return (
<>
<button className="download-trigger" onClick={openDialog} type="button">
Original laden
</button>
<dialog
aria-labelledby={`usage-dialog-title-${assetId}`}
className="usage-dialog"
onCancel={(event) => {
if (pending) event.preventDefault();
}}
onClose={() => {
setError(null);
idempotencyKeyRef.current = null;
}}
ref={dialogRef}
>
<form onSubmit={submit}>
<div className="usage-dialog-heading">
<p className="editorial-kicker">Download · {filename}</p>
<h2 id={`usage-dialog-title-${assetId}`}>Nutzung auswählen</h2>
<p>Ordnen Sie das Original einer bestehenden oder einer neuen Nutzung zu.</p>
</div>
<fieldset className="usage-options" disabled={pending}>
<legend>Abrechnung</legend>
{priorUsages.map((usage, index) => (
<label className="usage-option" key={usage.id}>
<input
checked={choice === `repeat:${usage.id}`}
name={`usage-${assetId}`}
onChange={() => {
setChoice(`repeat:${usage.id}`);
resetSubmission();
}}
ref={index === 0 ? firstChoiceRef : undefined}
type="radio"
value={`repeat:${usage.id}`}
/>
<span>
<strong>{usage.purpose}</strong>
<small>Bestehende Nutzung · {formatDate(usage.createdAt)}</small>
</span>
<b>{priceFormatter.format(0)}</b>
</label>
))}
<label className="usage-option">
<input
checked={isNewUsage}
name={`usage-${assetId}`}
onChange={() => {
setChoice("new_usage");
resetSubmission();
}}
ref={priorUsages.length === 0 ? firstChoiceRef : undefined}
type="radio"
value="new_usage"
/>
<span>
<strong>Neue Nutzung</strong>
<small>Neue Veröffentlichung oder neuer Verwendungszweck</small>
</span>
<b>{priceFormatter.format(newUsagePriceCents / 100)}</b>
</label>
</fieldset>
<label className="usage-purpose" htmlFor={`usage-purpose-${assetId}`}>
Verwendungszweck
<textarea
disabled={!isNewUsage || pending}
id={`usage-purpose-${assetId}`}
maxLength={200}
minLength={3}
onChange={(event) => {
setPurpose(event.target.value);
resetSubmission();
}}
required={isNewUsage}
rows={3}
value={purpose}
/>
</label>
{error ? <p role="alert">{error}</p> : null}
<div className="usage-dialog-actions">
<button disabled={pending} onClick={closeDialog} type="button">
Abbrechen
</button>
<button className="download-confirm" disabled={pending} type="submit">
{pending
? "Download wird vorbereitet …"
: error
? "Download erneut anfordern"
: "Download anfordern"}
</button>
</div>
</form>
</dialog>
</>
);
}
function formatDate(value: string): string {
const date = new Date(value);
return Number.isNaN(date.valueOf()) ? "Datum unbekannt" : dateFormatter.format(date);
}
function isLocalDownloadUrl(fileUrl: string, downloadId: string): boolean {
return fileUrl === `/api/downloads/${encodeURIComponent(downloadId)}/file`;
}