Files
immich-redaktions-plugin/src/modules/albums/catalog.ts
T

207 lines
6.5 KiB
TypeScript

import "server-only";
import { albumGrantService } from "@/modules/albums/grants";
import { immichClient } from "@/modules/immich/client";
import type { ImmichAlbumSummary, ImmichClient, ImmichSearchPage } from "@/modules/immich/types";
import { consumeRateLimit, searchPolicy } from "@/modules/security/rate-limit";
import {
enforceRateLimit,
RateLimitExceededError,
type ConsumeRateLimit,
} from "@/modules/security/rate-limit-guard";
export const PHOTO_PAGE_SIZE = 60;
export const MAX_PHOTO_PAGE = 1_000;
const MAX_DESCRIPTION_LENGTH = 200;
export type VisibleAlbum = ImmichAlbumSummary;
export type SearchVisiblePhotosInput = {
requestedAlbumId?: string;
description?: unknown;
page?: unknown;
size?: number;
};
export type AlbumCatalogDependencies = {
grants: Pick<typeof albumGrantService, "getGrantedAlbumIds">;
immich: Pick<ImmichClient, "listAlbums" | "searchPhotos">;
consumeRateLimit: ConsumeRateLimit;
};
export class AlbumCatalogError extends Error {
readonly name = "AlbumCatalogError";
constructor(
readonly code: "IMMICH_UNAVAILABLE" | "RATE_LIMITED",
readonly retryAfterSeconds?: number,
) {
super(code);
}
}
export function createAlbumCatalog({ grants, immich, consumeRateLimit: consume }: AlbumCatalogDependencies) {
return {
async getVisibleAlbums(editorialId: string): Promise<VisibleAlbum[]> {
const [grantedAlbumIds, albums] = await Promise.all([
currentGrantIds(grants, editorialId),
loadAlbums(immich),
]);
const granted = new Set(grantedAlbumIds);
return albums.filter((album) => granted.has(album.id));
},
async searchVisiblePhotos(
editorialId: string,
input: SearchVisiblePhotosInput,
): Promise<ImmichSearchPage> {
const description = normalizeDescription(input.description);
if (description) {
try {
await enforceRateLimit(consume, `search:${editorialId}`, searchPolicy);
} catch (error) {
if (error instanceof RateLimitExceededError) {
throw new AlbumCatalogError("RATE_LIMITED", error.retryAfterSeconds);
}
throw error;
}
}
const grantedAlbumIds = await currentGrantIds(grants, editorialId);
if (grantedAlbumIds.length === 0) {
return emptySearchPage();
}
const page = normalizePage(input.page);
const size = input.size ?? PHOTO_PAGE_SIZE;
if (input.requestedAlbumId) {
const albumIds = authorizedSearchAlbums(grantedAlbumIds, input.requestedAlbumId);
if (albumIds.length === 0) {
return emptySearchPage();
}
return searchAlbum(immich, albumIds, description, page, size);
}
// Cross-album search. Immich's `albumIds` filter is AND across albums —
// an asset must be in EVERY listed album — so one call with all granted
// ids returns nothing for assets that live in a single album (the common
// case: one photo per game/series album). Fan out per granted album and
// merge; callers paginate in-app via paginatePhotos.
// ponytail: N upstream calls per global search. Bounded by the editorial's
// grant count and narrowed by the description filter, so per-album results
// are small. If a huge-grant editorial makes this slow, cap the fan-out
// and accept partial coverage.
const pages = await Promise.all(
grantedAlbumIds.map((albumId) => searchAlbum(immich, [albumId], description, page, size)),
);
return mergeSearchPages(pages);
},
};
}
async function searchAlbum(
immich: Pick<ImmichClient, "searchPhotos">,
albumIds: string[],
description: string | undefined,
page: number,
size: number,
): Promise<ImmichSearchPage> {
try {
const searchPage = await immich.searchPhotos({
albumIds,
...(description === undefined ? {} : { description }),
type: "IMAGE",
page,
size,
});
const queriedAlbumId = albumIds[0];
return {
...searchPage,
items: queriedAlbumId
? searchPage.items.map((asset) => {
const queriedAlbum = asset.albums.find(({ id }) => id === queriedAlbumId) ?? { id: queriedAlbumId };
return {
...asset,
albums: [queriedAlbum, ...asset.albums.filter(({ id }) => id !== queriedAlbumId)],
};
})
: searchPage.items,
};
} catch {
throw new AlbumCatalogError("IMMICH_UNAVAILABLE");
}
}
function mergeSearchPages(pages: ImmichSearchPage[]): ImmichSearchPage {
// nextPage/previousPage are unused by callers — they paginate in-app via
// paginatePhotos, which recomputes both from the merged item count.
return {
items: pages.flatMap((p) => p.items),
total: pages.reduce((sum, p) => sum + p.total, 0),
nextPage: null,
previousPage: null,
};
}
function emptySearchPage(): ImmichSearchPage {
return { items: [], total: 0, nextPage: null, previousPage: null };
}
async function currentGrantIds(
grants: Pick<typeof albumGrantService, "getGrantedAlbumIds">,
editorialId: string,
): Promise<string[]> {
return [...new Set(await grants.getGrantedAlbumIds(editorialId))];
}
function authorizedSearchAlbums(grantedAlbumIds: string[], requestedAlbumId: string | undefined): string[] {
if (requestedAlbumId && grantedAlbumIds.includes(requestedAlbumId)) {
return [requestedAlbumId];
}
return grantedAlbumIds;
}
function normalizeDescription(description: unknown): string | undefined {
if (typeof description !== "string") {
return undefined;
}
const normalized = description.replace(/\s+/g, " ").trim().slice(0, MAX_DESCRIPTION_LENGTH);
return normalized || undefined;
}
export function normalizePage(page: unknown): number {
const parsed = parsePage(page);
if (parsed === null) {
return 1;
}
return Math.min(MAX_PHOTO_PAGE, Math.max(1, parsed));
}
function parsePage(page: unknown): number | null {
if (typeof page === "number") {
return Number.isFinite(page) && Number.isInteger(page) ? page : null;
}
if (typeof page !== "string" || !/^\d+$/.test(page)) {
return null;
}
const parsed = Number(page);
return Number.isSafeInteger(parsed) ? parsed : MAX_PHOTO_PAGE;
}
async function loadAlbums(
immich: Pick<ImmichClient, "listAlbums">,
): Promise<ImmichAlbumSummary[]> {
try {
return await immich.listAlbums();
} catch {
throw new AlbumCatalogError("IMMICH_UNAVAILABLE");
}
}
export const albumCatalog = createAlbumCatalog({
grants: albumGrantService,
immich: immichClient,
consumeRateLimit,
});