WebWorker.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. const os = require('os');
  2. const path = require('path');
  3. const fs = require('fs-extra');
  4. const _ = require('lodash');
  5. const ZipReader = require('./ZipReader');
  6. const WorkerState = require('./WorkerState');//singleton
  7. const { JembaDb, JembaDbThread } = require('jembadb');
  8. const DbCreator = require('./DbCreator');
  9. const DbSearcher = require('./DbSearcher');
  10. const InpxHashCreator = require('./InpxHashCreator');
  11. const RemoteLib = require('./RemoteLib');//singleton
  12. const asyncExit = new (require('./AsyncExit'))();
  13. const log = new (require('./AppLogger'))().log;//singleton
  14. const utils = require('./utils');
  15. const genreTree = require('./genres');
  16. const Fb2Helper = require('./fb2/Fb2Helper');
  17. //server states
  18. const ssNormal = 'normal';
  19. const ssDbLoading = 'db_loading';
  20. const ssDbCreating = 'db_creating';
  21. const stateToText = {
  22. [ssNormal]: '',
  23. [ssDbLoading]: 'Загрузка поисковой базы',
  24. [ssDbCreating]: 'Создание поисковой базы',
  25. };
  26. const cleanDirPeriod = 60*60*1000;//каждый час
  27. //singleton
  28. let instance = null;
  29. class WebWorker {
  30. constructor(config) {
  31. if (!instance) {
  32. this.config = config;
  33. this.workerState = new WorkerState();
  34. this.remoteLib = null;
  35. if (config.remoteLib) {
  36. this.remoteLib = new RemoteLib(config);
  37. }
  38. this.inpxHashCreator = new InpxHashCreator(config);
  39. this.fb2Helper = new Fb2Helper();
  40. this.inpxFileHash = '';
  41. this.wState = this.workerState.getControl('server_state');
  42. this.myState = '';
  43. this.db = null;
  44. this.dbSearcher = null;
  45. asyncExit.add(this.closeDb.bind(this));
  46. this.loadOrCreateDb();//no await
  47. this.periodicLogServerStats();//no await
  48. const dirConfig = [
  49. {
  50. dir: config.filesDir,
  51. maxSize: config.maxFilesDirSize,
  52. },
  53. ];
  54. this.periodicCleanDir(dirConfig);//no await
  55. this.periodicCheckInpx();//no await
  56. instance = this;
  57. }
  58. return instance;
  59. }
  60. checkMyState() {
  61. if (this.myState != ssNormal)
  62. throw new Error('server_busy');
  63. }
  64. setMyState(newState, workerState = {}) {
  65. this.myState = newState;
  66. this.wState.set(Object.assign({}, workerState, {
  67. state: newState,
  68. serverMessage: stateToText[newState]
  69. }));
  70. }
  71. async closeDb() {
  72. if (this.db) {
  73. await this.db.unlock();
  74. this.db = null;
  75. }
  76. }
  77. async createDb(dbPath) {
  78. this.setMyState(ssDbCreating);
  79. log('Searcher DB create start');
  80. const config = this.config;
  81. if (await fs.pathExists(dbPath))
  82. throw new Error(`createDb.pathExists: ${dbPath}`);
  83. const db = new JembaDbThread();
  84. await db.lock({
  85. dbPath,
  86. create: true,
  87. softLock: true,
  88. tableDefaults: {
  89. cacheSize: config.dbCacheSize,
  90. },
  91. });
  92. try {
  93. const dbCreator = new DbCreator(config);
  94. await dbCreator.run(db, (state) => {
  95. this.setMyState(ssDbCreating, state);
  96. if (state.fileName)
  97. log(` load ${state.fileName}`);
  98. if (state.recsLoaded)
  99. log(` processed ${state.recsLoaded} records`);
  100. if (state.job)
  101. log(` ${state.job}`);
  102. });
  103. log('Searcher DB successfully created');
  104. } finally {
  105. await db.unlock();
  106. }
  107. }
  108. async loadOrCreateDb(recreate = false, iteration = 0) {
  109. this.setMyState(ssDbLoading);
  110. try {
  111. const config = this.config;
  112. const dbPath = `${config.dataDir}/db`;
  113. this.inpxFileHash = await this.inpxHashCreator.getInpxFileHash();
  114. //проверим полный InxpHash (включая фильтр и версию БД)
  115. //для этого заглянем в конфиг внутри БД, если он есть
  116. if (!(config.recreateDb || recreate) && await fs.pathExists(dbPath)) {
  117. const newInpxHash = await this.inpxHashCreator.getHash();
  118. const tmpDb = new JembaDb();
  119. await tmpDb.lock({dbPath, softLock: true});
  120. try {
  121. await tmpDb.open({table: 'config'});
  122. const rows = await tmpDb.select({table: 'config', where: `@@id('inpxHash')`});
  123. if (!rows.length || newInpxHash !== rows[0].value)
  124. throw new Error('inpx file: changes found on start, recreating DB');
  125. } catch (e) {
  126. log(LM_WARN, e.message);
  127. recreate = true;
  128. } finally {
  129. await tmpDb.unlock();
  130. }
  131. }
  132. //удалим БД если нужно
  133. if (config.recreateDb || recreate)
  134. await fs.remove(dbPath);
  135. //пересоздаем БД из INPX если нужно
  136. if (!await fs.pathExists(dbPath)) {
  137. await this.createDb(dbPath);
  138. utils.freeMemory();
  139. }
  140. //загружаем БД
  141. this.setMyState(ssDbLoading);
  142. log('Searcher DB loading');
  143. const db = new JembaDbThread();//в отдельном потоке
  144. await db.lock({
  145. dbPath,
  146. softLock: true,
  147. tableDefaults: {
  148. cacheSize: config.dbCacheSize,
  149. },
  150. });
  151. try {
  152. //открываем таблицы
  153. await db.openAll({exclude: ['author_id', 'series_id', 'title_id', 'book']});
  154. const bookCacheSize = 500;
  155. await db.open({
  156. table: 'book',
  157. cacheSize: (config.lowMemoryMode || config.dbCacheSize > bookCacheSize ? config.dbCacheSize : bookCacheSize)
  158. });
  159. } catch(e) {
  160. log(LM_ERR, `Database error: ${e.message}`);
  161. if (iteration < 1) {
  162. log('Recreating DB');
  163. await this.loadOrCreateDb(true, iteration + 1);
  164. } else
  165. throw e;
  166. return;
  167. }
  168. //поисковый движок
  169. this.dbSearcher = new DbSearcher(config, db);
  170. await this.dbSearcher.init();
  171. //stuff
  172. db.wwCache = {};
  173. this.db = db;
  174. this.setMyState(ssNormal);
  175. log('Searcher DB ready');
  176. this.logServerStats();
  177. } catch (e) {
  178. log(LM_FATAL, e.message);
  179. asyncExit.exit(1);
  180. }
  181. }
  182. async recreateDb() {
  183. this.setMyState(ssDbCreating);
  184. if (this.dbSearcher) {
  185. await this.dbSearcher.close();
  186. this.dbSearcher = null;
  187. }
  188. await this.closeDb();
  189. await this.loadOrCreateDb(true);
  190. }
  191. async dbConfig() {
  192. this.checkMyState();
  193. const db = this.db;
  194. if (!db.wwCache.config) {
  195. const rows = await db.select({table: 'config'});
  196. const config = {};
  197. for (const row of rows) {
  198. config[row.id] = row.value;
  199. }
  200. db.wwCache.config = config;
  201. }
  202. return db.wwCache.config;
  203. }
  204. async search(from, query) {
  205. this.checkMyState();
  206. const result = await this.dbSearcher.search(from, query);
  207. const config = await this.dbConfig();
  208. result.inpxHash = (config.inpxHash ? config.inpxHash : '');
  209. return result;
  210. }
  211. async opdsQuery(from, query) {
  212. this.checkMyState();
  213. return await this.dbSearcher.opdsQuery(from, query);
  214. }
  215. async getAuthorBookList(authorId, author) {
  216. this.checkMyState();
  217. return await this.dbSearcher.getAuthorBookList(authorId, author);
  218. }
  219. async getAuthorSeriesList(authorId) {
  220. this.checkMyState();
  221. return await this.dbSearcher.getAuthorSeriesList(authorId);
  222. }
  223. async getSeriesBookList(series) {
  224. this.checkMyState();
  225. return await this.dbSearcher.getSeriesBookList(series);
  226. }
  227. async getGenreTree() {
  228. this.checkMyState();
  229. const config = await this.dbConfig();
  230. let result;
  231. const db = this.db;
  232. if (!db.wwCache.genres) {
  233. const genres = _.cloneDeep(genreTree);
  234. const last = genres[genres.length - 1];
  235. const genreValues = new Set();
  236. for (const section of genres) {
  237. for (const g of section.value)
  238. genreValues.add(g.value);
  239. }
  240. //добавим к жанрам те, что нашлись при парсинге
  241. const genreParsed = new Set();
  242. let rows = await db.select({table: 'genre', map: `(r) => ({value: r.value})`});
  243. for (const row of rows) {
  244. genreParsed.add(row.value);
  245. if (!genreValues.has(row.value))
  246. last.value.push({name: row.value, value: row.value});
  247. }
  248. //уберем те, которые не нашлись при парсинге
  249. for (let j = 0; j < genres.length; j++) {
  250. const section = genres[j];
  251. for (let i = 0; i < section.value.length; i++) {
  252. const g = section.value[i];
  253. if (!genreParsed.has(g.value))
  254. section.value.splice(i--, 1);
  255. }
  256. if (!section.value.length)
  257. genres.splice(j--, 1);
  258. }
  259. // langs
  260. rows = await db.select({table: 'lang', map: `(r) => ({value: r.value})`});
  261. const langs = rows.map(r => r.value);
  262. result = {
  263. genreTree: genres,
  264. langList: langs,
  265. inpxHash: (config.inpxHash ? config.inpxHash : ''),
  266. };
  267. db.wwCache.genres = result;
  268. } else {
  269. result = db.wwCache.genres;
  270. }
  271. return result;
  272. }
  273. async extractBook(bookPath) {
  274. const outFile = `${this.config.tempDir}/${utils.randomHexString(30)}`;
  275. const folder = `${this.config.libDir}/${path.dirname(bookPath)}`;
  276. const file = path.basename(bookPath);
  277. const zipReader = new ZipReader();
  278. await zipReader.open(folder);
  279. try {
  280. await zipReader.extractToFile(file, outFile);
  281. return outFile;
  282. } finally {
  283. await zipReader.close();
  284. }
  285. }
  286. async restoreBook(bookUid, bookPath, downFileName) {
  287. const db = this.db;
  288. let extractedFile = '';
  289. let hash = '';
  290. if (!this.remoteLib) {
  291. extractedFile = await this.extractBook(bookPath);
  292. hash = await utils.getFileHash(extractedFile, 'sha256', 'hex');
  293. } else {
  294. hash = await this.remoteLib.downloadBook(bookUid);
  295. }
  296. const link = `${this.config.filesPathStatic}/${hash}`;
  297. const bookFile = `${this.config.filesDir}/${hash}`;
  298. const bookFileDesc = `${bookFile}.d.json`;
  299. if (!await fs.pathExists(bookFile) || !await fs.pathExists(bookFileDesc)) {
  300. if (!await fs.pathExists(bookFile) && extractedFile) {
  301. const tmpFile = `${this.config.tempDir}/${utils.randomHexString(30)}`;
  302. await utils.gzipFile(extractedFile, tmpFile, 4);
  303. await fs.remove(extractedFile);
  304. await fs.move(tmpFile, bookFile, {overwrite: true});
  305. } else {
  306. await utils.touchFile(bookFile);
  307. }
  308. await fs.writeFile(bookFileDesc, JSON.stringify({bookPath, downFileName}));
  309. } else {
  310. if (extractedFile)
  311. await fs.remove(extractedFile);
  312. await utils.touchFile(bookFile);
  313. await utils.touchFile(bookFileDesc);
  314. }
  315. await db.insert({
  316. table: 'file_hash',
  317. replace: true,
  318. rows: [
  319. {id: bookPath, hash},
  320. {id: hash, bookPath, downFileName}
  321. ]
  322. });
  323. return link;
  324. }
  325. async getBookLink(bookUid) {
  326. this.checkMyState();
  327. try {
  328. const db = this.db;
  329. let link = '';
  330. //найдем bookPath и downFileName
  331. let rows = await db.select({table: 'book', where: `@@hash('_uid', ${db.esc(bookUid)})`});
  332. if (!rows.length)
  333. throw new Error('404 Файл не найден');
  334. const book = rows[0];
  335. let downFileName = book.file;
  336. const author = book.author.split(',');
  337. const at = [author[0], book.title];
  338. downFileName = utils.makeValidFileNameOrEmpty(at.filter(r => r).join(' - '))
  339. || utils.makeValidFileNameOrEmpty(at[0])
  340. || utils.makeValidFileNameOrEmpty(at[1])
  341. || downFileName;
  342. downFileName = downFileName.substring(0, 100);
  343. const ext = `.${book.ext}`;
  344. if (downFileName.substring(downFileName.length - ext.length) != ext)
  345. downFileName += ext;
  346. const bookPath = `${book.folder}/${book.file}${ext}`;
  347. //найдем хеш
  348. rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(bookPath)})`});
  349. if (rows.length) {//хеш найден по bookPath
  350. const hash = rows[0].hash;
  351. const bookFile = `${this.config.filesDir}/${hash}`;
  352. const bookFileDesc = `${bookFile}.d.json`;
  353. if (await fs.pathExists(bookFile) && await fs.pathExists(bookFileDesc)) {
  354. link = `${this.config.filesPathStatic}/${hash}`;
  355. }
  356. }
  357. if (!link) {
  358. link = await this.restoreBook(bookUid, bookPath, downFileName)
  359. }
  360. if (!link)
  361. throw new Error('404 Файл не найден');
  362. return {link, bookPath, downFileName};
  363. } catch(e) {
  364. log(LM_ERR, `getBookLink error: ${e.message}`);
  365. if (e.message.indexOf('ENOENT') >= 0)
  366. throw new Error('404 Файл не найден');
  367. throw e;
  368. }
  369. }
  370. async getBookInfo(bookUid) {
  371. this.checkMyState();
  372. try {
  373. const db = this.db;
  374. let bookInfo = await this.getBookLink(bookUid);
  375. const hash = path.basename(bookInfo.link);
  376. const bookFile = `${this.config.filesDir}/${hash}`;
  377. const bookFileInfo = `${bookFile}.i.json`;
  378. let rows = await db.select({table: 'book', where: `@@hash('_uid', ${db.esc(bookUid)})`});
  379. if (!rows.length)
  380. throw new Error('404 Файл не найден');
  381. const book = rows[0];
  382. const restoreBookInfo = async(info) => {
  383. const result = {};
  384. result.book = book;
  385. result.cover = '';
  386. result.fb2 = false;
  387. let parser = null;
  388. if (book.ext == 'fb2') {
  389. const {fb2, cover, coverExt} = await this.fb2Helper.getDescAndCover(bookFile);
  390. parser = fb2;
  391. result.fb2 = fb2.rawNodes;
  392. if (cover) {
  393. result.cover = `${this.config.filesPathStatic}/${hash}${coverExt}`;
  394. await fs.writeFile(`${bookFile}${coverExt}`, cover);
  395. }
  396. }
  397. Object.assign(info, result);
  398. await fs.writeFile(bookFileInfo, JSON.stringify(info));
  399. if (this.config.branch === 'development') {
  400. await fs.writeFile(`${bookFile}.dev`, `${JSON.stringify(info, null, 2)}\n\n${parser ? parser.toString({format: true}) : ''}`);
  401. }
  402. };
  403. if (!await fs.pathExists(bookFileInfo)) {
  404. await restoreBookInfo(bookInfo);
  405. } else {
  406. await utils.touchFile(bookFileInfo);
  407. const info = await fs.readFile(bookFileInfo, 'utf-8');
  408. const tmpInfo = JSON.parse(info);
  409. //проверим существование файла обложки, восстановим если нету
  410. let coverFile = '';
  411. if (tmpInfo.cover)
  412. coverFile = `${this.config.publicFilesDir}${tmpInfo.cover}`;
  413. if (book.id != tmpInfo.book.id || (coverFile && !await fs.pathExists(coverFile))) {
  414. await restoreBookInfo(bookInfo);
  415. } else {
  416. bookInfo = tmpInfo;
  417. }
  418. }
  419. return {bookInfo};
  420. } catch(e) {
  421. log(LM_ERR, `getBookInfo error: ${e.message}`);
  422. if (e.message.indexOf('ENOENT') >= 0)
  423. throw new Error('404 Файл не найден');
  424. throw e;
  425. }
  426. }
  427. async getInpxFile(params) {
  428. let data = null;
  429. if (params.inpxFileHash && this.inpxFileHash && params.inpxFileHash === this.inpxFileHash) {
  430. data = false;
  431. }
  432. if (data === null)
  433. data = await fs.readFile(this.config.inpxFile, 'base64');
  434. return {data};
  435. }
  436. logServerStats() {
  437. try {
  438. const memUsage = process.memoryUsage().rss/(1024*1024);//Mb
  439. let loadAvg = os.loadavg();
  440. loadAvg = loadAvg.map(v => v.toFixed(2));
  441. log(`Server info [ memUsage: ${memUsage.toFixed(2)}MB, loadAvg: (${loadAvg.join(', ')}) ]`);
  442. if (this.config.server.ready)
  443. log(`Server accessible at http://127.0.0.1:${this.config.server.port} (listening on ${this.config.server.host}:${this.config.server.port})`);
  444. } catch (e) {
  445. log(LM_ERR, e.message);
  446. }
  447. }
  448. async periodicLogServerStats() {
  449. while (1) {// eslint-disable-line
  450. this.logServerStats();
  451. await utils.sleep(60*1000);
  452. }
  453. }
  454. async cleanDir(config) {
  455. const {dir, maxSize} = config;
  456. const list = await fs.readdir(dir);
  457. let size = 0;
  458. let files = [];
  459. //формируем список
  460. for (const filename of list) {
  461. const filePath = `${dir}/${filename}`;
  462. const stat = await fs.stat(filePath);
  463. if (!stat.isDirectory()) {
  464. size += stat.size;
  465. files.push({name: filePath, stat});
  466. }
  467. }
  468. log(LM_WARN, `clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files, total size=${size}`);
  469. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  470. let i = 0;
  471. //удаляем
  472. while (i < files.length && size > maxSize) {
  473. const file = files[i];
  474. const oldFile = file.name;
  475. await fs.remove(oldFile);
  476. size -= file.stat.size;
  477. i++;
  478. }
  479. log(LM_WARN, `removed ${i} files`);
  480. }
  481. async periodicCleanDir(dirConfig) {
  482. try {
  483. for (const config of dirConfig)
  484. await fs.ensureDir(config.dir);
  485. let lastCleanDirTime = 0;
  486. while (1) {// eslint-disable-line no-constant-condition
  487. //чистка папок
  488. if (Date.now() - lastCleanDirTime >= cleanDirPeriod) {
  489. for (const config of dirConfig) {
  490. try {
  491. await this.cleanDir(config);
  492. } catch(e) {
  493. log(LM_ERR, e.stack);
  494. }
  495. }
  496. lastCleanDirTime = Date.now();
  497. }
  498. await utils.sleep(60*1000);//интервал проверки 1 минута
  499. }
  500. } catch (e) {
  501. log(LM_FATAL, e.message);
  502. asyncExit.exit(1);
  503. }
  504. }
  505. async periodicCheckInpx() {
  506. const inpxCheckInterval = this.config.inpxCheckInterval;
  507. if (!inpxCheckInterval)
  508. return;
  509. while (1) {// eslint-disable-line no-constant-condition
  510. try {
  511. while (this.myState != ssNormal)
  512. await utils.sleep(1000);
  513. if (this.remoteLib) {
  514. await this.remoteLib.downloadInpxFile();
  515. }
  516. const newInpxHash = await this.inpxHashCreator.getHash();
  517. const dbConfig = await this.dbConfig();
  518. const currentInpxHash = (dbConfig.inpxHash ? dbConfig.inpxHash : '');
  519. if (newInpxHash !== currentInpxHash) {
  520. log('inpx file: changes found, recreating DB');
  521. await this.recreateDb();
  522. } else {
  523. log('inpx file: no changes');
  524. }
  525. } catch(e) {
  526. log(LM_ERR, `periodicCheckInpx: ${e.message}`);
  527. }
  528. await utils.sleep(inpxCheckInterval*60*1000);
  529. }
  530. }
  531. }
  532. module.exports = WebWorker;