index.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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
  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. //cli
  45. if (argv.help) {
  46. showHelp();
  47. ayncExit.exit(0);
  48. } else {
  49. log(utils.versionText(config));
  50. log('Initializing');
  51. }
  52. const libDir = argv['lib-dir'];
  53. if (libDir) {
  54. if (await fs.pathExists(libDir)) {
  55. config.libDir = libDir;
  56. } else {
  57. throw new Error(`Directory "${libDir}" not exists`);
  58. }
  59. } else {
  60. config.libDir = config.execDir;
  61. }
  62. if (argv.inpx) {
  63. if (await fs.pathExists(argv.inpx)) {
  64. config.inpxFile = argv.inpx;
  65. } else {
  66. throw new Error(`File "${argv.inpx}" not found`);
  67. }
  68. } else {
  69. const inpxFiles = [];
  70. await utils.findFiles((file) => {
  71. if (path.extname(file) == '.inpx')
  72. inpxFiles.push(file);
  73. }, config.libDir, false);
  74. if (inpxFiles.length) {
  75. if (inpxFiles.length == 1) {
  76. config.inpxFile = inpxFiles[0];
  77. } else {
  78. throw new Error(`Found more than one .inpx files: \n${inpxFiles.join('\n')}`);
  79. }
  80. } else {
  81. throw new Error(`No .inpx files found here: ${config.libDir}`);
  82. }
  83. }
  84. config.recreateDb = argv.recreate || false;
  85. //app
  86. const appDir = `${config.publicDir}/app`;
  87. const appNewDir = `${config.publicDir}/app_new`;
  88. if (await fs.pathExists(appNewDir)) {
  89. await fs.remove(appDir);
  90. await fs.move(appNewDir, appDir);
  91. }
  92. }
  93. async function main() {
  94. const log = new (require('./core/AppLogger'))().log;//singleton
  95. //server
  96. const app = express();
  97. const server = http.createServer(app);
  98. const wss = new WebSocket.Server({ server, maxPayload: maxPayloadSize*1024*1024 });
  99. const serverConfig = Object.assign({}, config, config.server);
  100. let devModule = undefined;
  101. if (serverConfig.branch == 'development') {
  102. const devFileName = './dev.js'; //require ignored by pkg -50Mb executable size
  103. devModule = require(devFileName);
  104. devModule.webpackDevMiddleware(app);
  105. }
  106. app.use(compression({ level: 1 }));
  107. //app.use(express.json({limit: `${maxPayloadSize}mb`}));
  108. if (devModule)
  109. devModule.logQueries(app);
  110. initStatic(app, config);
  111. const { WebSocketController } = require('./controllers');
  112. new WebSocketController(wss, config);
  113. if (devModule) {
  114. devModule.logErrors(app);
  115. } else {
  116. app.use(function(err, req, res, next) {// eslint-disable-line no-unused-vars
  117. log(LM_ERR, err.stack);
  118. res.sendStatus(500);
  119. });
  120. }
  121. server.listen(serverConfig.port, serverConfig.ip, () => {
  122. log(`Server is ready on http://${serverConfig.ip}:${serverConfig.port}`);
  123. });
  124. }
  125. function initStatic(app, config) {
  126. const WebWorker = require('./core/WebWorker');//singleton
  127. const webWorker = new WebWorker(config);
  128. //загрузка или восстановление файлов в /files, при необходимости
  129. app.use(async(req, res, next) => {
  130. if ((req.method !== 'GET' && req.method !== 'HEAD') ||
  131. !(req.path.indexOf('/files/') === 0)
  132. ) {
  133. return next();
  134. }
  135. const publicPath = `${config.publicDir}${req.path}`;
  136. let downFileName = '';
  137. //восстановим
  138. try {
  139. if (!await fs.pathExists(publicPath)) {
  140. downFileName = await webWorker.restoreBookFile(publicPath);
  141. } else {
  142. downFileName = await webWorker.getDownFileName(publicPath);
  143. }
  144. } catch(e) {
  145. //quiet
  146. }
  147. if (downFileName)
  148. res.downFileName = downFileName;
  149. return next();
  150. });
  151. //заголовки при отдаче
  152. const filesDir = `${config.publicDir}/files`;
  153. app.use(express.static(config.publicDir, {
  154. maxAge: '30d',
  155. setHeaders: (res, filePath) => {
  156. if (path.dirname(filePath) == filesDir) {
  157. res.set('Content-Encoding', 'gzip');
  158. if (res.downFileName)
  159. res.set('Content-Disposition', `inline; filename*=UTF-8''${encodeURIComponent(res.downFileName)}`);
  160. }
  161. },
  162. }));
  163. }
  164. (async() => {
  165. try {
  166. await init();
  167. await main();
  168. } catch (e) {
  169. if (log)
  170. log(LM_FATAL, (branch == 'development' ? e.stack : e.message));
  171. else
  172. console.error(branch == 'development' ? e.stack : e.message);
  173. ayncExit.exit(1);
  174. }
  175. })();