index.js 4.8 KB

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