ReaderWorker.js 5.5 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. const maxTempPublicDirSize = 512*1024*1024;//512Мб
  10. const maxUploadDirSize = 100*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. 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. const decompFilename = await this.decomp.decompressFile(downloadedFilename, decompDir);
  56. wState.set({progress: 100});
  57. //parse book
  58. wState.set({state: 'convert', step: 3, progress: 0});
  59. convertFilename = `${this.config.tempDownloadDir}/${tempFilename2}`;
  60. await this.bookConverter.convertToFb2(decompFilename, convertFilename, url, progress => {
  61. wState.set({progress});
  62. });
  63. //compress file to tmp dir, if not exists with the same hashname
  64. const compFilename = await this.decomp.gzipFileIfNotExists(convertFilename, `${this.config.tempPublicDir}`);
  65. wState.set({progress: 100});
  66. //finish
  67. const finishFilename = path.basename(compFilename);
  68. wState.finish({path: `/tmp/${finishFilename}`});
  69. } catch (e) {
  70. wState.set({state: 'error', error: (errMes ? errMes : e.message)});
  71. } finally {
  72. //clean
  73. if (decompDir)
  74. await fs.remove(decompDir);
  75. if (downloadedFilename && !isUploaded)
  76. await fs.remove(downloadedFilename);
  77. if (convertFilename)
  78. await fs.remove(convertFilename);
  79. }
  80. }
  81. loadBookUrl(url) {
  82. const workerId = workerState.generateWorkerId();
  83. const wState = workerState.getControl(workerId);
  84. wState.set({state: 'start'});
  85. this.loadBook(url, wState);
  86. return workerId;
  87. }
  88. async saveFile(file) {
  89. const buf = await fs.readFile(file.path);
  90. const hash = crypto.createHash('sha256').update(buf).digest('hex');
  91. const outFilename = `${this.config.uploadDir}/${hash}`;
  92. if (!await fs.pathExists(outFilename)) {
  93. await fs.move(file.path, outFilename);
  94. } else {
  95. await fs.utimes(outFilename, Date.now()/1000, Date.now()/1000);
  96. await fs.remove(file.path);
  97. }
  98. return `file://${hash}`;
  99. }
  100. async periodicCleanDir(dir, maxSize, timeout) {
  101. const list = await fs.readdir(dir);
  102. let size = 0;
  103. let files = [];
  104. for (const name of list) {
  105. const stat = await fs.stat(`${dir}/${name}`);
  106. if (!stat.isDirectory()) {
  107. size += stat.size;
  108. files.push({name, stat});
  109. }
  110. }
  111. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  112. let i = 0;
  113. while (i < files.length && size > maxSize) {
  114. const file = files[i];
  115. await fs.remove(`${dir}/${file.name}`);
  116. size -= file.stat.size;
  117. i++;
  118. }
  119. setTimeout(() => {
  120. this.periodicCleanDir(dir, maxSize, timeout);
  121. }, timeout);
  122. }
  123. }
  124. module.exports = ReaderWorker;