ReaderWorker.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. const fs = require('fs-extra');
  2. const path = require('path');
  3. const WorkerState = require('../WorkerState');//singleton
  4. const FileDownloader = require('../FileDownloader');
  5. const FileDecompressor = require('../FileDecompressor');
  6. const BookConverter = require('./BookConverter');
  7. const utils = require('../utils');
  8. const log = new (require('../AppLogger'))().log;//singleton
  9. let instance = null;
  10. //singleton
  11. class ReaderWorker {
  12. constructor(config) {
  13. if (!instance) {
  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.workerState = new WorkerState();
  20. this.down = new FileDownloader();
  21. this.decomp = new FileDecompressor();
  22. this.bookConverter = new BookConverter(this.config);
  23. this.periodicCleanDir(this.config.tempPublicDir, this.config.maxTempPublicDirSize, 60*60*1000);//1 раз в час
  24. this.periodicCleanDir(this.config.uploadDir, this.config.maxUploadPublicDirSize, 60*60*1000);//1 раз в час
  25. instance = this;
  26. }
  27. return instance;
  28. }
  29. async loadBook(opts, wState) {
  30. const url = opts.url;
  31. let errMes = '';
  32. let decompDir = '';
  33. let downloadedFilename = '';
  34. let isUploaded = false;
  35. let convertFilename = '';
  36. try {
  37. wState.set({state: 'download', step: 1, totalSteps: 3, url});
  38. const tempFilename = utils.randomHexString(30);
  39. const tempFilename2 = utils.randomHexString(30);
  40. const decompDirname = utils.randomHexString(30);
  41. if (url.indexOf('file://') != 0) {//download
  42. const downdata = await this.down.load(url, (progress) => {
  43. wState.set({progress});
  44. });
  45. downloadedFilename = `${this.config.tempDownloadDir}/${tempFilename}`;
  46. await fs.writeFile(downloadedFilename, downdata);
  47. } else {//uploaded file
  48. downloadedFilename = `${this.config.uploadDir}/${url.substr(7)}`;
  49. if (!await fs.pathExists(downloadedFilename))
  50. throw new Error('Файл не найден на сервере (возможно был удален как устаревший). Пожалуйста, загрузите файл с диска на сервер заново.');
  51. await utils.touchFile(downloadedFilename);
  52. isUploaded = true;
  53. }
  54. wState.set({progress: 100});
  55. //decompress
  56. wState.set({state: 'decompress', step: 2, progress: 0});
  57. decompDir = `${this.config.tempDownloadDir}/${decompDirname}`;
  58. let decompFiles = {};
  59. try {
  60. decompFiles = await this.decomp.decompressNested(downloadedFilename, decompDir);
  61. } catch (e) {
  62. if (this.config.branch == 'development')
  63. console.error(e);
  64. throw new Error('Ошибка распаковки');
  65. }
  66. wState.set({progress: 100});
  67. //конвертирование в fb2
  68. wState.set({state: 'convert', step: 3, progress: 0});
  69. convertFilename = `${this.config.tempDownloadDir}/${tempFilename2}`;
  70. await this.bookConverter.convertToFb2(decompFiles, convertFilename, opts, progress => {
  71. wState.set({progress});
  72. });
  73. //сжимаем файл в tmp, если там уже нет с тем же именем-sha256
  74. const compFilename = await this.decomp.gzipFileIfNotExists(convertFilename, `${this.config.tempPublicDir}`);
  75. wState.set({progress: 100});
  76. //finish
  77. const finishFilename = path.basename(compFilename);
  78. wState.finish({path: `/tmp/${finishFilename}`});
  79. } catch (e) {
  80. log(LM_ERR, e.stack);
  81. wState.set({state: 'error', error: (errMes ? errMes : e.message)});
  82. } finally {
  83. //clean
  84. if (decompDir)
  85. await fs.remove(decompDir);
  86. if (downloadedFilename && !isUploaded)
  87. await fs.remove(downloadedFilename);
  88. if (convertFilename)
  89. await fs.remove(convertFilename);
  90. }
  91. }
  92. loadBookUrl(opts) {
  93. const workerId = this.workerState.generateWorkerId();
  94. const wState = this.workerState.getControl(workerId);
  95. wState.set({state: 'start'});
  96. this.loadBook(opts, wState);
  97. return workerId;
  98. }
  99. async saveFile(file) {
  100. const hash = await utils.getFileHash(file.path, 'sha256', 'hex');
  101. const outFilename = `${this.config.uploadDir}/${hash}`;
  102. if (!await fs.pathExists(outFilename)) {
  103. await fs.move(file.path, outFilename);
  104. } else {
  105. await utils.touchFile(outFilename);
  106. await fs.remove(file.path);
  107. }
  108. return `file://${hash}`;
  109. }
  110. async periodicCleanDir(dir, maxSize, timeout) {
  111. try {
  112. const list = await fs.readdir(dir);
  113. let size = 0;
  114. let files = [];
  115. for (const name of list) {
  116. const stat = await fs.stat(`${dir}/${name}`);
  117. if (!stat.isDirectory()) {
  118. size += stat.size;
  119. files.push({name, stat});
  120. }
  121. }
  122. log(`clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files`);
  123. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  124. let i = 0;
  125. while (i < files.length && size > maxSize) {
  126. const file = files[i];
  127. await fs.remove(`${dir}/${file.name}`);
  128. size -= file.stat.size;
  129. i++;
  130. }
  131. log(`removed ${i} files`);
  132. } catch(e) {
  133. log(LM_ERR, e.stack);
  134. } finally {
  135. setTimeout(() => {
  136. this.periodicCleanDir(dir, maxSize, timeout);
  137. }, timeout);
  138. }
  139. }
  140. }
  141. module.exports = ReaderWorker;