Files

215 lines
6.5 KiB
TypeScript

import { createServer, type Server, type IncomingMessage, type ServerResponse } from "node:http";
export type FakeImmichAsset = {
id: string;
type: "IMAGE";
originalFileName: string;
originalMimeType: string;
localDateTime: string;
fileCreatedAt: string;
albums: { id: string }[];
};
export type FakeImmichAlbum = {
id: string;
albumName: string;
description: string | null;
albumThumbnailAssetId: string | null;
assetCount: number;
assets: FakeImmichAsset[];
};
export type FakeImmichServerOptions = {
port?: number;
albums?: FakeImmichAlbum[];
apiKey?: string;
};
const SAMPLE_1X1_JPEG = Buffer.from(
"/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wgALCAABAAEBAREA/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxA=",
"base64",
);
export function createFakeImmichServer({
port = 2283,
albums = [
{
id: "album-1",
albumName: "Presse 2026",
description: "Offizielle Pressefotos",
albumThumbnailAssetId: "asset-1",
assetCount: 2,
assets: [
{
id: "asset-1",
type: "IMAGE",
originalFileName: "IMG_4821.jpg",
originalMimeType: "image/jpeg",
localDateTime: "2026-08-01T12:00:00Z",
fileCreatedAt: "2026-08-01T12:00:00Z",
albums: [{ id: "album-1" }],
},
{
id: "asset-2",
type: "IMAGE",
originalFileName: "IMG_4822.jpg",
originalMimeType: "image/jpeg",
localDateTime: "2026-08-02T14:00:00Z",
fileCreatedAt: "2026-08-02T14:00:00Z",
albums: [{ id: "album-1" }],
},
],
},
],
apiKey = "test-immich-api-key",
}: FakeImmichServerOptions = {}): {
server: Server;
start: () => Promise<string>;
stop: () => Promise<void>;
setOutage: (enabled: boolean) => void;
} {
let outage = false;
const server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
const reqApiKey = req.headers["x-api-key"];
if (apiKey && reqApiKey !== apiKey) {
res.writeHead(401, { "content-type": "application/json" });
res.end(JSON.stringify({ message: "Unauthorized" }));
return;
}
if (outage) {
res.writeHead(503, { "content-type": "application/json" });
res.end(JSON.stringify({ message: "Immich server unavailable" }));
return;
}
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
const path = url.pathname;
if (req.method === "GET" && path === "/api/albums") {
const summaries = albums.map(({ id, albumName, description, albumThumbnailAssetId, assetCount }) => ({
id,
albumName,
description,
albumThumbnailAssetId,
assetCount,
}));
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(summaries));
return;
}
const albumMatch = path.match(/^\/api\/albums\/([^/]+)$/);
if (req.method === "GET" && albumMatch) {
const albumId = decodeURIComponent(albumMatch[1]);
const album = albums.find((a) => a.id === albumId);
if (!album) {
res.writeHead(404, { "content-type": "application/json" });
res.end(JSON.stringify({ message: "Album not found" }));
return;
}
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(album));
return;
}
const assetMatch = path.match(/^\/api\/assets\/([^/]+)$/);
if (req.method === "GET" && assetMatch) {
const assetId = decodeURIComponent(assetMatch[1]);
const allAssets = albums.flatMap((a) => a.assets);
const asset = allAssets.find((a) => a.id === assetId);
if (!asset) {
res.writeHead(404, { "content-type": "application/json" });
res.end(JSON.stringify({ message: "Asset not found" }));
return;
}
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(asset));
return;
}
if (req.method === "POST" && path === "/api/search/metadata") {
let bodyStr = "";
for await (const chunk of req) {
bodyStr += chunk;
}
const body = JSON.parse(bodyStr || "{}");
const targetAlbumIds: string[] = body.albumIds || [];
const descriptionQuery: string | undefined = body.description;
const allAssets = albums
.filter((a) => targetAlbumIds.length === 0 || targetAlbumIds.includes(a.id))
.flatMap((a) => a.assets);
let items = allAssets;
if (descriptionQuery) {
items = items.filter((a) => a.originalFileName.toLowerCase().includes(descriptionQuery.toLowerCase()));
}
res.writeHead(200, { "content-type": "application/json" });
res.end(
JSON.stringify({
assets: {
items,
total: items.length,
nextPage: null,
previousPage: null,
},
}),
);
return;
}
const thumbMatch = path.match(/^\/api\/assets\/([^/]+)\/thumbnail$/);
if (req.method === "GET" && thumbMatch) {
res.writeHead(200, {
"content-type": "image/jpeg",
"content-length": String(SAMPLE_1X1_JPEG.length),
});
res.end(SAMPLE_1X1_JPEG);
return;
}
const origMatch = path.match(/^\/api\/assets\/([^/]+)\/original$/);
if (req.method === "GET" && origMatch) {
const assetId = decodeURIComponent(origMatch[1]);
const allAssets = albums.flatMap((a) => a.assets);
const asset = allAssets.find((a) => a.id === assetId);
const filename = asset?.originalFileName || `${assetId}.jpg`;
res.writeHead(200, {
"content-type": "image/jpeg",
"content-length": String(SAMPLE_1X1_JPEG.length),
"content-disposition": `attachment; filename="${filename}"`,
});
res.end(SAMPLE_1X1_JPEG);
return;
}
res.writeHead(404, { "content-type": "application/json" });
res.end(JSON.stringify({ message: "Not found" }));
});
return {
server,
start() {
return new Promise((resolve, reject) => {
server.listen(port, () => {
const addr = server.address();
const actualPort = typeof addr === "object" && addr ? addr.port : port;
resolve(`http://localhost:${actualPort}`);
});
server.on("error", reject);
});
},
stop() {
return new Promise((resolve, reject) => {
server.close((err) => (err ? reject(err) : resolve()));
});
},
setOutage(enabled: boolean) {
outage = enabled;
},
};
}