assetRouter.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const express = require("express");
  2. var fs = require('fs');
  3. var path = require('path');
  4. const cors = require('cors');
  5. const router = express.Router();
  6. var mime = {
  7. html: 'text/html',
  8. txt: 'text/plain',
  9. css: 'text/css',
  10. gif: 'image/gif',
  11. jpg: 'image/jpeg',
  12. png: 'image/png',
  13. svg: 'image/svg+xml',
  14. js: 'application/javascript',
  15. mp4: 'video/mp4',
  16. ogv: 'video/ogg'
  17. };
  18. // Read (GET) an asset
  19. router.get("/images/projects/:projectId/:imagePath", async (req, res) => {
  20. var reqpath = req.url.toString().split('?')[0];
  21. var file = "./assets" + reqpath.replace(/\/$/, '');
  22. var scale = parseInt(req.query.w);
  23. // Serve a scaled image if width has been specified.
  24. if (parseInt(req.query.w) >= 0){
  25. var width = 100;
  26. for (var i = 100; i < 1000; i += 100){
  27. width = i;
  28. if (width >= scale) break;
  29. }
  30. file = file.replace("/assets/images/", "/assets/images_scaled/x" + width + "/");
  31. }
  32. var type = mime[path.extname(file).slice(1)] || 'text/plain';
  33. var s = fs.createReadStream(file);
  34. s.on('open', function () {
  35. res.setHeader('Content-Type', type);
  36. res.setHeader('Accept-Ranges', 'bytes');
  37. res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
  38. s.pipe(res);
  39. });
  40. s.on('error', function () {
  41. res.setHeader('Content-Type', 'text/plain');
  42. res.statusCode = 404;
  43. res.end('Not found');
  44. });
  45. });
  46. router.get("/images/profile/:imagePath", async (req, res) => {
  47. var reqpath = req.url.toString().split('?')[0];
  48. var file = "./assets" + reqpath.replace(/\/$/, '');
  49. var scale = parseInt(req.query.w);
  50. // Serve a scaled image if width has been specified.
  51. if (parseInt(req.query.w) >= 0){
  52. var width = 100;
  53. for (var i = 100; i < 1000; i += 100){
  54. width = i;
  55. if (width >= scale) break;
  56. }
  57. file = file.replace("/assets/images/", "/assets/images_scaled/x" + width + "/");
  58. }
  59. var type = mime[path.extname(file).slice(1)] || 'text/plain';
  60. var s = fs.createReadStream(file);
  61. s.on('open', function () {
  62. res.setHeader('Content-Type', type);
  63. res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
  64. s.pipe(res);
  65. });
  66. s.on('error', function () {
  67. res.setHeader('Content-Type', 'text/plain');
  68. res.statusCode = 404;
  69. res.end('Not found');
  70. });
  71. });
  72. module.exports = router;