const CONFIG = require('../src/config.js'); const PasteContent = require('../models/pasteContent.js').PasteContent; const QRCode = require("qrcode"); const { createCanvas, loadImage } = require("canvas"); async function createQrCode(url, params) { const width = params?.width || 500; const canvas = createCanvas(width, width); QRCode.toCanvas( canvas, url, { width: width, errorCorrectionLevel: "H", margin: 1, color: { dark: params?.dark || "#333", light: params?.light || "#eee" }, }); if (params?.centerImage) { const ctx = canvas.getContext("2d"); const img = await loadImage(params.centerImage); const sizeFactor = (width/3.5)/Math.max(img.width, img.height); ctx.drawImage(img, 0, 0, img.width, img.height, (width - img.width*sizeFactor) /2, (width - img.height*sizeFactor) /2, img.width * sizeFactor, img.height * sizeFactor); } return canvas.toBuffer(); } module.exports = { register: app => { // Params: // - s: size (in px) // - bg: bg color // - fg: fg color // - origin: to append to the url app.router.get("/:id/qrcode.png", async (req, res) => { if (!req.body.origin) return app.routerUtils.onPageNotFound(res); let entity = await app.databaseHelper.findOne(PasteContent, { publicId: req.params.id }); if (!entity) return app.routerUtils.onPageNotFound(res); const qrcode = await createQrCode(decodeURIComponent(req.body.origin) +"/x/" +entity.publicId +(req.body.rel ? ("?rel="+decodeURIComponent(req.body.rel)) : ""), { width: req.body.s ? Number.parseInt(req.body.s) : undefined, light: req.body.bg ? decodeURIComponent(req.body.bg) : undefined, dark: req.body.fg ? decodeURIComponent(req.body.fg) : undefined, }); res.writeHead(200, { "Content-Type": "image/png", "Content-Length": qrcode.length, "Cache-Control": "max-age=604800" }); // Cache=1 week res.end(qrcode); }); } };