index.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. const argvStrings = ['lib-dir', 'inpx'];
  14. function showHelp() {
  15. console.log(utils.versionText(config));
  16. console.log(
  17. `Usage: ${config.name} [options]
  18. Options:
  19. --help Print ${config.name} command line options
  20. --lib-dir=<dirpath> Set library directory, default: the same as ${config.name} executable
  21. --inpx=<filepath> Set INPX collection file, default: the one that found in library dir
  22. --recreate Force recreation of the search database on start
  23. `
  24. );
  25. }
  26. async function init() {
  27. argv = require('minimist')(process.argv.slice(2), {string: argvStrings});
  28. //config
  29. const configManager = new (require('./config'))();//singleton
  30. await configManager.init();
  31. //configManager.userConfigFile = argv.config;
  32. await configManager.load();
  33. config = configManager.config;
  34. //logger
  35. const appLogger = new (require('./core/AppLogger'))();//singleton
  36. await appLogger.init(config);
  37. log = appLogger.log;
  38. //cli
  39. if (argv.help) {
  40. showHelp();
  41. ayncExit.exit(0);
  42. } else {
  43. log(utils.versionText(config));
  44. log('Initializing');
  45. }
  46. const libDir = argv['lib-dir'];
  47. if (libDir) {
  48. if (await fs.pathExists(libDir)) {
  49. config.libDir = libDir;
  50. } else {
  51. throw new Error(`Directory "${libDir}" not exists`);
  52. }
  53. } else {
  54. config.libDir = config.execDir;
  55. }
  56. if (argv.inpx) {
  57. if (await fs.pathExists(argv.inpx)) {
  58. config.inpxFile = argv.inpx;
  59. } else {
  60. throw new Error(`File "${argv.inpx}" not found`);
  61. }
  62. } else {
  63. const inpxFiles = [];
  64. await utils.findFiles((file) => {
  65. if (path.extname(file) == '.inpx')
  66. inpxFiles.push(file);
  67. }, config.libDir, false);
  68. if (inpxFiles.length) {
  69. if (inpxFiles.length == 1) {
  70. config.inpxFile = inpxFiles[0];
  71. } else {
  72. throw new Error(`Found more than one .inpx files: \n${inpxFiles.join('\n')}`);
  73. }
  74. } else {
  75. throw new Error(`No .inpx files found here: ${config.libDir}`);
  76. }
  77. }
  78. config.recreateDb = argv.recreate || false;
  79. //dirs
  80. await fs.ensureDir(config.dataDir);
  81. await fs.ensureDir(config.tempDir);
  82. await fs.emptyDir(config.tempDir);
  83. const appDir = `${config.publicDir}/app`;
  84. const appNewDir = `${config.publicDir}/app_new`;
  85. if (await fs.pathExists(appNewDir)) {
  86. await fs.remove(appDir);
  87. await fs.move(appNewDir, appDir);
  88. }
  89. }
  90. async function main() {
  91. const log = new (require('./core/AppLogger'))().log;//singleton
  92. //server
  93. const app = express();
  94. const server = http.createServer(app);
  95. const wss = new WebSocket.Server({ server, maxPayload: maxPayloadSize*1024*1024 });
  96. const serverConfig = Object.assign({}, config, config.server);
  97. let devModule = undefined;
  98. if (serverConfig.branch == 'development') {
  99. const devFileName = './dev.js'; //require ignored by pkg -50Mb executable size
  100. devModule = require(devFileName);
  101. devModule.webpackDevMiddleware(app);
  102. }
  103. app.use(compression({ level: 1 }));
  104. //app.use(express.json({limit: `${maxPayloadSize}mb`}));
  105. if (devModule)
  106. devModule.logQueries(app);
  107. initStatic(app, config);
  108. const { WebSocketController } = require('./controllers');
  109. new WebSocketController(wss, config);
  110. if (devModule) {
  111. devModule.logErrors(app);
  112. } else {
  113. app.use(function(err, req, res, next) {// eslint-disable-line no-unused-vars
  114. log(LM_ERR, err.stack);
  115. res.sendStatus(500);
  116. });
  117. }
  118. server.listen(serverConfig.port, serverConfig.ip, function() {
  119. log(`Server is ready on http://${serverConfig.ip}:${serverConfig.port}`);
  120. });
  121. }
  122. function initStatic(app, config) {// eslint-disable-line
  123. //загрузка файлов в /files
  124. //TODO
  125. app.use(express.static(config.publicDir, {
  126. maxAge: '30d',
  127. /*setHeaders: (res, filePath) => {
  128. if (path.dirname(filePath) == filesDir) {
  129. res.set('Content-Type', 'application/xml');
  130. res.set('Content-Encoding', 'gzip');
  131. }
  132. },*/
  133. }));
  134. }
  135. (async() => {
  136. try {
  137. await init();
  138. await main();
  139. } catch (e) {
  140. if (log)
  141. log(LM_FATAL, e.stack);
  142. else
  143. console.error(e.stack);
  144. ayncExit.exit(1);
  145. }
  146. })();