SPB Git

Repository Public

fetch-assets.mjs 8.5 KB 194 lines javascript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : agentilab-web8 * File             : scripts/fetch-assets.mjs9 * Module           : Scripts10 * Repository       : https://git.spboucher.ai/agentilab-web11 * Project Website  : Not specified12 * Created          : 2026-12-0513 * Last Modified    : 2026-12-0514 *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          : Proprietary34 *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// Rapatrie les actifs réels des produits depuis leurs sites publics officiels :44//   - ORIX : icône et première capture de chaque fiche de www.orixlab.dev45//   - Groupe Ka : symbole (favicon SVG ou apple-touch-icon) et capture de la page d'accueil46// Rien n'est fabriqué : chaque fichier vient d'une page publique, et sa source est47// consignée dans content/public/assets.generated.json (registre des actifs).48//49// Usage : node scripts/fetch-assets.mjs [--only orix|ka]50import { mkdir, writeFile } from 'node:fs/promises';51import path from 'node:path';52import { fileURLToPath } from 'node:url';53import sharp from 'sharp';54import { chromium } from '@playwright/test';5556const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');57const outDir = path.join(root, 'public', 'brands');58const only = process.argv.includes('--only') ? process.argv[process.argv.indexOf('--only') + 1] : null;59const today = new Date().toISOString().slice(0, 10);6061const ORIX_BASE = 'https://www.orixlab.dev';62const ORIX_APPS = [63  'arcade', 'astra', 'audio', 'calc', 'camera', 'clean', 'convert',64  'docs', 'maps', 'monitor', 'navigator', 'scan', 'sheet', 'sonata',65];66const KA_SITES = [67  // `shot` : hauteur de capture (px) ou null. La capture s'arrête au-dessus des68  // bandes d'annonces pour ne reproduire aucune photo de tiers ; les accueils qui69  // montrent d'emblée une photo de tiers, une marque tierce ou une adresse précise70  // (Vrai-Prix, Auto-Ka, Food-Ka) ne sont pas capturés.71  { id: 'groupe-ka', url: 'https://www.groupe-ka.com/', shot: 900 },72  { id: 'lou-ka', url: 'https://www.lou-ka.com/', shot: 655 },73  { id: 'immo-ka', url: 'https://www.immo-ka.com/', shot: 690 },74  { id: 'vrai-prix', url: 'https://www.vrai-prix.com/', shot: null },75  { id: 'valo-plex', url: 'https://www.valo-plex.com/', shot: 780 },76  { id: 'auto-ka', url: 'https://www.auto-ka.com/', shot: null },77  { id: 'food-ka', url: 'https://www.food-ka.com/', shot: null },78];7980const decode = (s) =>81  s.replace(/&amp;/g, '&').replace(/&#x27;/g, "'").replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>');8283async function get(url) {84  const res = await fetch(url, { redirect: 'follow' });85  if (!res.ok) throw new Error(`${url} → HTTP ${res.status}`);86  return res;87}8889/** Première image de capture (≠ icône) d'une fiche ORIX : { src, alt, width, height }. */90function firstScreenshot(html) {91  for (const tag of html.match(/<img[^>]+>/g) ?? []) {92    const alt = decode(/alt="([^"]*)"/.exec(tag)?.[1] ?? '');93    const width = Number(/width="(\d+)"/.exec(tag)?.[1] ?? 0);94    const src = /url=([^&"]+)&amp;w=/.exec(tag)?.[1];95    if (!src || width < 400 || /icon/i.test(alt)) continue;96    return { src: decodeURIComponent(src), alt };97  }98  return null;99}100101async function saveWebp(buffer, file, width) {102  const img = sharp(buffer).resize({ width, withoutEnlargement: true }).webp({ quality: 82 });103  const info = await img.toFile(file);104  return { width: info.width, height: info.height };105}106107const records = [];108109async function fetchOrix() {110  for (const slug of ORIX_APPS) {111    const dir = path.join(outDir, 'orix', slug);112    await mkdir(dir, { recursive: true });113    const [en, fr] = await Promise.all([114      get(`${ORIX_BASE}/apps/${slug}`).then((r) => r.text()),115      get(`${ORIX_BASE}/fr/apps/${slug}`).then((r) => r.text()),116    ]);117    const icon = Buffer.from(await (await get(`${ORIX_BASE}/apps/${slug}/icon.png`)).arrayBuffer());118    const iconDims = await saveWebp(icon, path.join(dir, 'icon.webp'), 256);119    records.push({120      id: `orix-${slug}-icon`, file: `/brands/orix/${slug}/icon.webp`, ...iconDims,121      source: `${ORIX_BASE}/apps/${slug}/icon.png`, retrievedAt: today,122      altFr: '', altEn: '', usage: 'product-icon',123    });124    const shotEn = firstScreenshot(en);125    const shotFr = firstScreenshot(fr);126    if (shotEn) {127      const shot = Buffer.from(await (await get(`${ORIX_BASE}${shotEn.src}`)).arrayBuffer());128      const dims = await saveWebp(shot, path.join(dir, 'screenshot.webp'), 1200);129      records.push({130        id: `orix-${slug}-screenshot`, file: `/brands/orix/${slug}/screenshot.webp`, ...dims,131        source: `${ORIX_BASE}${shotEn.src}`, retrievedAt: today,132        altFr: shotFr?.alt ?? shotEn.alt, altEn: shotEn.alt, usage: 'product-screenshot',133      });134    }135    console.log(`orix/${slug} ok${shotEn ? '' : ' (sans capture)'}`);136  }137}138139async function fetchKa() {140  const browser = await chromium.launch();141  const context = await browser.newContext({142    viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1, locale: 'fr-CA',143  });144  for (const site of KA_SITES) {145    const dir = path.join(outDir, 'ka', site.id);146    await mkdir(dir, { recursive: true });147    // Symbole : favicon SVG si présent, sinon apple-touch-icon, sinon rien.148    let mark = null;149    for (const candidate of ['favicon.svg', 'apple-touch-icon.png']) {150      try {151        const res = await get(new URL(candidate, site.url).href);152        const type = res.headers.get('content-type') ?? '';153        const buf = Buffer.from(await res.arrayBuffer());154        if (candidate.endsWith('.svg') && type.includes('svg')) {155          await writeFile(path.join(dir, 'mark.svg'), buf);156          mark = { file: `/brands/ka/${site.id}/mark.svg`, width: 64, height: 64 };157        } else if (type.includes('png')) {158          const dims = await saveWebp(buf, path.join(dir, 'mark.webp'), 180);159          mark = { file: `/brands/ka/${site.id}/mark.webp`, ...dims };160        } else continue;161        records.push({162          id: `${site.id}-mark`, ...mark, source: new URL(candidate, site.url).href,163          retrievedAt: today, altFr: '', altEn: '', usage: 'product-icon',164        });165        break;166      } catch { /* candidat suivant */ }167    }168    if (!site.shot) { console.log(`ka/${site.id} ok (symbole seul)`); continue; }169    const page = await context.newPage();170    await page.goto(site.url, { waitUntil: 'networkidle', timeout: 60000 }).catch(() => {});171    await page.waitForTimeout(1500);172    const png = await page.screenshot({ type: 'png', clip: { x: 0, y: 0, width: 1440, height: site.shot } });173    await page.close();174    const dims = await saveWebp(png, path.join(dir, 'screenshot.webp'), 1440);175    records.push({176      id: `${site.id}-screenshot`, file: `/brands/ka/${site.id}/screenshot.webp`, ...dims,177      source: site.url, retrievedAt: today, altFr: '', altEn: '', usage: 'product-screenshot',178    });179    console.log(`ka/${site.id} ok${mark ? '' : ' (sans symbole)'}`);180  }181  await browser.close();182}183184async function run(group, fn) {185  records.length = 0;186  await fn();187  const manifest = path.join(root, 'content', 'public', `assets.${group}.generated.json`);188  await mkdir(path.dirname(manifest), { recursive: true });189  await writeFile(manifest, JSON.stringify(records, null, 2) + '\n');190  console.log(`${records.length} actifs consignés dans ${path.relative(root, manifest)}`);191}192if (!only || only === 'orix') await run('orix', fetchOrix);193if (!only || only === 'ka') await run('ka', fetchKa);194
Files main
Menu

Theme