ReaderWorker.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. log(LM_ERR, e.stack);
  63. throw new Error('Ошибка распаковки');
  64. }
  65. wState.set({progress: 100});
  66. //конвертирование в fb2
  67. wState.set({state: 'convert', step: 3, progress: 0});
  68. convertFilename = `${this.config.tempDownloadDir}/${tempFilename2}`;
  69. await this.bookConverter.convertToFb2(decompFiles, convertFilename, opts, progress => {
  70. wState.set({progress});
  71. });
  72. //сжимаем файл в tmp, если там уже нет с тем же именем-sha256
  73. const compFilename = await this.decomp.gzipFileIfNotExists(convertFilename, `${this.config.tempPublicDir}`);
  74. wState.set({progress: 100});
  75. //finish
  76. const finishFilename = path.basename(compFilename);
  77. wState.finish({path: `/tmp/${finishFilename}`});
  78. } catch (e) {
  79. log(LM_ERR, e.stack);
  80. wState.set({state: 'error', error: (errMes ? errMes : e.message)});
  81. } finally {
  82. //clean
  83. if (decompDir)
  84. await fs.remove(decompDir);
  85. if (downloadedFilename && !isUploaded)
  86. await fs.remove(downloadedFilename);
  87. if (convertFilename)
  88. await fs.remove(convertFilename);
  89. }
  90. }
  91. loadBookUrl(opts) {
  92. const workerId = this.workerState.generateWorkerId();
  93. const wState = this.workerState.getControl(workerId);
  94. wState.set({state: 'start'});
  95. this.loadBook(opts, wState);
  96. return workerId;
  97. }
  98. async saveFile(file) {
  99. const hash = await utils.getFileHash(file.path, 'sha256', 'hex');
  100. const outFilename = `${this.config.uploadDir}/${hash}`;
  101. if (!await fs.pathExists(outFilename)) {
  102. await fs.move(file.path, outFilename);
  103. } else {
  104. await utils.touchFile(outFilename);
  105. await fs.remove(file.path);
  106. }
  107. return `file://${hash}`;
  108. }
  109. async periodicCleanDir(dir, maxSize, timeout) {
  110. try {
  111. const list = await fs.readdir(dir);
  112. let size = 0;
  113. let files = [];
  114. for (const name of list) {
  115. const stat = await fs.stat(`${dir}/${name}`);
  116. if (!stat.isDirectory()) {
  117. size += stat.size;
  118. files.push({name, stat});
  119. }
  120. }
  121. log(`clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files`);
  122. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  123. let i = 0;
  124. while (i < files.length && size > maxSize) {
  125. const file = files[i];
  126. await fs.remove(`${dir}/${file.name}`);
  127. size -= file.stat.size;
  128. i++;
  129. }
  130. log(`removed ${i} files`);
  131. } catch(e) {
  132. log(LM_ERR, e.stack);
  133. } finally {
  134. setTimeout(() => {
  135. this.periodicCleanDir(dir, maxSize, timeout);
  136. }, timeout);
  137. }
  138. }
  139. }
  140. module.exports = ReaderWorker;