ReaderWorker.js 6.3 KB

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