index.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. const fs = require('fs-extra');
  2. const path = require('path');
  3. const express = require('express');
  4. const compression = require('compression');
  5. const http = require('http');
  6. const WebSocket = require ('ws');
  7. const ayncExit = new (require('./core/AsyncExit'))();
  8. const utils = require('./core/utils');
  9. const maxPayloadSize = 50;//in MB
  10. let log;
  11. let config;
  12. let argv;
  13. let branch = '';
  14. const argvStrings = ['lib-dir', 'inpx'];
  15. function showHelp() {
  16. console.log(utils.versionText(config));
  17. console.log(
  18. `Usage: ${config.name} [options]
  19. Options:
  20. --help Print ${config.name} command line options
  21. --lib-dir=<dirpath> Set library directory, default: the same as ${config.name} executable's
  22. --inpx=<filepath> Set INPX collection file, default: the one that found in library dir
  23. --recreate Force recreation of the search database on start
  24. `
  25. );
  26. }
  27. async function init() {
  28. argv = require('minimist')(process.argv.slice(2), {string: argvStrings});
  29. //config
  30. const configManager = new (require('./config'))();//singleton
  31. await configManager.init();
  32. //configManager.userConfigFile = argv.config;
  33. await configManager.load();
  34. config = configManager.config;
  35. branch = config.branch;
  36. //logger
  37. const appLogger = new (require('./core/AppLogger'))();//singleton
  38. await appLogger.init(config);
  39. log = appLogger.log;
  40. //dirs
  41. await fs.ensureDir(config.dataDir);
  42. await fs.ensureDir(config.tempDir);
  43. await fs.emptyDir(config.tempDir);
  44. //web app
  45. const createWebApp = require('./createWebApp');
  46. await createWebApp(config);
  47. //cli
  48. if (argv.help) {
  49. showHelp();
  50. ayncExit.exit(0);
  51. } else {
  52. log(utils.versionText(config));
  53. log('Initializing');
  54. }
  55. const libDir = argv['lib-dir'];
  56. if (libDir) {
  57. if (await fs.pathExists(libDir)) {
  58. config.libDir = libDir;
  59. } else {
  60. throw new Error(`Directory "${libDir}" not exists`);
  61. }
  62. } else {
  63. config.libDir = config.execDir;
  64. }
  65. if (argv.inpx) {
  66. if (await fs.pathExists(argv.inpx)) {
  67. config.inpxFile = argv.inpx;
  68. } else {
  69. throw new Error(`File "${argv.inpx}" not found`);
  70. }
  71. } else {
  72. const inpxFiles = [];
  73. await utils.findFiles((file) => {
  74. if (path.extname(file) == '.inpx')
  75. inpxFiles.push(file);
  76. }, config.libDir, false);
  77. if (inpxFiles.length) {
  78. if (inpxFiles.length == 1) {
  79. config.inpxFile = inpxFiles[0];
  80. } else {
  81. throw new Error(`Found more than one .inpx files: \n${inpxFiles.join('\n')}`);
  82. }
  83. } else {
  84. throw new Error(`No .inpx files found here: ${config.libDir}`);
  85. }
  86. }
  87. config.recreateDb = argv.recreate || false;
  88. //app
  89. const appDir = `${config.publicDir}/app`;
  90. const appNewDir = `${config.publicDir}/app_new`;
  91. if (await fs.pathExists(appNewDir)) {
  92. await fs.remove(appDir);
  93. await fs.move(appNewDir, appDir);
  94. }
  95. }
  96. async function main() {
  97. const log = new (require('./core/AppLogger'))().log;//singleton
  98. //server
  99. const app = express();
  100. const server = http.createServer(app);
  101. const wss = new WebSocket.Server({ server, maxPayload: maxPayloadSize*1024*1024 });
  102. const serverConfig = Object.assign({}, config, config.server);
  103. let devModule = undefined;
  104. if (serverConfig.branch == 'development') {
  105. const devFileName = './dev.js'; //require ignored by pkg -50Mb executable size
  106. devModule = require(devFileName);
  107. devModule.webpackDevMiddleware(app);
  108. }
  109. app.use(compression({ level: 1 }));
  110. //app.use(express.json({limit: `${maxPayloadSize}mb`}));
  111. if (devModule)
  112. devModule.logQueries(app);
  113. initStatic(app, config);
  114. const { WebSocketController } = require('./controllers');
  115. new WebSocketController(wss, config);
  116. if (devModule) {
  117. devModule.logErrors(app);
  118. } else {
  119. app.use(function(err, req, res, next) {// eslint-disable-line no-unused-vars
  120. log(LM_ERR, err.stack);
  121. res.sendStatus(500);
  122. });
  123. }
  124. server.listen(serverConfig.port, serverConfig.ip, () => {
  125. log(`Server is ready on http://${serverConfig.ip}:${serverConfig.port}`);
  126. });
  127. }
  128. function initStatic(app, config) {
  129. const WebWorker = require('./core/WebWorker');//singleton
  130. const webWorker = new WebWorker(config);
  131. //загрузка или восстановление файлов в /files, при необходимости
  132. app.use(async(req, res, next) => {
  133. if ((req.method !== 'GET' && req.method !== 'HEAD') ||
  134. !(req.path.indexOf('/files/') === 0)
  135. ) {
  136. return next();
  137. }
  138. const publicPath = `${config.publicDir}${req.path}`;
  139. let downFileName = '';
  140. //восстановим
  141. try {
  142. if (!await fs.pathExists(publicPath)) {
  143. downFileName = await webWorker.restoreBookFile(publicPath);
  144. } else {
  145. downFileName = await webWorker.getDownFileName(publicPath);
  146. }
  147. } catch(e) {
  148. //quiet
  149. }
  150. if (downFileName)
  151. res.downFileName = downFileName;
  152. return next();
  153. });
  154. //заголовки при отдаче
  155. const filesDir = `${config.publicDir}/files`;
  156. app.use(express.static(config.publicDir, {
  157. maxAge: '30d',
  158. setHeaders: (res, filePath) => {
  159. if (path.dirname(filePath) == filesDir) {
  160. res.set('Content-Encoding', 'gzip');
  161. if (res.downFileName)
  162. res.set('Content-Disposition', `inline; filename*=UTF-8''${encodeURIComponent(res.downFileName)}`);
  163. }
  164. },
  165. }));
  166. }
  167. (async() => {
  168. try {
  169. await init();
  170. await main();
  171. } catch (e) {
  172. if (log)
  173. log(LM_FATAL, (branch == 'development' ? e.stack : e.message));
  174. else
  175. console.error(branch == 'development' ? e.stack : e.message);
  176. ayncExit.exit(1);
  177. }
  178. })();