SPB Git

Repository Public

images.ts 8.4 KB 212 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : UQO Éval — Le Grand Défi Immobilier8 * File             : apps/api/src/images.ts9 * Module           : api10 * Repository       : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website  : https://jeux.uqo-eval.app12 * Created          : 2026-11-2513 * Last Modified    : 2026-11-2514 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * Property Image Pipeline.45 *46 * Le navigateur ne voit que des identifiants opaques : `/img/<id>/<largeur>`.47 * Le serveur récupère la photographie d'origine, la réoriente, la48 * redimensionne sans l'altérer, retire les métadonnées, la convertit en WebP49 * et la conserve en cache. Ni l'URL d'origine ni le nom du fichier ne sont50 * transmis au joueur.51 */52import fs from "node:fs";53import path from "node:path";54import sharp from "sharp";55import { config } from "./config.ts";56import { sql } from "./db.ts";5758export const IMAGE_WIDTHS = [480, 960, 1600] as const;59export type ImageWidth = (typeof IMAGE_WIDTHS)[number];6061const MAX_BYTES = 20 * 1024 * 1024;62const inflight = new Map<string, Promise<string | null>>();63const sourceCache = new Map<string, string | null>();6465function cachePath(id: string, width: number): string {66  return path.join(config.imageStoragePath, id.slice(0, 2), `${id}-${width}.webp`);67}6869function isPublicUrl(raw: string): boolean {70  try {71    const url = new URL(raw);72    if (url.protocol !== "https:" && url.protocol !== "http:") return false;73    const host = url.hostname;74    if (/^\d+$/.test(host) || /^0x/i.test(host) || /^(0\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)/.test(host)) return false;75    return !(host === "localhost" || /^(127\.|10\.|192\.168\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.)/.test(host) || host.endsWith(".local") || host.includes(":"));76  } catch {77    return false;78  }79}8081async function sourceUrl(id: string): Promise<string | null> {82  if (sourceCache.has(id)) return sourceCache.get(id)!;83  const [row] = await sql<{ source_url: string }[]>`select source_url from question_images where id = ${id}`;84  const url = row?.source_url ?? null;85  if (sourceCache.size > 20_000) sourceCache.clear();86  sourceCache.set(id, url);87  return url;88}8990async function download(url: string): Promise<Buffer> {91  const origin = new URL(url).origin;92  const response = await fetch(url, {93    signal: AbortSignal.timeout(15_000),94    redirect: "follow",95    headers: {96      "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15",97      accept: "image/avif,image/webp,image/*,*/*;q=0.8",98      referer: `${origin}/`,99    },100  });101  if (!response.ok) throw new Error(`HTTP ${response.status}`);102  const length = Number(response.headers.get("content-length") ?? 0);103  if (length > MAX_BYTES) throw new Error("image trop volumineuse");104  const buffer = Buffer.from(await response.arrayBuffer());105  if (buffer.length > MAX_BYTES || buffer.length < 2_000) throw new Error("taille d'image invalide");106  return buffer;107}108109async function produce(id: string, width: ImageWidth): Promise<string | null> {110  const target = cachePath(id, width);111  if (fs.existsSync(target)) return target;112  const url = await sourceUrl(id);113  if (!url || !isPublicUrl(url)) return null;114  try {115    const original = await download(url);116    const image = sharp(original, { failOn: "none" }).rotate();117    const meta = await image.metadata();118    if (!meta.width || !meta.height || meta.width < 200 || meta.height < 150) throw new Error("image trop petite");119    // Redimensionnement proportionnel, sans agrandissement ; les métadonnées (EXIF, GPS) ne sont pas conservées.120    const output = await image.resize({ width, withoutEnlargement: true }).webp({ quality: 78, effort: 4 }).toBuffer();121    await fs.promises.mkdir(path.dirname(target), { recursive: true });122    const temp = `${target}.${process.pid}.${Date.now()}.tmp`;123    await fs.promises.writeFile(temp, output);124    await fs.promises.rename(temp, target);125    await sql`update question_images set status = 'ok', width = ${meta.width}, height = ${meta.height}, checked_at = now() where id = ${id} and status <> 'ok'`;126    return target;127  } catch {128    await sql`update question_images set status = 'failed', checked_at = now() where id = ${id}`.catch(() => {});129    return null;130  }131}132133/** Chemin du fichier WebP en cache (créé au besoin), ou `null` si la photo est indisponible. */134export function imageFile(id: string, width: ImageWidth): Promise<string | null> {135  const key = `${id}:${width}`;136  const running = inflight.get(key);137  if (running) return running;138  const task = produce(id, width).finally(() => inflight.delete(key));139  inflight.set(key, task);140  return task;141}142143export interface PrefetchReport {144  total: number;145  ok: number;146  failed: number;147}148149/** Met en cache les photographies d'une compétition : la partie ne dépend plus des sites d'origine. */150export async function prefetchCompetition(competitionId: string, widths: readonly ImageWidth[] = [960], concurrency = 6): Promise<PrefetchReport> {151  const images = await sql<{ id: string }[]>`152    select i.id from question_images i join questions q on q.id = i.question_id153    where q.competition_id = ${competitionId} order by i.position, q.position`;154  const report: PrefetchReport = { total: images.length, ok: 0, failed: 0 };155  let cursor = 0;156  await Promise.all(157    Array.from({ length: concurrency }, async () => {158      while (cursor < images.length) {159        const image = images[cursor++]!;160        let good = true;161        for (const width of widths) good = (await imageFile(image.id, width)) !== null && good;162        if (good) report.ok += 1;163        else report.failed += 1;164      }165    }),166  );167  return report;168}169170export const MIN_USABLE_IMAGES = 3;171172/**173 * Vérifie les photographies d'un brouillon et remplace les propriétés qui174 * n'en ont pas assez d'utilisables (au plus trois passes).175 */176export async function ensureBankImages(competitionId: string): Promise<{ report: PrefetchReport; replaced: number }> {177  const { replaceQuestion } = await import("./bank.ts");178  let replaced = 0;179  let report = await prefetchCompetition(competitionId, [960]);180  for (let pass = 0; pass < 3; pass++) {181    const weak = await sql<{ id: string }[]>`182      select q.id from questions q where q.competition_id = ${competitionId}183        and (select count(*) from question_images i where i.question_id = q.id and i.status = 'ok') < ${MIN_USABLE_IMAGES}`;184    if (weak.length === 0) break;185    for (const q of weak) {186      await replaceQuestion(competitionId, q.id);187      replaced += 1;188    }189    report = await prefetchCompetition(competitionId, [960]);190  }191  return { report, replaced };192}193194export async function cacheSize(): Promise<{ files: number; bytes: number }> {195  let files = 0;196  let bytes = 0;197  try {198    for (const dir of await fs.promises.readdir(config.imageStoragePath)) {199      const full = path.join(config.imageStoragePath, dir);200      const stat = await fs.promises.stat(full);201      if (!stat.isDirectory()) continue;202      for (const file of await fs.promises.readdir(full)) {203        files += 1;204        bytes += (await fs.promises.stat(path.join(full, file))).size;205      }206    }207  } catch {208    /* cache encore vide */209  }210  return { files, bytes };211}212
Files main
Menu

Theme