feat: redesign dashboard, add lightbox bulk download, and standardize ui

This commit is contained in:
Leon Tonhäuser committed 2026-08-11 11:18:39 +02:00
1 parent 8728308fc6
commit 4a9da65901
13 files changed
+923 -104

No files matched your search

@@ -3,6 +3,17 @@ import { expect, test, vi } from "vitest";
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
import { createThumbnailHandler } from "./thumbnail-handler";
vi.mock("sharp", () => {
return {
default: () => ({
metadata: vi.fn().mockResolvedValue({ width: 100, height: 100 }),
composite: vi.fn().mockReturnThis(),
webp: vi.fn().mockReturnThis(),
toBuffer: vi.fn().mockResolvedValue(Buffer.from(new Uint8Array([1, 2, 3]))),
}),
};
});
const grantedAlbum = {
id: "allowed",
albumName: "Freigegebenes Heimspiel",
@@ -42,9 +53,15 @@ function createHandler(options?: {
requireAdmin: vi.fn().mockResolvedValue({ userId: "admin-1" }),
getGrantedAlbumIds: vi.fn().mockResolvedValue(options?.grantedAlbumIds ?? ["allowed"]),
immich: {
listAlbumsForAsset: vi.fn().mockImplementation(async () => {
getAsset: vi.fn().mockImplementation(async () => {
if (options?.assetAlbumLookupError) throw options.assetAlbumLookupError;
return (options?.assetAlbumIds ?? ["allowed"]).map((id) => ({ id }));
return {
id: "asset-1",
originalFileName: "foo.jpg",
originalMimeType: "image/jpeg",
type: "IMAGE",
albums: (options?.assetAlbumIds ?? ["allowed"]).map((id) => ({ id })),
};
}),
getAlbum: vi.fn().mockImplementation(async () => {
return {
@@ -88,7 +105,7 @@ test("refuses a thumbnail immediately after its last grant is revoked", async ()
const response = await call(handler);
expect(response.status).toBe(404);
expect(dependencies.immich.listAlbumsForAsset).not.toHaveBeenCalled();
expect(dependencies.immich.getAsset).not.toHaveBeenCalled();
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled();
});
@@ -147,8 +164,8 @@ test("uses one asset-album membership lookup for a 60-photo gallery regardless o
const response = await call(handler);
expect(response.status).toBe(200);
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledTimes(1);
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledWith("asset-1");
expect(dependencies.immich.getAsset).toHaveBeenCalledTimes(1);
expect(dependencies.immich.getAsset).toHaveBeenCalledWith("asset-1");
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
});
@@ -11,6 +11,7 @@ type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
type ThumbnailImmich = {
listAlbumsForAsset(assetId: string): Promise<Array<{ id: string }>>;
getAlbum(albumId: string): Promise<{ albumThumbnailAssetId: string | null }>;
getAsset(assetId: string): Promise<{ albums: Array<{ id: string }> }>;
getThumbnail(assetId: string): Promise<ImmichBinary>;
};
@@ -83,7 +84,8 @@ async function isGrantedEditorialAsset(
return false;
}
const assetAlbums = await dependencies.immich.listAlbumsForAsset(assetId);
const asset = await dependencies.immich.getAsset(assetId);
const assetAlbums = asset.albums;
const granted = new Set(grantedAlbumIds);
return assetAlbums.some((album) => granted.has(album.id));
}
+144
View File
@@ -0,0 +1,144 @@
import { NextRequest } from "next/server";
import { requireActiveEditorial } from "@/modules/auth/principal";
import { usageService } from "@/modules/usages/service";
import { immichClient } from "@/modules/immich/client";
import { downloadDeliveryRepository } from "@/modules/downloads/stream";
import { albumGrantService } from "@/modules/albums/grants";
const archiver = require("archiver");
import { Readable } from "stream";
export async function POST(request: NextRequest) {
try {
const principal = await requireActiveEditorial(request.headers);
const { assetIds, purpose } = await request.json();
if (!Array.isArray(assetIds) || assetIds.length === 0 || !purpose) {
return new Response("Invalid request", { status: 400 });
}
const grantedAlbumIds = await albumGrantService.getGrantedAlbumIds(principal.editorialId);
const grantedSet = new Set(grantedAlbumIds);
const downloadsToProcess: { assetId: string, downloadId: string, filename: string, intentKind: "new_usage" | "repeat" }[] = [];
for (const assetId of assetIds) {
// 1. Fetch asset to find its albums
let asset;
try {
asset = await immichClient.getAsset(assetId);
} catch (err) {
console.error("Asset fetch failed", assetId, err);
continue; // Skip unavailable assets
}
// 2. Find the first album the editorial has access to
const validAlbum = asset.albums.find(a => grantedSet.has(a.id));
if (!validAlbum) continue; // Editorial does not have access
// 3. Check for prior usages to avoid double charging
const priorUsages = await usageService.listPriorUsages(principal.editorialId, assetId);
const isRepeat = priorUsages.length > 0;
// 4. Create new usage (or repeat download if prior usages exist)
// Since createNewUsage handles idempotent repeats automatically, we just need to pass an idempotency key.
const idempotencyKey = `${principal.editorialId}-${assetId}-${purpose}`;
const newUsage = await usageService.createNewUsage({
editorialId: principal.editorialId,
assetId,
albumId: validAlbum.id,
purpose,
reference: undefined,
idempotencyKey,
});
downloadsToProcess.push({
assetId,
downloadId: newUsage.id,
filename: asset.originalFileName,
intentKind: isRepeat ? "repeat" : "new_usage",
});
}
if (downloadsToProcess.length === 0) {
return new Response("No valid assets found for download", { status: 404 });
}
// Create a streaming response with archiver
const archive = archiver('zip', { zlib: { level: 0 } }); // No compression, images are already compressed
// We must return a ReadableStream to Next.js
const transformStream = new TransformStream();
// Pipe archiver output to the writable side of the TransformStream
const writableNodeStream = new WritableStreamToNodeStream(transformStream.writable);
archive.pipe(writableNodeStream);
// Start appending files asynchronously
(async () => {
for (const download of downloadsToProcess) {
// Claim the download to verify it's authorized
const claim = await downloadDeliveryRepository.claimAuthorized(principal.editorialId, download.downloadId);
if (claim.outcome !== "claimed") continue;
try {
const original = await immichClient.getOriginal(download.assetId);
// Track bytes read for accounting
let transferredBytes = 0;
const trackingTransform = new TransformStream({
transform(chunk, controller) {
transferredBytes += chunk.length;
controller.enqueue(chunk);
},
async flush() {
await downloadDeliveryRepository.markCompleted(download.downloadId, transferredBytes);
}
});
const trackedStream = original.body.pipeThrough(trackingTransform);
const nodeStream = Readable.fromWeb(trackedStream as any);
archive.append(nodeStream, { name: download.filename });
} catch (err) {
console.error("Failed to append original for asset", download.assetId, err);
await downloadDeliveryRepository.failBeforeDelivery(download.downloadId, {
voidNewUsage: download.intentKind === "new_usage"
});
}
}
archive.finalize();
})();
const date = new Date().toISOString().split('T')[0];
return new Response(transformStream.readable, {
headers: {
"Content-Type": "application/zip",
"Content-Disposition": `attachment; filename="leuchtkasten-${date}.zip"`,
},
});
} catch (err) {
console.error("Bulk download failed", err);
return new Response("Internal Server Error", { status: 500 });
}
}
// Helper to convert Web WritableStream to Node Writable Stream
import { Writable } from "stream";
class WritableStreamToNodeStream extends Writable {
private writer: WritableStreamDefaultWriter<any>;
constructor(writableStream: WritableStream) {
super();
this.writer = writableStream.getWriter();
}
_write(chunk: any, encoding: string, callback: (error?: Error | null) => void) {
this.writer.write(chunk).then(() => callback()).catch(callback);
}
_final(callback: (error?: Error | null) => void) {
this.writer.close().then(() => callback()).catch(callback);
}
}