WebWorker.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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. //stuff
  171. db.wwCache = {};
  172. this.db = db;
  173. this.setMyState(ssNormal);
  174. log('Searcher DB ready');
  175. this.logServerStats();
  176. } catch (e) {
  177. log(LM_FATAL, e.message);
  178. asyncExit.exit(1);
  179. }
  180. }
  181. async recreateDb() {
  182. this.setMyState(ssDbCreating);
  183. if (this.dbSearcher) {
  184. await this.dbSearcher.close();
  185. this.dbSearcher = null;
  186. }
  187. await this.closeDb();
  188. await this.loadOrCreateDb(true);
  189. }
  190. async dbConfig() {
  191. this.checkMyState();
  192. const db = this.db;
  193. if (!db.wwCache.config) {
  194. const rows = await db.select({table: 'config'});
  195. const config = {};
  196. for (const row of rows) {
  197. config[row.id] = row.value;
  198. }
  199. db.wwCache.config = config;
  200. }
  201. return db.wwCache.config;
  202. }
  203. async search(from, query) {
  204. this.checkMyState();
  205. const result = await this.dbSearcher.search(from, query);
  206. const config = await this.dbConfig();
  207. result.inpxHash = (config.inpxHash ? config.inpxHash : '');
  208. return result;
  209. }
  210. async opdsQuery(from, query) {
  211. this.checkMyState();
  212. return await this.dbSearcher.opdsQuery(from, query);
  213. }
  214. async getAuthorBookList(authorId, author) {
  215. this.checkMyState();
  216. return await this.dbSearcher.getAuthorBookList(authorId, author);
  217. }
  218. async getAuthorSeriesList(authorId) {
  219. this.checkMyState();
  220. return await this.dbSearcher.getAuthorSeriesList(authorId);
  221. }
  222. async getSeriesBookList(series) {
  223. this.checkMyState();
  224. return await this.dbSearcher.getSeriesBookList(series);
  225. }
  226. async getGenreTree() {
  227. this.checkMyState();
  228. const config = await this.dbConfig();
  229. let result;
  230. const db = this.db;
  231. if (!db.wwCache.genres) {
  232. const genres = _.cloneDeep(genreTree);
  233. const last = genres[genres.length - 1];
  234. const genreValues = new Set();
  235. for (const section of genres) {
  236. for (const g of section.value)
  237. genreValues.add(g.value);
  238. }
  239. //добавим к жанрам те, что нашлись при парсинге
  240. const genreParsed = new Set();
  241. let rows = await db.select({table: 'genre', map: `(r) => ({value: r.value})`});
  242. for (const row of rows) {
  243. genreParsed.add(row.value);
  244. if (!genreValues.has(row.value))
  245. last.value.push({name: row.value, value: row.value});
  246. }
  247. //уберем те, которые не нашлись при парсинге
  248. for (let j = 0; j < genres.length; j++) {
  249. const section = genres[j];
  250. for (let i = 0; i < section.value.length; i++) {
  251. const g = section.value[i];
  252. if (!genreParsed.has(g.value))
  253. section.value.splice(i--, 1);
  254. }
  255. if (!section.value.length)
  256. genres.splice(j--, 1);
  257. }
  258. // langs
  259. rows = await db.select({table: 'lang', map: `(r) => ({value: r.value})`});
  260. const langs = rows.map(r => r.value);
  261. result = {
  262. genreTree: genres,
  263. langList: langs,
  264. inpxHash: (config.inpxHash ? config.inpxHash : ''),
  265. };
  266. db.wwCache.genres = result;
  267. } else {
  268. result = db.wwCache.genres;
  269. }
  270. return result;
  271. }
  272. async extractBook(bookPath) {
  273. const outFile = `${this.config.tempDir}/${utils.randomHexString(30)}`;
  274. const folder = `${this.config.libDir}/${path.dirname(bookPath)}`;
  275. const file = path.basename(bookPath);
  276. const zipReader = new ZipReader();
  277. await zipReader.open(folder);
  278. try {
  279. await zipReader.extractToFile(file, outFile);
  280. return outFile;
  281. } finally {
  282. await zipReader.close();
  283. }
  284. }
  285. async restoreBook(bookUid, bookPath, downFileName) {
  286. const db = this.db;
  287. let extractedFile = '';
  288. let hash = '';
  289. if (!this.remoteLib) {
  290. extractedFile = await this.extractBook(bookPath);
  291. hash = await utils.getFileHash(extractedFile, 'sha256', 'hex');
  292. } else {
  293. hash = await this.remoteLib.downloadBook(bookUid);
  294. }
  295. const link = `${this.config.filesPathStatic}/${hash}`;
  296. const bookFile = `${this.config.filesDir}/${hash}`;
  297. const bookFileDesc = `${bookFile}.d.json`;
  298. if (!await fs.pathExists(bookFile) || !await fs.pathExists(bookFileDesc)) {
  299. if (!await fs.pathExists(bookFile) && extractedFile) {
  300. const tmpFile = `${this.config.tempDir}/${utils.randomHexString(30)}`;
  301. await utils.gzipFile(extractedFile, tmpFile, 4);
  302. await fs.remove(extractedFile);
  303. await fs.move(tmpFile, bookFile, {overwrite: true});
  304. } else {
  305. await utils.touchFile(bookFile);
  306. }
  307. await fs.writeFile(bookFileDesc, JSON.stringify({bookPath, downFileName}));
  308. } else {
  309. if (extractedFile)
  310. await fs.remove(extractedFile);
  311. await utils.touchFile(bookFile);
  312. await utils.touchFile(bookFileDesc);
  313. }
  314. await db.insert({
  315. table: 'file_hash',
  316. replace: true,
  317. rows: [
  318. {id: bookPath, hash},
  319. {id: hash, bookPath, downFileName}
  320. ]
  321. });
  322. return link;
  323. }
  324. async getBookLink(bookUid) {
  325. this.checkMyState();
  326. try {
  327. const db = this.db;
  328. let link = '';
  329. //найдем bookPath и downFileName
  330. let rows = await db.select({table: 'book', where: `@@hash('_uid', ${db.esc(bookUid)})`});
  331. if (!rows.length)
  332. throw new Error('404 Файл не найден');
  333. const book = rows[0];
  334. let downFileName = book.file;
  335. const author = book.author.split(',');
  336. const at = [author[0], book.title];
  337. downFileName = utils.makeValidFileNameOrEmpty(at.filter(r => r).join(' - '))
  338. || utils.makeValidFileNameOrEmpty(at[0])
  339. || utils.makeValidFileNameOrEmpty(at[1])
  340. || downFileName;
  341. downFileName = downFileName.substring(0, 100);
  342. const ext = `.${book.ext}`;
  343. if (downFileName.substring(downFileName.length - ext.length) != ext)
  344. downFileName += ext;
  345. const bookPath = `${book.folder}/${book.file}${ext}`;
  346. //найдем хеш
  347. rows = await db.select({table: 'file_hash', where: `@@id(${db.esc(bookPath)})`});
  348. if (rows.length) {//хеш найден по bookPath
  349. const hash = rows[0].hash;
  350. const bookFile = `${this.config.filesDir}/${hash}`;
  351. const bookFileDesc = `${bookFile}.d.json`;
  352. if (await fs.pathExists(bookFile) && await fs.pathExists(bookFileDesc)) {
  353. link = `${this.config.filesPathStatic}/${hash}`;
  354. }
  355. }
  356. if (!link) {
  357. link = await this.restoreBook(bookUid, bookPath, downFileName)
  358. }
  359. if (!link)
  360. throw new Error('404 Файл не найден');
  361. return {link, bookPath, downFileName};
  362. } catch(e) {
  363. log(LM_ERR, `getBookLink error: ${e.message}`);
  364. if (e.message.indexOf('ENOENT') >= 0)
  365. throw new Error('404 Файл не найден');
  366. throw e;
  367. }
  368. }
  369. async getBookInfo(bookUid) {
  370. this.checkMyState();
  371. try {
  372. const db = this.db;
  373. let bookInfo = await this.getBookLink(bookUid);
  374. const hash = path.basename(bookInfo.link);
  375. const bookFile = `${this.config.filesDir}/${hash}`;
  376. const bookFileInfo = `${bookFile}.i.json`;
  377. let rows = await db.select({table: 'book', where: `@@hash('_uid', ${db.esc(bookUid)})`});
  378. if (!rows.length)
  379. throw new Error('404 Файл не найден');
  380. const book = rows[0];
  381. const restoreBookInfo = async(info) => {
  382. const result = {};
  383. result.book = book;
  384. result.cover = '';
  385. result.fb2 = false;
  386. let parser = null;
  387. if (book.ext == 'fb2') {
  388. const {fb2, cover, coverExt} = await this.fb2Helper.getDescAndCover(bookFile);
  389. parser = fb2;
  390. result.fb2 = fb2.rawNodes;
  391. if (cover) {
  392. result.cover = `${this.config.filesPathStatic}/${hash}${coverExt}`;
  393. await fs.writeFile(`${bookFile}${coverExt}`, cover);
  394. }
  395. }
  396. Object.assign(info, result);
  397. await fs.writeFile(bookFileInfo, JSON.stringify(info));
  398. if (this.config.branch === 'development') {
  399. await fs.writeFile(`${bookFile}.dev`, `${JSON.stringify(info, null, 2)}\n\n${parser ? parser.toString({format: true}) : ''}`);
  400. }
  401. };
  402. if (!await fs.pathExists(bookFileInfo)) {
  403. await restoreBookInfo(bookInfo);
  404. } else {
  405. await utils.touchFile(bookFileInfo);
  406. const info = await fs.readFile(bookFileInfo, 'utf-8');
  407. const tmpInfo = JSON.parse(info);
  408. //проверим существование файла обложки, восстановим если нету
  409. let coverFile = '';
  410. if (tmpInfo.cover)
  411. coverFile = `${this.config.publicFilesDir}${tmpInfo.cover}`;
  412. if (book.id != tmpInfo.book.id || (coverFile && !await fs.pathExists(coverFile))) {
  413. await restoreBookInfo(bookInfo);
  414. } else {
  415. bookInfo = tmpInfo;
  416. }
  417. }
  418. return {bookInfo};
  419. } catch(e) {
  420. log(LM_ERR, `getBookInfo error: ${e.message}`);
  421. if (e.message.indexOf('ENOENT') >= 0)
  422. throw new Error('404 Файл не найден');
  423. throw e;
  424. }
  425. }
  426. async getInpxFile(params) {
  427. let data = null;
  428. if (params.inpxFileHash && this.inpxFileHash && params.inpxFileHash === this.inpxFileHash) {
  429. data = false;
  430. }
  431. if (data === null)
  432. data = await fs.readFile(this.config.inpxFile, 'base64');
  433. return {data};
  434. }
  435. logServerStats() {
  436. try {
  437. const memUsage = process.memoryUsage().rss/(1024*1024);//Mb
  438. let loadAvg = os.loadavg();
  439. loadAvg = loadAvg.map(v => v.toFixed(2));
  440. log(`Server info [ memUsage: ${memUsage.toFixed(2)}MB, loadAvg: (${loadAvg.join(', ')}) ]`);
  441. if (this.config.server.ready)
  442. log(`Server accessible at http://127.0.0.1:${this.config.server.port} (listening on ${this.config.server.host}:${this.config.server.port})`);
  443. } catch (e) {
  444. log(LM_ERR, e.message);
  445. }
  446. }
  447. async periodicLogServerStats() {
  448. while (1) {// eslint-disable-line
  449. this.logServerStats();
  450. await utils.sleep(60*1000);
  451. }
  452. }
  453. async cleanDir(config) {
  454. const {dir, maxSize} = config;
  455. const list = await fs.readdir(dir);
  456. let size = 0;
  457. let files = [];
  458. //формируем список
  459. for (const filename of list) {
  460. const filePath = `${dir}/${filename}`;
  461. const stat = await fs.stat(filePath);
  462. if (!stat.isDirectory()) {
  463. size += stat.size;
  464. files.push({name: filePath, stat});
  465. }
  466. }
  467. log(LM_WARN, `clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files, total size=${size}`);
  468. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  469. let i = 0;
  470. //удаляем
  471. while (i < files.length && size > maxSize) {
  472. const file = files[i];
  473. const oldFile = file.name;
  474. await fs.remove(oldFile);
  475. size -= file.stat.size;
  476. i++;
  477. }
  478. log(LM_WARN, `removed ${i} files`);
  479. }
  480. async periodicCleanDir(dirConfig) {
  481. try {
  482. for (const config of dirConfig)
  483. await fs.ensureDir(config.dir);
  484. let lastCleanDirTime = 0;
  485. while (1) {// eslint-disable-line no-constant-condition
  486. //чистка папок
  487. if (Date.now() - lastCleanDirTime >= cleanDirPeriod) {
  488. for (const config of dirConfig) {
  489. try {
  490. await this.cleanDir(config);
  491. } catch(e) {
  492. log(LM_ERR, e.stack);
  493. }
  494. }
  495. lastCleanDirTime = Date.now();
  496. }
  497. await utils.sleep(60*1000);//интервал проверки 1 минута
  498. }
  499. } catch (e) {
  500. log(LM_FATAL, e.message);
  501. asyncExit.exit(1);
  502. }
  503. }
  504. async periodicCheckInpx() {
  505. const inpxCheckInterval = this.config.inpxCheckInterval;
  506. if (!inpxCheckInterval)
  507. return;
  508. while (1) {// eslint-disable-line no-constant-condition
  509. try {
  510. while (this.myState != ssNormal)
  511. await utils.sleep(1000);
  512. if (this.remoteLib) {
  513. await this.remoteLib.downloadInpxFile();
  514. }
  515. const newInpxHash = await this.inpxHashCreator.getHash();
  516. const dbConfig = await this.dbConfig();
  517. const currentInpxHash = (dbConfig.inpxHash ? dbConfig.inpxHash : '');
  518. if (newInpxHash !== currentInpxHash) {
  519. log('inpx file: changes found, recreating DB');
  520. await this.recreateDb();
  521. } else {
  522. log('inpx file: no changes');
  523. }
  524. } catch(e) {
  525. log(LM_ERR, `periodicCheckInpx: ${e.message}`);
  526. }
  527. await utils.sleep(inpxCheckInterval*60*1000);
  528. }
  529. }
  530. }
  531. module.exports = WebWorker;