ReaderWorker.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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 maxTempPublicDirSize = 512*1024*1024;//512Мб
  10. const maxUploadDirSize = 200*1024*1024;//100Мб
  11. let singleCleanExecute = false;
  12. class ReaderWorker {
  13. constructor(config) {
  14. this.config = Object.assign({}, config);
  15. this.config.tempDownloadDir = `${config.tempDir}/download`;
  16. fs.ensureDirSync(this.config.tempDownloadDir);
  17. this.config.tempPublicDir = `${config.publicDir}/tmp`;
  18. fs.ensureDirSync(this.config.tempPublicDir);
  19. this.down = new FileDownloader();
  20. this.decomp = new FileDecompressor();
  21. this.bookConverter = new BookConverter();
  22. if (!singleCleanExecute) {
  23. this.periodicCleanDir(this.config.tempPublicDir, maxTempPublicDirSize, 60*60*1000);//1 раз в час
  24. this.periodicCleanDir(this.config.uploadDir, maxUploadDirSize, 60*60*1000);//1 раз в час
  25. singleCleanExecute = true;
  26. }
  27. }
  28. async loadBook(url, wState) {
  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. const decompFilename = await this.decomp.decompressFile(downloadedFilename, decompDir);
  57. wState.set({progress: 100});
  58. //parse book
  59. wState.set({state: 'convert', step: 3, progress: 0});
  60. convertFilename = `${this.config.tempDownloadDir}/${tempFilename2}`;
  61. await this.bookConverter.convertToFb2(decompFilename, convertFilename, url, progress => {
  62. wState.set({progress});
  63. });
  64. //compress file to tmp dir, if not exists with the same hashname
  65. const compFilename = await this.decomp.gzipFileIfNotExists(convertFilename, `${this.config.tempPublicDir}`);
  66. wState.set({progress: 100});
  67. //finish
  68. const finishFilename = path.basename(compFilename);
  69. wState.finish({path: `/tmp/${finishFilename}`});
  70. } catch (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;