ReaderWorker.js 6.0 KB

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