index.js 6.6 KB

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