const { q, requests } = require("./memory"); const DOCKER_ARGS = require("./docker-args"); const { v4: uuid } = require("uuid"); const { spawn } = require("child_process"); module.exports = class ScreenshotRequest { constructor(url, domains) { this.url = url; this.domains = domains; this.id = uuid(); this.status = "waiting"; this.output = ""; this.images = []; this.request_time = Date.now(); this.started_time = null; this.finished_time = null; this.processing_took = null; this.waiting_took = null; q.push(async () => { return this.exec(); }); requests[this.id] = this; } async getJSON() { return { url: this.url, domains: this.domains, id: this.id, status: this.status, output: this.output, images: this.images, request_time: this.request_time, started_time: this.started_time, finished_time: this.finished_time, processing_took: this.processing_took, waiting_took: this.waiting_took, elapsed_time_s: Math.round( ((this.status === "finished" ? this.finished_time : Date.now()) - this.request_time) / 1000 ), }; } setFinished() { this.status = "finished"; this.finished_time = Date.now(); this.processing_took = this.finished_time - this.started_time; this.waiting_took = this.started_time - this.request_time; } async exec() { this.started_time = Date.now(); 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.setFinished(); if (exitCode === 0) { resolve(); } else { reject(); } }); this.process.stdout.on("data", (d) => { try { const parsed = JSON.parse(d.toString()); if (parsed.new_file) { this.images.push(parsed.new_file); } } catch (e) {} this.output += d.toString(); /* console.log("DATA!", d.toString()); */ }); this.process.stderr.on("data", (d) => { this.output += d.toString(); /* console.log("STDERR!", d.toString()); */ }); }); } };