routes.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. const fs = require('fs-extra');
  2. const express = require('express');
  3. const multer = require('multer');
  4. const ReaderWorker = require('./core/Reader/ReaderWorker');//singleton
  5. const log = new (require('./core/AppLogger'))().log;//singleton
  6. const {
  7. ReaderController,
  8. WebSocketController,
  9. BookUpdateCheckerController,
  10. } = require('./controllers');
  11. const utils = require('./core/utils');
  12. function initRoutes(app, wss, config) {
  13. //эксклюзив для update_checker
  14. if (config.mode === 'book_update_checker') {
  15. new BookUpdateCheckerController(wss, config);
  16. return;
  17. }
  18. if (config.mode !== 'reader' && config.mode !== 'omnireader' && config.mode !== 'liberama')
  19. throw new Error(`Unknown server mode: ${config.mode}`);
  20. initStatic(app, config);
  21. const reader = new ReaderController(config);
  22. new WebSocketController(wss, config);
  23. //multer
  24. const storage = multer.diskStorage({
  25. destination: (req, file, cb) => {
  26. cb(null, config.uploadPublicDir);
  27. },
  28. filename: (req, file, cb) => {
  29. cb(null, utils.randomHexString(30));
  30. }
  31. });
  32. const upload = multer({ storage, limits: {fileSize: config.maxUploadFileSize} });
  33. //routes
  34. const routes = [
  35. ['POST', '/api/reader/upload-file', [upload.single('file'), reader.uploadFile.bind(reader)]],
  36. ];
  37. //to app
  38. for (let route of routes) {
  39. let callbacks = [];
  40. let [httpMethod, actionPath, controllers] = route;
  41. let controller = controllers;
  42. if (Array.isArray(controllers)) {
  43. controller = controllers[controllers.length - 1];
  44. callbacks = controllers.slice(0, -1);
  45. }
  46. const callback = async function(req, res) {
  47. try {
  48. const result = await controller(req, res);
  49. if (result !== false)
  50. res.send(result);
  51. } catch (e) {
  52. res.status(500).send({error: e.message});
  53. }
  54. };
  55. callbacks.push(callback);
  56. switch (httpMethod) {
  57. case 'GET' :
  58. app.get(actionPath, ...callbacks);
  59. break;
  60. case 'POST':
  61. app.post(actionPath, ...callbacks);
  62. break;
  63. default:
  64. throw new Error(`initRoutes error: unknown httpMethod: ${httpMethod}`);
  65. }
  66. }
  67. }
  68. function initStatic(app, config) {
  69. const readerWorker = new ReaderWorker(config);
  70. //восстановление файлов в /tmp и /upload из webdav-storage, при необходимости
  71. app.use('/tmp',
  72. async(req, res, next) => {
  73. if (req.method !== 'GET' && req.method !== 'HEAD') {
  74. return next();
  75. }
  76. const filePath = `${config.tempPublicDir}${req.path}`;
  77. //восстановим
  78. try {
  79. if (!await fs.pathExists(filePath))
  80. await readerWorker.restoreRemoteFile(req.path, '/tmp');
  81. } catch(e) {
  82. log(LM_ERR, `static::restoreRemoteFile ${filePath} > ${e.message}`);
  83. }
  84. return next();
  85. },
  86. express.static(config.tempPublicDir, {
  87. setHeaders: (res) => {
  88. res.set('Content-Type', 'application/xml');
  89. res.set('Content-Encoding', 'gzip');
  90. },
  91. })
  92. );
  93. app.use('/upload',
  94. async(req, res, next) => {
  95. if (req.method !== 'GET' && req.method !== 'HEAD') {
  96. return next();
  97. }
  98. const filePath = `${config.uploadPublicDir}${req.path}`;
  99. //восстановим
  100. try {
  101. if (!await fs.pathExists(filePath))
  102. await readerWorker.restoreRemoteFile(req.path, '/upload');
  103. } catch(e) {
  104. log(LM_ERR, `static::restoreRemoteFile ${filePath} > ${e.message}`);
  105. }
  106. return next();
  107. },
  108. express.static(config.uploadPublicDir)
  109. );
  110. app.use(express.static(config.publicDir));
  111. }
  112. module.exports = {
  113. initRoutes
  114. }