qrcode.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const CONFIG = require('../src/config.js');
  2. const PasteContent = require('../models/pasteContent.js').PasteContent;
  3. const QRCode = require("qrcode");
  4. const { createCanvas, loadImage } = require("canvas");
  5. async function createQrCode(url, params) {
  6. const width = params?.width || 500;
  7. const canvas = createCanvas(width, width);
  8. QRCode.toCanvas(
  9. canvas,
  10. url,
  11. {
  12. width: width,
  13. errorCorrectionLevel: "H",
  14. margin: 1,
  15. color: {
  16. dark: params?.dark || "#333",
  17. light: params?.light || "#eee"
  18. },
  19. });
  20. if (params?.centerImage) {
  21. const ctx = canvas.getContext("2d");
  22. const img = await loadImage(params.centerImage);
  23. const sizeFactor = (width/3.5)/Math.max(img.width, img.height);
  24. 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);
  25. }
  26. return canvas.toBuffer();
  27. }
  28. module.exports = {
  29. register: app => {
  30. // Params:
  31. // - s: size (in px)
  32. // - bg: bg color
  33. // - fg: fg color
  34. // - origin: to append to the url
  35. app.router.get("/:id/qrcode.png", async (req, res) => {
  36. if (!req.body.origin)
  37. return app.routerUtils.onPageNotFound(res);
  38. let entity = await app.databaseHelper.findOne(PasteContent, { publicId: req.params.id });
  39. if (!entity)
  40. return app.routerUtils.onPageNotFound(res);
  41. const qrcode = await createQrCode(decodeURIComponent(req.body.origin) +"/x/" +entity.publicId +(req.body.rel ? ("?rel="+decodeURIComponent(req.body.rel)) : ""), {
  42. width: req.body.s ? Number.parseInt(req.body.s) : undefined,
  43. light: req.body.bg ? decodeURIComponent(req.body.bg) : undefined,
  44. dark: req.body.fg ? decodeURIComponent(req.body.fg) : undefined,
  45. });
  46. res.writeHead(200, { "Content-Type": "image/png", "Content-Length": qrcode.length, "Cache-Control": "max-age=604800" }); // Cache=1 week
  47. res.end(qrcode);
  48. });
  49. }
  50. };