index.js 6.9 KB

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