ReaderWorker.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. const fs = require('fs-extra');
  2. const path = require('path');
  3. const crypto = require('crypto');
  4. const workerState = require('./workerState');
  5. const FileDownloader = require('./FileDownloader');
  6. const FileDecompressor = require('./FileDecompressor');
  7. const BookConverter = require('./BookConverter');
  8. const utils = require('./utils');
  9. const log = require('./getLogger').getLog();
  10. let singleCleanExecute = false;
  11. class ReaderWorker {
  12. constructor(config) {
  13. this.config = Object.assign({}, config);
  14. this.config.tempDownloadDir = `${config.tempDir}/download`;
  15. fs.ensureDirSync(this.config.tempDownloadDir);
  16. this.config.tempPublicDir = `${config.publicDir}/tmp`;
  17. fs.ensureDirSync(this.config.tempPublicDir);
  18. this.down = new FileDownloader();
  19. this.decomp = new FileDecompressor();
  20. this.bookConverter = new BookConverter(this.config);
  21. if (!singleCleanExecute) {
  22. this.periodicCleanDir(this.config.tempPublicDir, this.config.maxTempPublicDirSize, 60*60*1000);//1 раз в час
  23. this.periodicCleanDir(this.config.uploadDir, this.config.maxUploadPublicDirSize, 60*60*1000);//1 раз в час
  24. singleCleanExecute = true;
  25. }
  26. }
  27. async loadBook(url, wState) {
  28. let errMes = '';
  29. let decompDir = '';
  30. let downloadedFilename = '';
  31. let isUploaded = false;
  32. let convertFilename = '';
  33. try {
  34. wState.set({state: 'download', step: 1, totalSteps: 3, url});
  35. const tempFilename = utils.randomHexString(30);
  36. const tempFilename2 = utils.randomHexString(30);
  37. const decompDirname = utils.randomHexString(30);
  38. if (url.indexOf('file://') != 0) {//download
  39. const downdata = await this.down.load(url, (progress) => {
  40. wState.set({progress});
  41. });
  42. downloadedFilename = `${this.config.tempDownloadDir}/${tempFilename}`;
  43. await fs.writeFile(downloadedFilename, downdata);
  44. } else {//uploaded file
  45. downloadedFilename = `${this.config.uploadDir}/${url.substr(7)}`;
  46. if (!await fs.pathExists(downloadedFilename))
  47. throw new Error('Файл не найден на сервере (возможно был удален как устаревший). Пожалуйста, загрузите файл с диска на сервер заново.');
  48. await utils.touchFile(downloadedFilename);
  49. isUploaded = true;
  50. }
  51. wState.set({progress: 100});
  52. //decompress
  53. wState.set({state: 'decompress', step: 2, progress: 0});
  54. decompDir = `${this.config.tempDownloadDir}/${decompDirname}`;
  55. let decompFiles = {};
  56. try {
  57. decompFiles = await this.decomp.decompressNested(downloadedFilename, decompDir);
  58. } catch (e) {
  59. if (this.config.branch == 'development')
  60. console.error(e);
  61. throw new Error('Ошибка распаковки');
  62. }
  63. wState.set({progress: 100});
  64. //конвертирование в fb2
  65. wState.set({state: 'convert', step: 3, progress: 0});
  66. convertFilename = `${this.config.tempDownloadDir}/${tempFilename2}`;
  67. await this.bookConverter.convertToFb2(decompFiles, convertFilename, url, progress => {
  68. wState.set({progress});
  69. });
  70. //сжимаем файл в tmp, если там уже нет с тем же именем-sha256
  71. const compFilename = await this.decomp.gzipFileIfNotExists(convertFilename, `${this.config.tempPublicDir}`);
  72. wState.set({progress: 100});
  73. //finish
  74. const finishFilename = path.basename(compFilename);
  75. wState.finish({path: `/tmp/${finishFilename}`});
  76. } catch (e) {
  77. if (this.config.branch == 'development')
  78. console.error(e);
  79. wState.set({state: 'error', error: (errMes ? errMes : e.message)});
  80. } finally {
  81. //clean
  82. if (decompDir)
  83. await fs.remove(decompDir);
  84. if (downloadedFilename && !isUploaded)
  85. await fs.remove(downloadedFilename);
  86. if (convertFilename)
  87. await fs.remove(convertFilename);
  88. }
  89. }
  90. loadBookUrl(url) {
  91. const workerId = workerState.generateWorkerId();
  92. const wState = workerState.getControl(workerId);
  93. wState.set({state: 'start'});
  94. this.loadBook(url, wState);
  95. return workerId;
  96. }
  97. async saveFile(file) {
  98. const buf = await fs.readFile(file.path);
  99. const hash = crypto.createHash('sha256').update(buf).digest('hex');
  100. const outFilename = `${this.config.uploadDir}/${hash}`;
  101. if (!await fs.pathExists(outFilename)) {
  102. await fs.move(file.path, outFilename);
  103. } else {
  104. await utils.touchFile(outFilename);
  105. await fs.remove(file.path);
  106. }
  107. return `file://${hash}`;
  108. }
  109. async periodicCleanDir(dir, maxSize, timeout) {
  110. try {
  111. log(`Start clean dir: ${dir}, maxSize=${maxSize}`);
  112. const list = await fs.readdir(dir);
  113. let size = 0;
  114. let files = [];
  115. for (const name of list) {
  116. const stat = await fs.stat(`${dir}/${name}`);
  117. if (!stat.isDirectory()) {
  118. size += stat.size;
  119. files.push({name, stat});
  120. }
  121. }
  122. log(`found ${files.length} files in dir ${dir}`);
  123. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  124. let i = 0;
  125. while (i < files.length && size > maxSize) {
  126. const file = files[i];
  127. log(`rm ${dir}/${file.name}`);
  128. await fs.remove(`${dir}/${file.name}`);
  129. size -= file.stat.size;
  130. i++;
  131. }
  132. log(`removed ${i} files`);
  133. } catch(e) {
  134. log(LM_ERR, e.message);
  135. } finally {
  136. setTimeout(() => {
  137. this.periodicCleanDir(dir, maxSize, timeout);
  138. }, timeout);
  139. }
  140. }
  141. }
  142. module.exports = ReaderWorker;