aboutsummaryrefslogtreecommitdiff
path: root/routes/api/public
diff options
context:
space:
mode:
authorBobby <[email protected]>2022-07-05 00:23:58 +0530
committerBobby <[email protected]>2022-07-05 00:23:58 +0530
commit406a35de9d0d37d20123a0a3e961614142c2cf3c (patch)
tree31299b83e59f02ad08051c7e21655e1895b79106 /routes/api/public
parentde994764b87d2716f951941f26a1044aaca63ed7 (diff)
downloadthatcomputerscientist-archived.tar.xz
thatcomputerscientist-archived.zip
Updarte Screenshot API as a Public Servicearchived
Diffstat (limited to 'routes/api/public')
-rw-r--r--routes/api/public/screenshot.js46
1 files changed, 46 insertions, 0 deletions
diff --git a/routes/api/public/screenshot.js b/routes/api/public/screenshot.js
new file mode 100644
index 00000000..6c8c1fe0
--- /dev/null
+++ b/routes/api/public/screenshot.js
@@ -0,0 +1,46 @@
+const router = require("express").Router();
+const puppeteer = require("puppeteer");
+const fs = require("fs");
+const yaml = require("yaml");
+const config = yaml.parse(fs.readFileSync("site.config.yml", "utf8"));
+
+router.get("/", async (req, res) => {
+ const width = parseInt(req.query.width) ? parseInt(req.query.width) : 1920;
+ const height = parseInt(req.query.height) ? parseInt(req.query.height) : 1080;
+ const url = req.query.url || config.url;
+ const format = req.query.format ? ['png', 'jpeg', 'webp'].includes(req.query.format) ? req.query.format : 'png' : 'png';
+ const fullpage = req.query.fullpage || true;
+
+ // Set screenshot options
+ const options = { type: format, fullPage: fullpage };
+
+ // Take a screenshot
+ const image = async (url, width, height, options) => {
+ const browser = await puppeteer.launch();
+ const page = await browser.newPage();
+ page.setViewport({ width, height });
+ // Go to the url
+ await page.goto(url, { waitUntil: "networkidle2" });
+ // Take a screenshot
+ const screenshot = await page.screenshot(options);
+ // Close the browser
+ await browser.close();
+ // Return the screenshot
+ return screenshot;
+ }
+
+ // Get the screenshot
+ image(url, width, height, options).then(screenshot => {
+ // Send the screenshot
+ res.setHeader("Content-Type", `image/${format}`);
+ res.send(screenshot);
+ }).catch(err => {
+ // Send an error
+ res.status(500).json({
+ message: "Error",
+ error: err
+ });
+ });
+});
+
+module.exports = router;