Files
immich-redaktions-plugin/src/app/api/assets/[assetId]/thumbnail/thumbnail-handler.ts
T

171 lines
5.4 KiB
TypeScript

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";
import sharp from "sharp";
type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
type ThumbnailImmich = {
listAlbumsForAsset(assetId: string): Promise<Array<{ id: string }>>;
getAlbum(albumId: string): Promise<{ albumThumbnailAssetId: string | null }>;
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 requestedUrl = new URL(request.url);
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,
requestedUrl.searchParams.get("albumId"),
)
: await isGrantedEditorialAsset(dependencies, access.editorialId, assetId);
if (!authorized) {
return genericNotFound();
}
const thumbnail = await dependencies.immich.getThumbnail(assetId);
if (access.kind === "editorial") {
return watermarkedThumbnailResponse(thumbnail);
}
return thumbnailResponse(thumbnail);
} catch (err) {
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 assetAlbums = await dependencies.immich.listAlbumsForAsset(assetId);
const granted = new Set(grantedAlbumIds);
return assetAlbums.some((album) => granted.has(album.id));
}
async function isAdminAlbumCover(
immich: ThumbnailImmich,
assetId: string,
albumId: string | null,
): Promise<boolean> {
if (!albumId || !isSafeAssetId(albumId)) {
return false;
}
const album = await immich.getAlbum(albumId);
return 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 });
}
async function watermarkedThumbnailResponse(thumbnail: ImmichBinary): Promise<Response> {
const reader = thumbnail.body.getReader();
const chunks: Uint8Array[] = [];
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) chunks.push(value);
}
const buffer = Buffer.concat(chunks);
const metadata = await sharp(buffer).metadata();
const width = metadata.width ?? 400;
const height = metadata.height ?? 300;
const svgText = `
<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg">
<text x="50%" y="50%" font-family="Arial, sans-serif" font-size="${Math.max(24, width / 8)}" font-weight="bold" fill="white" opacity="0.5" text-anchor="middle" alignment-baseline="middle" transform="rotate(-30 ${width/2} ${height/2})">
PREVIEW
</text>
</svg>
`;
const watermarked = await sharp(buffer)
.composite([
{
input: Buffer.from(svgText),
gravity: "center",
},
])
.webp({ quality: 80 })
.toBuffer();
const responseHeaders = new Headers({
"cache-control": "private, no-store",
"content-type": "image/webp",
"content-length": String(watermarked.length),
"x-content-type-options": "nosniff",
});
return new Response(watermarked, { headers: responseHeaders });
}
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,
});