ReaderWorker.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. const decompFiles = await this.decomp.decompressFile(downloadedFilename, decompDir);
  55. wState.set({progress: 100});
  56. //конвертирование в fb2
  57. wState.set({state: 'convert', step: 3, progress: 0});
  58. convertFilename = `${this.config.tempDownloadDir}/${tempFilename2}`;
  59. await this.bookConverter.convertToFb2(decompFiles, convertFilename, url, progress => {
  60. wState.set({progress});
  61. });
  62. //сжимаем файл в tmp, если там уже нет с тем же именем-sha256
  63. const compFilename = await this.decomp.gzipFileIfNotExists(convertFilename, `${this.config.tempPublicDir}`);
  64. wState.set({progress: 100});
  65. //finish
  66. const finishFilename = path.basename(compFilename);
  67. wState.finish({path: `/tmp/${finishFilename}`});
  68. } catch (e) {
  69. if (this.config.branch == 'development')
  70. console.error(e);
  71. wState.set({state: 'error', error: (errMes ? errMes : e.message)});
  72. } finally {
  73. //clean
  74. if (decompDir)
  75. await fs.remove(decompDir);
  76. if (downloadedFilename && !isUploaded)
  77. await fs.remove(downloadedFilename);
  78. if (convertFilename)
  79. await fs.remove(convertFilename);
  80. }
  81. }
  82. loadBookUrl(url) {
  83. const workerId = workerState.generateWorkerId();
  84. const wState = workerState.getControl(workerId);
  85. wState.set({state: 'start'});
  86. this.loadBook(url, wState);
  87. return workerId;
  88. }
  89. async saveFile(file) {
  90. const buf = await fs.readFile(file.path);
  91. const hash = crypto.createHash('sha256').update(buf).digest('hex');
  92. const outFilename = `${this.config.uploadDir}/${hash}`;
  93. if (!await fs.pathExists(outFilename)) {
  94. await fs.move(file.path, outFilename);
  95. } else {
  96. await utils.touchFile(outFilename);
  97. await fs.remove(file.path);
  98. }
  99. return `file://${hash}`;
  100. }
  101. async periodicCleanDir(dir, maxSize, timeout) {
  102. const list = await fs.readdir(dir);
  103. let size = 0;
  104. let files = [];
  105. for (const name of list) {
  106. const stat = await fs.stat(`${dir}/${name}`);
  107. if (!stat.isDirectory()) {
  108. size += stat.size;
  109. files.push({name, stat});
  110. }
  111. }
  112. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  113. let i = 0;
  114. while (i < files.length && size > maxSize) {
  115. const file = files[i];
  116. await fs.remove(`${dir}/${file.name}`);
  117. size -= file.stat.size;
  118. i++;
  119. }
  120. setTimeout(() => {
  121. this.periodicCleanDir(dir, maxSize, timeout);
  122. }, timeout);
  123. }
  124. }
  125. module.exports = ReaderWorker;