screenshot-service/index.js

92 lines
2.5 KiB
JavaScript
Raw Normal View History

2022-04-24 17:24:27 +02:00
const { v4: uuid } = require("uuid");
var serve = require("koa-static");
const Koa = require("koa");
const Router = require("@koa/router");
const mount = require("koa-mount");
const qs = require("qs");
const { Readable } = require("stream");
const { spawn } = require("child_process");
const router = new Router();
// response
const app = new Koa();
const static = new Koa();
static.use(serve("./static"));
app.use(mount("/static", static));
function attach(docker_id, output_stream) {
// to prevent browser timeout
const interval = setInterval(() => output_stream.push("<span></span>"), 500);
const task = spawn("docker", ["logs", "-f", docker_id]);
2022-04-24 19:57:01 +02:00
task.stdout.on("data", (d) => {
output_stream.push(d);
console.log("DATA!", d.toString());
});
2022-04-24 20:04:45 +02:00
task.stderr.on("data", (d) => {
/* output_stream.push(d); */
console.log("STDERR!", d.toString());
});
2022-04-24 19:57:01 +02:00
task.stdout.on("error", (d) => {
output_stream.push(d);
});
2022-04-24 17:24:27 +02:00
task.on("close", () => {
2022-04-24 20:35:24 +02:00
output_stream.push("</pre>");
output_stream.push(/* HTML */ `<script>
clearInterval(window.interval);
</script>`);
clearInterval(interval);
output_stream.push(null);
2022-04-24 17:24:27 +02:00
});
}
router.get("/", async (ctx) => {
const s = new Readable({ read() {} });
// stream data
ctx.response.set("content-type", "txt/html");
ctx.type = "html"; // <-- THIS is the important step!
ctx.body = s;
ctx.body.push("<!doctype html>");
2022-04-24 19:57:01 +02:00
const id = uuid();
ctx.body.push(
`<img id="preview" width="1080" height="608" src="/static/${id}/preview.png?id=0"/><br/>`
);
ctx.body.push(/* HTML */ `<script>
2022-04-24 20:35:24 +02:00
window.interval = setInterval(() => (preview.src = preview.src + "0"), 500);
2022-04-24 19:57:01 +02:00
</script>`);
2022-04-24 17:24:27 +02:00
const params = qs.parse(ctx.querystring);
s.push(`Got request to screenshot ${params.url}<pre>`);
let docker_id = "";
2022-04-24 18:58:08 +02:00
if (!params.url) {
ctx.body = "specify url!";
return;
}
2022-04-24 17:24:27 +02:00
const starter = spawn(
"docker",
[
"run",
"-i",
"-d",
"-v",
`${process.cwd()}/static:/opt/static`,
"headless-fox",
"./script3.sh",
2022-04-24 18:58:54 +02:00
`{"url": "${params.url}", "third_party_domains": ["hotjar.com", "cookielaw.org", "facebook.com", "gemius.pl"]}`,
2022-04-24 17:24:27 +02:00
id,
],
{ cwd: process.cwd() }
);
starter.stdout.on("data", (data) => {
docker_id += data.toString().replace(/\n/g, "");
});
starter.on("close", () => {
ctx.body.push("spawned " + docker_id);
attach(docker_id, ctx.body);
});
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);