2022-07-06 02:41:27 +02:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
const path = require("path");
|
|
|
|
const fs = require("fs");
|
|
|
|
const os = require("os");
|
|
|
|
|
|
|
|
const phin = require("phin");
|
|
|
|
|
|
|
|
const a = require("./Ansi.js");
|
2024-05-19 17:34:25 +02:00
|
|
|
var pretty_ms = null;
|
2022-07-06 02:41:27 +02:00
|
|
|
|
|
|
|
class FileFetcher {
|
|
|
|
#cache = [];
|
|
|
|
|
|
|
|
#pkg_obj = null;
|
|
|
|
|
|
|
|
constructor() {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
fetch_file(url) {
|
|
|
|
let target_client = path.join(`/img`, path.basename(url));
|
|
|
|
|
|
|
|
if(this.#cache.includes(url)) return target_client;
|
|
|
|
|
|
|
|
this.#cache.push(url);
|
|
|
|
|
|
|
|
this.download_file(url); // Returns a promise! We fire-and-forget it though 'cause this function *must* be synchronous :-/
|
|
|
|
|
|
|
|
return target_client;
|
|
|
|
}
|
|
|
|
|
|
|
|
async download_file(url) {
|
|
|
|
const time_start = new Date();
|
2024-05-19 17:34:25 +02:00
|
|
|
if(pretty_ms === null)
|
|
|
|
pretty_ms = (await import("pretty-ms")).default;
|
2022-07-06 02:41:27 +02:00
|
|
|
|
|
|
|
if(this.#pkg_obj === null) {
|
|
|
|
this.#pkg_obj = JSON.parse(await fs.promises.readFile(
|
|
|
|
path.join(path.dirname(__dirname), "package.json"), "utf8"
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
|
|
|
let target_download = path.join(`_site/img`, path.basename(url));
|
|
|
|
|
|
|
|
const response = await phin({
|
|
|
|
url,
|
|
|
|
headers: {
|
2022-08-06 16:17:16 +02:00
|
|
|
"user-agent": `WorldEditAdditionsStaticBuilder/${this.#pkg_obj.version} (Node.js/${process.version}; ${os.platform()} ${os.arch()}) eleventy/${this.#pkg_obj.dependencies["@11ty/eleventy"].replace(/\^/, "")}`
|
2022-07-06 02:41:27 +02:00
|
|
|
},
|
|
|
|
followRedirects: true,
|
|
|
|
parse: 'none' // Returns a Buffer
|
|
|
|
// If we stream and pipe to a file, the build never ends :-/
|
|
|
|
});
|
|
|
|
|
|
|
|
await fs.promises.writeFile(target_download, response.body);
|
|
|
|
|
|
|
|
console.log([
|
|
|
|
`${a.fred}${a.hicol}FETCH_FILE${a.reset}`,
|
|
|
|
`${a.fyellow}${pretty_ms(new Date() - time_start)}${a.reset}`,
|
|
|
|
`${a.fgreen}${url}${a.reset}`
|
|
|
|
].join("\t"));
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = FileFetcher;
|