import path from 'path'; import Vibrant from 'node-vibrant'; import { NumistaType } from '@/types/numista'; import { asyncSpawn } from './async-spawn'; import puppeteer, { Page } from 'puppeteer'; import { writeFile } from 'fs/promises'; import { getTextureUrl } from '@/core/utils/texture-urls'; const baseDir = './public'; export const downloadFile = async (page: Page, url: string): Promise<[string, string, string?]> => { const filepath = url.split('catalogue')[1]; const folder = path.join(baseDir, filepath.split('/').slice(0, -1).join('/')); console.log(url); await asyncSpawn('mkdir', ['-p', folder]); const destination = path.join(baseDir, filepath); const pageRes = await page.goto(url, { waitUntil: 'load' }); if (pageRes) { await writeFile(destination, await pageRes.buffer()); } const destinationWebp = destination.replace(/\.\w*$/g, '.webp') await asyncSpawn('cwebp', [destination, '-o', destinationWebp]) let color: string | undefined; const palette = await Vibrant.from(destination).getPalette(); if (palette.Vibrant) { color = 'rgb(' + palette.Vibrant.rgb.join(',') + ')'; } return [destinationWebp, destination, color]; }; export const fetchTextures = async (type: NumistaType) => { try { const browser = await puppeteer.launch({ headless: false }); const page = await browser.newPage(); const texturesToBump: string[] = []; page.setViewport({ width: 1280, height: 926 }); if (type?.obverse?.picture) { const [destinationWebp, destination, color] = await downloadFile(page, type.obverse.picture); type.obverse.picture = destinationWebp.split('public')[1]; texturesToBump.push(`./public${destination.split('public')[1]}`); if (color) { type.color = color; } } if (type?.reverse?.picture) { const [destinationWebp, destination] = await downloadFile(page, type.reverse.picture); type.reverse.picture = destinationWebp.split('public')[1]; texturesToBump.push(`./public${destination.split('public')[1]}`); } if (type?.edge?.picture) { const [destinationWebp, destination] = await downloadFile(page, type.edge.picture); type.edge.picture = destinationWebp.split('public')[1]; await asyncSpawn('rm', [`./public${destination.split('public')[1]}`]) } await browser.close(); const bumpPngs = [] for (const texture of texturesToBump) { await asyncSpawn('./bin/generate-depth.sh', [texture]); const bumpTextureWebp = getTextureUrl(texture, 'bump') const bumpTexturePng = bumpTextureWebp.replace(/(\.[^/.]+)$/, '.png') bumpPngs.push(bumpTexturePng) await asyncSpawn('cwebp', [bumpTexturePng, '-o', bumpTextureWebp]) } await asyncSpawn('rm', [...texturesToBump,...bumpPngs]) return type; } catch (e) { console.error(e); return null; } };