394 lines
11 KiB
TypeScript
394 lines
11 KiB
TypeScript
import "server-only";
|
|
|
|
import { z } from "zod";
|
|
|
|
import { env } from "@/config/env";
|
|
|
|
import { ImmichClientError, type ImmichErrorCode } from "./errors";
|
|
import type {
|
|
ImmichAlbum,
|
|
ImmichAlbumSummary,
|
|
ImmichAsset,
|
|
ImmichBinary,
|
|
ImmichClient,
|
|
ImmichSearchPage,
|
|
} from "./types";
|
|
|
|
const nullableString = z.string().nullable().optional().transform((value) => value ?? null);
|
|
|
|
const assetSchema = z
|
|
.object({
|
|
id: z.string(),
|
|
type: z.literal("IMAGE"),
|
|
originalFileName: z.string(),
|
|
originalMimeType: z.string(),
|
|
localDateTime: nullableString,
|
|
fileCreatedAt: nullableString,
|
|
albums: z.array(z.object({ id: z.string() }).passthrough()).optional().default([]),
|
|
exifInfo: z.object({
|
|
exifImageWidth: z.number().optional().nullable(),
|
|
exifImageHeight: z.number().optional().nullable(),
|
|
}).passthrough().optional().nullable(),
|
|
})
|
|
.passthrough();
|
|
|
|
const currentAssetSchema = assetSchema.extend({
|
|
type: z.enum(["IMAGE", "VIDEO"]),
|
|
});
|
|
|
|
const albumSummarySchema = z
|
|
.object({
|
|
id: z.string(),
|
|
albumName: z.string(),
|
|
description: nullableString,
|
|
albumThumbnailAssetId: nullableString,
|
|
assetCount: z.number().int().nonnegative(),
|
|
})
|
|
.passthrough();
|
|
|
|
const albumSchema = albumSummarySchema.extend({
|
|
// `getAlbum` requests `?withoutAssets=true` so Immich returns album metadata
|
|
// without the full asset list — otherwise large albums blow past the request
|
|
// timeout and surface as IMMICH_UNAVAILABLE. No consumer reads `.assets`.
|
|
assets: z.array(assetSchema).optional().default([]),
|
|
});
|
|
|
|
const metadataSearchSchema = z
|
|
.object({
|
|
assets: z
|
|
.object({
|
|
items: z.array(assetSchema),
|
|
total: z.number().int().nonnegative(),
|
|
// Immich v3 returns `nextPage` as a cursor string (previously a page
|
|
// number); accept either so schema validation doesn't reject v3
|
|
// responses. We only use it as a has-more-pages signal, never as the
|
|
// page link target (links are currentPage ± 1).
|
|
nextPage: z
|
|
.union([z.string(), z.number()])
|
|
.nullable()
|
|
.optional()
|
|
.transform((value) => value ?? null),
|
|
previousPage: z
|
|
.union([z.string(), z.number()])
|
|
.nullable()
|
|
.optional()
|
|
.transform((value) => value ?? null),
|
|
})
|
|
.passthrough(),
|
|
})
|
|
.passthrough();
|
|
|
|
type FetchLike = typeof globalThis.fetch;
|
|
|
|
type RequestLifecycle = {
|
|
signal: AbortSignal;
|
|
cleanup(): void;
|
|
clearTimeout(): void;
|
|
failureCode(): Extract<ImmichErrorCode, "IMMICH_ABORTED" | "IMMICH_TIMEOUT"> | undefined;
|
|
};
|
|
|
|
export type CreateImmichClientOptions = {
|
|
baseUrl?: string;
|
|
apiKey?: string;
|
|
fetch?: FetchLike;
|
|
timeoutMs?: number;
|
|
};
|
|
|
|
function errorForStatus(status: number): ImmichClientError {
|
|
const code: ImmichErrorCode =
|
|
status === 401 || status === 403
|
|
? "IMMICH_AUTH_FAILED"
|
|
: status === 404
|
|
? "IMMICH_NOT_FOUND"
|
|
: status === 429
|
|
? "IMMICH_RATE_LIMITED"
|
|
: status >= 500
|
|
? "IMMICH_UNAVAILABLE"
|
|
: "IMMICH_REQUEST_FAILED";
|
|
|
|
return new ImmichClientError(code, status);
|
|
}
|
|
|
|
function responseFilename(response: Response, fallback: string): string {
|
|
const contentDisposition = response.headers.get("content-disposition");
|
|
const match = contentDisposition?.match(/filename\*?=(?:UTF-8''|\")(.*?)(?:\"|;|$)/i);
|
|
const filename = match?.[1]?.trim();
|
|
|
|
if (!filename) {
|
|
return fallback;
|
|
}
|
|
|
|
try {
|
|
return decodeURIComponent(filename);
|
|
} catch {
|
|
return filename;
|
|
}
|
|
}
|
|
|
|
function contentLength(response: Response): number | null {
|
|
const value = response.headers.get("content-length");
|
|
if (!value || !/^\d+$/.test(value)) {
|
|
return null;
|
|
}
|
|
|
|
const length = Number(value);
|
|
return Number.isSafeInteger(length) ? length : null;
|
|
}
|
|
|
|
function createRequestLifecycle(callerSignal: AbortSignal | undefined, timeoutMs: number): RequestLifecycle {
|
|
const controller = new AbortController();
|
|
let timedOut = false;
|
|
let timeoutId: ReturnType<typeof setTimeout> | undefined = setTimeout(() => {
|
|
timedOut = true;
|
|
controller.abort();
|
|
}, timeoutMs);
|
|
|
|
const abortFromCaller = () => controller.abort();
|
|
if (callerSignal?.aborted) {
|
|
abortFromCaller();
|
|
} else {
|
|
callerSignal?.addEventListener("abort", abortFromCaller, { once: true });
|
|
}
|
|
|
|
function clearTimeout() {
|
|
if (timeoutId !== undefined) {
|
|
globalThis.clearTimeout(timeoutId);
|
|
timeoutId = undefined;
|
|
}
|
|
}
|
|
|
|
return {
|
|
signal: controller.signal,
|
|
cleanup() {
|
|
clearTimeout();
|
|
callerSignal?.removeEventListener("abort", abortFromCaller);
|
|
},
|
|
clearTimeout,
|
|
failureCode() {
|
|
if (timedOut) {
|
|
return "IMMICH_TIMEOUT";
|
|
}
|
|
if (callerSignal?.aborted) {
|
|
return "IMMICH_ABORTED";
|
|
}
|
|
return undefined;
|
|
},
|
|
};
|
|
}
|
|
|
|
function failureError(lifecycle: RequestLifecycle): ImmichClientError {
|
|
return new ImmichClientError(lifecycle.failureCode() ?? "IMMICH_UNAVAILABLE");
|
|
}
|
|
|
|
export function createImmichClient({
|
|
baseUrl = env.IMMICH_BASE_URL,
|
|
apiKey = env.IMMICH_API_KEY,
|
|
fetch: fetchImpl,
|
|
timeoutMs = 15_000,
|
|
}: CreateImmichClientOptions = {}): ImmichClient {
|
|
const apiBaseUrl = `${baseUrl.replace(/\/+$/, "")}/api`;
|
|
|
|
async function request(
|
|
path: string,
|
|
init: RequestInit,
|
|
signal?: AbortSignal,
|
|
): Promise<{ response: Response; lifecycle: RequestLifecycle }> {
|
|
const lifecycle = createRequestLifecycle(signal, timeoutMs);
|
|
|
|
try {
|
|
const response = await (fetchImpl ?? globalThis.fetch)(`${apiBaseUrl}${path}`, {
|
|
...init,
|
|
headers: {
|
|
"x-api-key": apiKey,
|
|
...init.headers,
|
|
},
|
|
signal: lifecycle.signal,
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw errorForStatus(response.status);
|
|
}
|
|
|
|
return { response, lifecycle };
|
|
} catch (error) {
|
|
lifecycle.cleanup();
|
|
if (error instanceof ImmichClientError) {
|
|
throw error;
|
|
}
|
|
throw failureError(lifecycle);
|
|
}
|
|
}
|
|
|
|
async function requestJson<T>(
|
|
path: string,
|
|
init: RequestInit,
|
|
schema: z.ZodType<T>,
|
|
signal?: AbortSignal,
|
|
): Promise<T> {
|
|
const { response, lifecycle } = await request(path, init, signal);
|
|
|
|
try {
|
|
let body: unknown;
|
|
try {
|
|
body = await response.json();
|
|
} catch (error) {
|
|
const code = lifecycle.failureCode();
|
|
if (code) {
|
|
throw new ImmichClientError(code);
|
|
}
|
|
if (error instanceof SyntaxError) {
|
|
throw new ImmichClientError("IMMICH_INVALID_RESPONSE");
|
|
}
|
|
throw new ImmichClientError("IMMICH_UNAVAILABLE");
|
|
}
|
|
|
|
try {
|
|
return schema.parse(body);
|
|
} catch (error) {
|
|
if (error instanceof z.ZodError) {
|
|
throw new ImmichClientError("IMMICH_INVALID_RESPONSE");
|
|
}
|
|
throw error;
|
|
}
|
|
} finally {
|
|
lifecycle.cleanup();
|
|
}
|
|
}
|
|
|
|
async function requestBinary(path: string, signal?: AbortSignal): Promise<ImmichBinary> {
|
|
const { response, lifecycle } = await request(path, { method: "GET" }, signal);
|
|
if (!response.body) {
|
|
lifecycle.cleanup();
|
|
throw new ImmichClientError("IMMICH_INVALID_RESPONSE");
|
|
}
|
|
|
|
lifecycle.clearTimeout();
|
|
const reader = response.body.getReader();
|
|
let completed = false;
|
|
let abortStream: (() => void) | undefined;
|
|
const finish = () => {
|
|
if (completed) {
|
|
return;
|
|
}
|
|
completed = true;
|
|
if (abortStream) {
|
|
lifecycle.signal.removeEventListener("abort", abortStream);
|
|
}
|
|
lifecycle.cleanup();
|
|
};
|
|
|
|
const body = new ReadableStream<Uint8Array>({
|
|
start(controller) {
|
|
abortStream = () => {
|
|
if (completed) {
|
|
return;
|
|
}
|
|
const error = failureError(lifecycle);
|
|
finish();
|
|
void reader.cancel(error).catch(() => undefined);
|
|
controller.error(error);
|
|
};
|
|
lifecycle.signal.addEventListener("abort", abortStream, { once: true });
|
|
if (lifecycle.signal.aborted) {
|
|
abortStream();
|
|
}
|
|
},
|
|
async pull(controller) {
|
|
if (completed) {
|
|
return;
|
|
}
|
|
try {
|
|
const { done, value } = await reader.read();
|
|
if (done) {
|
|
finish();
|
|
controller.close();
|
|
return;
|
|
}
|
|
controller.enqueue(value);
|
|
} catch {
|
|
if (completed) {
|
|
return;
|
|
}
|
|
const error = failureError(lifecycle);
|
|
finish();
|
|
controller.error(error);
|
|
}
|
|
},
|
|
cancel(reason) {
|
|
finish();
|
|
return reader.cancel(reason);
|
|
},
|
|
});
|
|
|
|
return {
|
|
body,
|
|
contentType: response.headers.get("content-type") ?? "application/octet-stream",
|
|
contentLength: contentLength(response),
|
|
filename: responseFilename(response, "asset"),
|
|
};
|
|
}
|
|
|
|
return {
|
|
listAlbums(signal) {
|
|
return requestJson<ImmichAlbumSummary[]>("/albums", { method: "GET" }, z.array(albumSummarySchema), signal);
|
|
},
|
|
listAlbumsForAsset(assetId, signal) {
|
|
const query = new URLSearchParams({ assetId });
|
|
return requestJson<ImmichAlbumSummary[]>(
|
|
`/albums?${query.toString()}`,
|
|
{ method: "GET" },
|
|
z.array(albumSummarySchema),
|
|
signal,
|
|
);
|
|
},
|
|
getAlbum(albumId, signal) {
|
|
return requestJson<ImmichAlbum>(
|
|
`/albums/${encodeURIComponent(albumId)}?withoutAssets=true`,
|
|
{ method: "GET" },
|
|
albumSchema,
|
|
signal,
|
|
);
|
|
},
|
|
getAsset(assetId, signal) {
|
|
return requestJson<ImmichAsset>(
|
|
`/assets/${encodeURIComponent(assetId)}`,
|
|
{ method: "GET" },
|
|
currentAssetSchema,
|
|
signal,
|
|
);
|
|
},
|
|
searchPhotos(input, signal) {
|
|
return requestJson<ImmichSearchPage>(
|
|
"/search/metadata",
|
|
{
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({
|
|
albumIds: input.albumIds,
|
|
...(input.description === undefined ? {} : { description: input.description }),
|
|
type: "IMAGE",
|
|
page: input.page,
|
|
size: input.size,
|
|
}),
|
|
},
|
|
metadataSearchSchema.transform(({ assets }) => ({
|
|
items: assets.items,
|
|
total: assets.total,
|
|
nextPage: assets.nextPage,
|
|
previousPage: assets.previousPage,
|
|
})),
|
|
signal,
|
|
);
|
|
},
|
|
getThumbnail(assetId, signal) {
|
|
// Request 'preview' size to get a larger image, so we can resize it cleanly to 480px
|
|
return requestBinary(`/assets/${encodeURIComponent(assetId)}/thumbnail?size=preview`, signal);
|
|
},
|
|
getOriginal(assetId, signal) {
|
|
return requestBinary(`/assets/${encodeURIComponent(assetId)}/original`, signal);
|
|
},
|
|
};
|
|
}
|
|
|
|
export const immichClient = createImmichClient();
|