index.js 6.6 KB

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