Files
coins/bin/fetch-textures.mjs
T
2023-09-12 13:16:07 +01:00

87 lines
2.5 KiB
JavaScript

import { readFile, readdir, writeFile } from "fs/promises";
import process from "process";
import path from "path";
import Vibrant from "node-vibrant";
import { spawn } from "child_process";
const baseDir = process.argv[2];
const asyncSpawn = (command, args) => {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
stdio: "inherit",
});
child.on("error", reject);
child.stdout?.on("data", process.stdout.write);
child.stderr?.on("data", process.stderr.write);
child.on("close", (code) => {
if (code === 0) {
resolve(code);
} else {
reject(code);
}
});
});
};
const downloadFile = async (url) => {
const filepath = url.split("catalogue")[1];
const folder = path.join(
baseDir,
"..",
filepath.split("/").slice(0, -1).join("/"),
);
await asyncSpawn("mkdir", ["-p", folder]);
const destination = path.join(baseDir, "..", filepath);
await asyncSpawn("curl", [url, "--output", destination]);
return destination;
};
const processCoin = async (country, filename) => {
console.log(" ", filename);
const filepath = path.join(baseDir, country, filename);
try {
const coin = JSON.parse(await readFile(filepath, { encoding: "utf-8" }));
if (coin?.obverse?.picture) {
const destination = await downloadFile(coin.obverse.picture);
coin.obverse.picture = destination.split("public")[1];
const palette = await Vibrant.from(destination).getPalette();
coin.color = "rgb(" + palette.Vibrant.rgb.join(",") + ")";
}
if (coin?.reverse?.picture) {
const destination = await downloadFile(coin.reverse.picture);
coin.reverse.picture = destination.split("public")[1];
}
if (coin?.edge?.picture) {
const destination = await downloadFile(coin.edge.picture);
coin.edge.picture = destination.split("public")[1];
}
await writeFile(filepath, JSON.stringify(coin, null, 2));
} catch (e) {
console.log("\nfailed for", filename, "\n");
console.error(e);
}
};
const processCountry = async (country) => {
console.log(country);
const coins = (await readdir(path.join(baseDir, country))).filter((file) =>
file.endsWith(".json"),
);
for (const coin of coins) {
await processCoin(country, coin);
}
};
const countries = (await readdir(baseDir, { withFileTypes: true }))
.filter((file) => file.isDirectory())
.map(({ name }) => name);
for (const country of countries) {
await processCountry(country);
}