Secure Sakani portal and show full album titles
This commit is contained in:
1 parent
c40ccf77cf
commit
69264ce165
49 files changed
+1362
-601
No files matched your search
@@ -1,103 +1,189 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef } from "react";
|
||||
import { useRef, useState, type FormEvent } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Alert, Button, Input } from "@sakaniui/react";
|
||||
import { IconDownload } from "@sakaniui/react/icons";
|
||||
|
||||
export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) {
|
||||
import { formatBerlinDate } from "@/modules/downloads/format";
|
||||
import type { EditorialDownloadOptions } from "@/modules/downloads/stream";
|
||||
|
||||
type Photo = { assetId: string; albumId: string; filename: string };
|
||||
type Choice = { selection: string; purpose?: string };
|
||||
|
||||
const priceFormatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
|
||||
|
||||
export function DownloadLightboxForm({
|
||||
photos,
|
||||
options,
|
||||
}: {
|
||||
photos: Photo[];
|
||||
options: EditorialDownloadOptions;
|
||||
}) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const [purpose, setPurpose] = useState("");
|
||||
const [choices, setChoices] = useState<Record<string, Choice>>({});
|
||||
const [commonPurpose, setCommonPurpose] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const inFlight = useRef(false);
|
||||
const intentKeys = useRef(new Map<string, string>());
|
||||
const router = useRouter();
|
||||
|
||||
async function handleBulkDownload(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!purpose.trim() || assetIds.length === 0) return;
|
||||
const selected = photos.filter(({ assetId }) => {
|
||||
const selection = choices[assetId]?.selection;
|
||||
return Boolean(selection && selection !== "skip");
|
||||
});
|
||||
const newPhotos = selected.filter(({ assetId }) => choices[assetId].selection === "new");
|
||||
const price = priceFormatter.format(options.priceCents / 100);
|
||||
const ready = selected.length > 0 && selected.length <= 100 &&
|
||||
photos.every(({ assetId }) => currentSelection(assetId)) &&
|
||||
newPhotos.every(({ assetId }) => [...purposeFor(choices[assetId])].length >= 3);
|
||||
|
||||
function currentSelection(assetId: string) {
|
||||
const selection = choices[assetId]?.selection;
|
||||
if (selection === "new" || selection === "skip") return selection;
|
||||
return options.priorUsagesByAsset[assetId]?.find(({ id }) => id === selection)?.id ?? "";
|
||||
}
|
||||
|
||||
function purposeFor(choice: Choice) {
|
||||
return choice.purpose?.trim() || commonPurpose.trim();
|
||||
}
|
||||
|
||||
async function handleBulkDownload(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!ready || inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const items = selected.map(({ assetId, albumId }) => {
|
||||
const choice = choices[assetId];
|
||||
const purpose = choice.selection === "new" ? purposeFor(choice) : undefined;
|
||||
const key = JSON.stringify([assetId, choice.selection, purpose]);
|
||||
let idempotencyKey = intentKeys.current.get(key);
|
||||
if (!idempotencyKey) {
|
||||
idempotencyKey = crypto.randomUUID();
|
||||
intentKeys.current.set(key, idempotencyKey);
|
||||
}
|
||||
return purpose
|
||||
? { assetId, albumId, purpose, idempotencyKey }
|
||||
: { assetId, usageId: choice.selection, idempotencyKey };
|
||||
});
|
||||
|
||||
const response = await fetch("/api/lightbox/bulk-download", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ assetIds, purpose }),
|
||||
body: JSON.stringify({ items, maxPriceCents: options.priceCents }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
// Surface the server's error code instead of a generic message so the
|
||||
// real cause (e.g. IMMICH_UNAVAILABLE, REQUEST_FAILED) is visible in the
|
||||
// browser console — the bulk handler maps UsageAccountingError to codes.
|
||||
let code: string | undefined;
|
||||
try {
|
||||
code = (await response.clone().json()).code;
|
||||
} catch {
|
||||
/* non-JSON body (e.g. plain 500) — code stays undefined */
|
||||
const payload = await response.json().catch(() => null);
|
||||
if (payload?.code === "INVALID_PRICE") {
|
||||
router.refresh();
|
||||
throw new Error("Der Tarif hat sich geändert. Bitte prüfen Sie den aktualisierten Preis.");
|
||||
}
|
||||
const status = response.status;
|
||||
console.error("[bulk-download] server error:", { status, code });
|
||||
throw new Error(`Download fehlgeschlagen (${status}${code ? ` ${code}` : ""})`);
|
||||
if (payload?.code === "IDEMPOTENCY_CONFLICT") {
|
||||
router.refresh();
|
||||
throw new Error("Der Downloadversuch ist bereits erfasst. Prüfen Sie Ihre Nutzungen, bevor Sie einen neuen Zweck buchen.");
|
||||
}
|
||||
throw new Error("Bitte prüfen Sie die Auswahl und versuchen Sie es erneut.");
|
||||
}
|
||||
|
||||
// Download the ZIP file
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `leuchtkasten-${new Date().toISOString().split("T")[0]}.zip`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = "leuchtkasten.zip";
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
intentKeys.current.clear();
|
||||
dialogRef.current?.close();
|
||||
setPurpose("");
|
||||
router.refresh(); // Refresh to update usage history
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Download fehlgeschlagen";
|
||||
setError(`Bulk-Download fehlgeschlagen: ${message}`);
|
||||
console.error(err);
|
||||
setChoices({});
|
||||
setCommonPurpose("");
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
setError(error instanceof Error ? error.message : "Bitte versuchen Sie es erneut.");
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
disabled={assetIds.length === 0}
|
||||
leftIcon={<IconDownload size={16} />}
|
||||
onClick={() => dialogRef.current?.showModal()}
|
||||
type="button"
|
||||
>
|
||||
Alle herunterladen
|
||||
<Button leftIcon={<IconDownload size={16} />} onClick={() => dialogRef.current?.showModal()} type="button">
|
||||
ZIP-Download vorbereiten
|
||||
</Button>
|
||||
|
||||
<dialog ref={dialogRef} aria-labelledby="bulk-download-title" className="usage-dialog max-w-md">
|
||||
<form className="flex flex-col gap-4 p-6" onSubmit={handleBulkDownload}>
|
||||
<h2 id="bulk-download-title" className="text-xl font-semibold">Verwendungszweck angeben</h2>
|
||||
<p className="text-sm text-[var(--color-fg-muted)]">
|
||||
Bitte gib einen gemeinsamen Verwendungszweck für alle {assetIds.length} Bilder an. Diese werden in einem ZIP-Archiv heruntergeladen.
|
||||
</p>
|
||||
<form className="flex flex-col gap-4 p-6" method="post" onSubmit={handleBulkDownload}>
|
||||
<h2 id="bulk-download-title" className="text-xl font-semibold">Nutzungen für ZIP-Download</h2>
|
||||
<Input
|
||||
disabled={loading}
|
||||
id="purpose"
|
||||
label="Verwendungszweck"
|
||||
onChange={(e) => setPurpose(e.target.value)}
|
||||
placeholder="z.B. Webseite, Social Media"
|
||||
required
|
||||
type="text"
|
||||
value={purpose}
|
||||
label="Gemeinsamer Zweck für neue Nutzungen"
|
||||
maxLength={200}
|
||||
onChange={(event) => setCommonPurpose(event.target.value)}
|
||||
value={commonPurpose}
|
||||
/>
|
||||
{error ? <Alert color="danger" description={error} /> : null}
|
||||
<ul className="flex flex-col gap-4">
|
||||
{photos.map(({ assetId, filename }) => {
|
||||
const choice = choices[assetId];
|
||||
return (
|
||||
<li key={assetId} className="flex flex-col gap-2">
|
||||
<label className="flex flex-col gap-1 text-sm font-medium">
|
||||
{filename}
|
||||
<select
|
||||
className="rounded-md border border-[var(--color-border-subtle)] bg-[var(--color-bg-surface)] p-2 text-[var(--color-fg-default)]"
|
||||
disabled={loading}
|
||||
onChange={(event) => {
|
||||
const selection = event.target.value;
|
||||
setChoices((previous) => ({ ...previous, [assetId]: { selection } }));
|
||||
}}
|
||||
value={currentSelection(assetId)}
|
||||
>
|
||||
<option value="">Nutzung auswählen</option>
|
||||
<option value="new">Neue Nutzung · bis {price} netto</option>
|
||||
{(options.priorUsagesByAsset[assetId] ?? []).map((usage) => (
|
||||
<option key={usage.id} value={usage.id}>
|
||||
{usage.purpose} ({formatBerlinDate(new Date(usage.createdAt))}) · kostenlos wiederholen
|
||||
</option>
|
||||
))}
|
||||
<option value="skip">Bild auslassen</option>
|
||||
</select>
|
||||
</label>
|
||||
{choice?.selection === "new" && (
|
||||
<Input
|
||||
disabled={loading}
|
||||
label={`Eigener Zweck für ${filename}`}
|
||||
maxLength={200}
|
||||
onChange={(event) => {
|
||||
const purpose = event.target.value;
|
||||
setChoices((previous) => ({ ...previous, [assetId]: { selection: "new", purpose } }));
|
||||
}}
|
||||
value={choice.purpose ?? ""}
|
||||
/>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
{newPhotos.length > 0 && (
|
||||
<p className="text-sm" role="status">
|
||||
{newPhotos.length} neue {newPhotos.length === 1 ? "Nutzung" : "Nutzungen"} · bis{" "}
|
||||
{priceFormatter.format(newPhotos.length * options.priceCents / 100)} netto.
|
||||
Ein verfügbares Flatrate-Kontingent wird beim Download angerechnet.
|
||||
</p>
|
||||
)}
|
||||
{selected.length > 100 && <Alert color="warning" description="Wählen Sie höchstens 100 Bilder pro ZIP aus." />}
|
||||
{error && <Alert color="danger" description={error} />}
|
||||
<div className="mt-4 flex justify-end gap-3">
|
||||
<Button disabled={loading} onClick={() => dialogRef.current?.close()} type="button" variant="ghost">
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button disabled={loading || !purpose.trim()} type="submit">
|
||||
{loading ? "Wird verpackt …" : "Download starten (ZIP)"}
|
||||
<Button disabled={loading || !ready} type="submit">
|
||||
{loading ? "Wird verpackt …" : newPhotos.length ? "Nutzungen bestätigen und laden" : "ZIP herunterladen"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
Reference in new issue
Block a user