ReaderWorker.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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 decompFilename = 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(decompFilename, 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. wState.set({state: 'error', error: (errMes ? errMes : e.message)});
  70. } finally {
  71. //clean
  72. if (decompDir)
  73. await fs.remove(decompDir);
  74. if (downloadedFilename && !isUploaded)
  75. await fs.remove(downloadedFilename);
  76. if (convertFilename)
  77. await fs.remove(convertFilename);
  78. }
  79. }
  80. loadBookUrl(url) {
  81. const workerId = workerState.generateWorkerId();
  82. const wState = workerState.getControl(workerId);
  83. wState.set({state: 'start'});
  84. this.loadBook(url, wState);
  85. return workerId;
  86. }
  87. async saveFile(file) {
  88. const buf = await fs.readFile(file.path);
  89. const hash = crypto.createHash('sha256').update(buf).digest('hex');
  90. const outFilename = `${this.config.uploadDir}/${hash}`;
  91. if (!await fs.pathExists(outFilename)) {
  92. await fs.move(file.path, outFilename);
  93. } else {
  94. await utils.touchFile(outFilename);
  95. await fs.remove(file.path);
  96. }
  97. return `file://${hash}`;
  98. }
  99. async periodicCleanDir(dir, maxSize, timeout) {
  100. const list = await fs.readdir(dir);
  101. let size = 0;
  102. let files = [];
  103. for (const name of list) {
  104. const stat = await fs.stat(`${dir}/${name}`);
  105. if (!stat.isDirectory()) {
  106. size += stat.size;
  107. files.push({name, stat});
  108. }
  109. }
  110. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  111. let i = 0;
  112. while (i < files.length && size > maxSize) {
  113. const file = files[i];
  114. await fs.remove(`${dir}/${file.name}`);
  115. size -= file.stat.size;
  116. i++;
  117. }
  118. setTimeout(() => {
  119. this.periodicCleanDir(dir, maxSize, timeout);
  120. }, timeout);
  121. }
  122. }
  123. module.exports = ReaderWorker;