/** * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ import { existsSync } from "node:fs"; import { loadCookieJar } from "../cookies/cookie-loader.ts"; import { DEFAULT_GOOGLE_COOKIE_JAR } from "../google/search.ts"; import { sharedCache } from "../google/cache.ts"; import { googleImageSearch } from "../google/verticals.ts"; export type AssetKind = "image" | "gif"; export type AssetRating = "high" | "medium" | "low" | "off"; export interface AssetSearchOptions { kind?: AssetKind; limit?: number; locale?: string; country?: string; rating?: AssetRating; providers?: readonly string[]; cacheTtlMs?: number; staleTtlMs?: number; offset?: number; } export interface AssetSearchResult { id: string; kind: AssetKind; provider: string; title: string; url: string; previewUrl: string | null; pageUrl: string | null; width: number | null; height: number | null; attribution: string; analytics?: { onload?: string; onclick?: string; onsent?: string; }; } export interface AssetProviderStatus { provider: string; status: "ok" | "empty" | "error"; count: number; error?: string; } export interface AssetSearchResponse { query: string; kind: AssetKind; results: AssetSearchResult[]; providers: AssetProviderStatus[]; cache: "fresh" | "stale" | "miss"; offset: number; nextOffset: number | null; } export interface AssetProvider { readonly name: string; readonly kinds: readonly AssetKind[]; available(): boolean; search( query: string, options: AssetSearchOptions, ): Promise; } type FetchLike = ( input: string | URL | Request, init?: RequestInit, ) => Promise; function boundedLimit(value: number | undefined): number { return Math.max(1, Math.min(50, Math.floor(value ?? 10))); } function numberOrNull(value: unknown): number | null { const parsed = Number(value); return Number.isFinite(parsed) && parsed > 0 ? parsed : null; } async function fetchJson(fetcher: FetchLike, url: URL): Promise { let lastError: unknown; for (let attempt = 0; attempt < 3; attempt++) { try { const response = await fetcher(url, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(15_000), }); if (response.ok) return (await response.json()) as T; if (response.status !== 429 && response.status < 500) throw new Error(`${url.hostname} returned HTTP ${response.status}`); lastError = new Error(`${url.hostname} returned HTTP ${response.status}`); } catch (error) { lastError = error; if ( error instanceof Error && /HTTP 4\d\d/.test(error.message) && !/HTTP 429/.test(error.message) ) throw error; } if (attempt < 2) await Bun.sleep(150 * 2 ** attempt + Math.floor(Math.random() * 100)); } throw lastError instanceof Error ? lastError : new Error(`${url.hostname} request failed`); } export class GoogleImageProvider implements AssetProvider { readonly name = "google-images"; readonly kinds = ["image", "gif"] as const; available(): boolean { return true; } async search( query: string, options: AssetSearchOptions, ): Promise { const kind = options.kind ?? "image"; const cookies = existsSync(DEFAULT_GOOGLE_COOKIE_JAR) ? await loadCookieJar(DEFAULT_GOOGLE_COOKIE_JAR).catch(() => []) : []; const suffix = kind === "gif" ? " filetype:gif" : ""; const rows = await googleImageSearch(`${query}${suffix}`, { hl: options.locale?.split(/[-_]/)[0] ?? "en", gl: options.country ?? "US", num: boundedLimit(options.limit), cookies, }); return rows .filter((row) => row.imageUrl ?? row.thumbnail) .map((row, index) => ({ id: `${index}:${row.imageUrl ?? row.thumbnail}`, kind, provider: this.name, title: row.title, url: row.imageUrl ?? row.thumbnail, previewUrl: row.thumbnail || null, pageUrl: row.source || null, width: null, height: null, attribution: "Google Images result; follow the source page for rights and attribution", })); } } interface CommonsResponse { query?: { pages?: Record< string, { pageid?: number; title?: string; imageinfo?: Array<{ url?: string; thumburl?: string; width?: number; height?: number; descriptionurl?: string; extmetadata?: Record; }>; } >; }; } export class WikimediaImageProvider implements AssetProvider { readonly name = "wikimedia-commons"; readonly kinds = ["image"] as const; constructor(private readonly fetcher: FetchLike = fetch) {} available(): boolean { return true; } async search( query: string, options: AssetSearchOptions, ): Promise { const url = new URL("https://commons.wikimedia.org/w/api.php"); url.searchParams.set("action", "query"); url.searchParams.set("format", "json"); url.searchParams.set("generator", "search"); url.searchParams.set("gsrnamespace", "6"); url.searchParams.set("gsrsearch", query); url.searchParams.set("gsrlimit", String(boundedLimit(options.limit))); url.searchParams.set("prop", "imageinfo"); url.searchParams.set("iiprop", "url|size|extmetadata"); url.searchParams.set("iiurlwidth", "480"); url.searchParams.set("origin", "*"); const body = await fetchJson(this.fetcher, url); return Object.values(body.query?.pages ?? {}).flatMap((page) => { const image = page.imageinfo?.[0]; if (!page.pageid || !image?.url) return []; const license = image.extmetadata?.LicenseShortName?.value; const artist = image.extmetadata?.Artist?.value?.replace(/<[^>]*>/g, ""); return [ { id: String(page.pageid), kind: "image" as const, provider: this.name, title: page.title?.replace(/^File:/, "") ?? "", url: image.url, previewUrl: image.thumburl ?? image.url, pageUrl: image.descriptionurl ?? null, width: numberOrNull(image.width), height: numberOrNull(image.height), attribution: [artist, license, "Wikimedia Commons"] .filter(Boolean) .join(" — "), }, ]; }); } } export class TenorGifProvider implements AssetProvider { readonly name = "tenor"; readonly kinds = ["gif"] as const; constructor( _apiKey = Bun.env.TENOR_API_KEY, _clientKey = Bun.env.TENOR_CLIENT_KEY ?? "bxc", _fetcher: FetchLike = fetch, ) {} available(): boolean { return false; } async search( _query: string, _options: AssetSearchOptions, ): Promise { throw new Error("Tenor API was retired on 2026-06-30"); } } interface GiphyResponse { data?: Array<{ id?: string; title?: string; url?: string; images?: Record; }>; pagination?: { total_count?: number; count?: number; offset?: number }; meta?: { status?: number; msg?: string; response_id?: string }; } export class GiphyGifProvider implements AssetProvider { readonly name = "giphy"; readonly kinds = ["gif"] as const; constructor( private readonly apiKey = Bun.env.GIPHY_API_KEY, private readonly fetcher: FetchLike = fetch, ) {} available(): boolean { return Boolean(this.apiKey); } async search( query: string, options: AssetSearchOptions, ): Promise { if (!this.apiKey) throw new Error("GIPHY_API_KEY is required"); const url = new URL("https://api.giphy.com/v1/gifs/search"); url.searchParams.set("api_key", this.apiKey); url.searchParams.set("q", [...query].slice(0, 50).join("")); url.searchParams.set("limit", String(boundedLimit(options.limit))); url.searchParams.set( "offset", String(Math.max(0, Math.min(4999, Math.floor(options.offset ?? 0)))), ); url.searchParams.set( "rating", options.rating === "off" ? "r" : options.rating === "low" ? "pg-13" : options.rating === "medium" ? "pg" : "g", ); url.searchParams.set("lang", options.locale?.split(/[-_]/)[0] ?? "en"); url.searchParams.set( "country_code", (options.country ?? "US").toUpperCase(), ); url.searchParams.set("bundle", "messaging_non_clips"); const body = await fetchJson(this.fetcher, url); if (body.meta?.status !== 200 || !body.meta.response_id) throw new Error( `GIPHY API error ${body.meta?.status ?? "invalid-response"}`, ); return (body.data ?? []).flatMap((row) => { const image = row.images?.downsized ?? row.images?.downsized_medium ?? row.images?.original; if (!row.id || !image?.url) return []; return [ { id: row.id, kind: "gif" as const, provider: this.name, title: row.title ?? "", url: image.url, previewUrl: row.images?.fixed_width_small?.url ?? image.url, pageUrl: row.url ?? null, width: numberOrNull(image.width), height: numberOrNull(image.height), attribution: "Powered by GIPHY", analytics: (row as { analytics?: AssetSearchResult["analytics"] }) .analytics, }, ]; }); } } export class AssetSearch { constructor( readonly providers: readonly AssetProvider[] = [ new WikimediaImageProvider(), new GoogleImageProvider(), new GiphyGifProvider(), ], ) {} available(kind: AssetKind): string[] { return this.providers .filter( (provider) => provider.available() && provider.kinds.includes(kind), ) .map((provider) => provider.name); } async search( query: string, options: AssetSearchOptions = {}, ): Promise { const trimmed = query.trim(); if (!trimmed) throw new Error("asset search query cannot be empty"); const kind = options.kind ?? "image"; const limit = boundedLimit(options.limit); const offset = Math.max(0, Math.floor(options.offset ?? 0)); const selected = new Set(options.providers ?? []); const providers = this.providers.filter( (provider) => provider.available() && provider.kinds.includes(kind) && (selected.size === 0 || selected.has(provider.name)), ); if (providers.length === 0) throw new Error(`no ${kind} provider is configured`); const key = `asset-search:v2:${kind}:${trimmed}:${options.locale ?? ""}:${options.country ?? ""}:${options.rating ?? ""}:${providers.map((p) => p.name).join(",")}:${limit}:${offset}`; const cache = sharedCache(); const hit = cache.get(key); if (hit) return { ...hit, cache: "fresh" }; const staleKey = `${key}:stale`; const settled = await Promise.allSettled( providers.map((provider) => provider.search(trimmed, { ...options, kind, limit }), ), ); const byUrl = new Map(); const statuses: AssetProviderStatus[] = []; for (let index = 0; index < settled.length; index++) { const result = settled[index]; const provider = providers[index]; if (result.status !== "fulfilled") { statuses.push({ provider: provider.name, status: "error", count: 0, error: result.reason instanceof Error ? result.reason.message : "provider failed", }); continue; } statuses.push({ provider: provider.name, status: result.value.length ? "ok" : "empty", count: result.value.length, }); for (const asset of result.value) { if (!byUrl.has(asset.url)) byUrl.set(asset.url, asset); } } const assets = [...byUrl.values()].slice(0, limit); if (assets.length === 0) { const stale = cache.get(staleKey); if (stale) return { ...stale, cache: "stale", providers: statuses }; throw new Error( `all configured ${kind} providers failed or returned no results`, ); } const response: AssetSearchResponse = { query: trimmed, kind, results: assets, providers: statuses, cache: "miss", offset, nextOffset: assets.length >= limit ? offset + limit : null, }; cache.set(key, response, options.cacheTtlMs ?? 3_600_000); cache.set(staleKey, response, options.staleTtlMs ?? 86_400_000); return response; } }