Files
coins/bin/fetch-textures.ts
T

60 lines
1.7 KiB
TypeScript

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";
const baseDir = "./public";
export const downloadFile = async (page: Page, url: 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());
}
return destination;
};
export const fetchTextures = async (type: NumistaType) => {
try {
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
page.setViewport({ width: 1280, height: 926 });
if (type?.obverse?.picture) {
const destination = await downloadFile(page, type.obverse.picture);
type.obverse.picture = destination.split("public")[1];
const palette = await Vibrant.from(destination).getPalette();
if (palette.Vibrant) {
type.color = "rgb(" + palette.Vibrant.rgb.join(",") + ")";
}
}
if (type?.reverse?.picture) {
const destination = await downloadFile(page, type.reverse.picture);
type.reverse.picture = destination.split("public")[1];
}
if (type?.edge?.picture) {
const destination = await downloadFile(page, type.edge.picture);
type.edge.picture = destination.split("public")[1];
}
await browser.close();
return type;
} catch (e) {
console.error(e);
return null;
}
};