WebWorker.js 21 KB

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