screenshot-service/request.js

76 lines
1.8 KiB
JavaScript

const { q, requests } = require("./memory");
const DOCKER_ARGS = require("./docker-args");
const { v4: uuid } = require("uuid");
const { promises: fs } = require("fs");
const { spawn } = require("child_process");
const { resolve } = require("path");
module.exports = class ScreenshotRequest {
constructor(url, domains) {
this.url = url;
this.domains = domains;
this.id = uuid();
this.status = "waiting";
this.output = "";
this.images = [];
q.push(async () => {
return this.exec();
});
requests[this.id] = this;
}
async getImages() {
try {
const files = await fs.readdir(resolve(__dirname, "./static/" + this.id));
return files.filter((file) => file.match(/.final.png$/));
} catch (e) {
return [];
}
}
async getJSON() {
return {
url: this.url,
domains: this.domains,
id: this.id,
status: this.status,
/* output: this.output, */
files: await this.getImages(),
};
}
async exec() {
return new Promise((resolve, reject) => {
this.status = "running";
this.process = spawn(
"docker",
[
...DOCKER_ARGS,
JSON.stringify({
url: this.url,
third_party_domains: this.domains,
}),
this.id,
],
{ cwd: process.cwd() }
);
this.process.on("close", (exitCode) => {
this.status = "finished";
if (exitCode === 0) {
resolve();
} else {
reject();
}
});
this.process.stdout.on("data", (d) => {
this.output += d.toString();
/* console.log("DATA!", d.toString()); */
});
this.process.stderr.on("data", (d) => {
this.output += d.toString();
/* console.log("STDERR!", d.toString()); */
});
});
}
};