ReaderWorker.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. const fs = require('fs-extra');
  2. const path = require('path');
  3. const workerState = require('./workerState');
  4. const FileDownloader = require('./FileDownloader');
  5. const FileDecompressor = require('./FileDecompressor');
  6. const BookConverter = require('./BookConverter');
  7. const utils = require('./utils');
  8. const log = new (require('./AppLogger'))().log;//singleton
  9. let singleCleanExecute = false;
  10. class ReaderWorker {
  11. constructor(config) {
  12. this.config = Object.assign({}, config);
  13. this.config.tempDownloadDir = `${config.tempDir}/download`;
  14. fs.ensureDirSync(this.config.tempDownloadDir);
  15. this.config.tempPublicDir = `${config.publicDir}/tmp`;
  16. fs.ensureDirSync(this.config.tempPublicDir);
  17. this.down = new FileDownloader();
  18. this.decomp = new FileDecompressor();
  19. this.bookConverter = new BookConverter(this.config);
  20. if (!singleCleanExecute) {
  21. this.periodicCleanDir(this.config.tempPublicDir, this.config.maxTempPublicDirSize, 60*60*1000);//1 раз в час
  22. this.periodicCleanDir(this.config.uploadDir, this.config.maxUploadPublicDirSize, 60*60*1000);//1 раз в час
  23. singleCleanExecute = true;
  24. }
  25. }
  26. async loadBook(opts, wState) {
  27. const url = opts.url;
  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, opts, 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(opts) {
  91. const workerId = workerState.generateWorkerId();
  92. const wState = workerState.getControl(workerId);
  93. wState.set({state: 'start'});
  94. this.loadBook(opts, wState);
  95. return workerId;
  96. }
  97. async saveFile(file) {
  98. const hash = await utils.getFileHash(file.path, 'sha256', 'hex');
  99. const outFilename = `${this.config.uploadDir}/${hash}`;
  100. if (!await fs.pathExists(outFilename)) {
  101. await fs.move(file.path, outFilename);
  102. } else {
  103. await utils.touchFile(outFilename);
  104. await fs.remove(file.path);
  105. }
  106. return `file://${hash}`;
  107. }
  108. async periodicCleanDir(dir, maxSize, timeout) {
  109. try {
  110. log(`Start clean dir: ${dir}, maxSize=${maxSize}`);
  111. const list = await fs.readdir(dir);
  112. let size = 0;
  113. let files = [];
  114. for (const name of list) {
  115. const stat = await fs.stat(`${dir}/${name}`);
  116. if (!stat.isDirectory()) {
  117. size += stat.size;
  118. files.push({name, stat});
  119. }
  120. }
  121. log(`found ${files.length} files in dir ${dir}`);
  122. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  123. let i = 0;
  124. while (i < files.length && size > maxSize) {
  125. const file = files[i];
  126. log(`rm ${dir}/${file.name}`);
  127. await fs.remove(`${dir}/${file.name}`);
  128. size -= file.stat.size;
  129. i++;
  130. }
  131. log(`removed ${i} files`);
  132. } catch(e) {
  133. log(LM_ERR, e.message);
  134. } finally {
  135. setTimeout(() => {
  136. this.periodicCleanDir(dir, maxSize, timeout);
  137. }, timeout);
  138. }
  139. }
  140. }
  141. module.exports = ReaderWorker;