ReaderWorker.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. if (this.config.branch == 'development')
  81. console.error(e);
  82. wState.set({state: 'error', error: (errMes ? errMes : e.message)});
  83. } finally {
  84. //clean
  85. if (decompDir)
  86. await fs.remove(decompDir);
  87. if (downloadedFilename && !isUploaded)
  88. await fs.remove(downloadedFilename);
  89. if (convertFilename)
  90. await fs.remove(convertFilename);
  91. }
  92. }
  93. loadBookUrl(opts) {
  94. const workerId = this.workerState.generateWorkerId();
  95. const wState = this.workerState.getControl(workerId);
  96. wState.set({state: 'start'});
  97. this.loadBook(opts, wState);
  98. return workerId;
  99. }
  100. async saveFile(file) {
  101. const hash = await utils.getFileHash(file.path, 'sha256', 'hex');
  102. const outFilename = `${this.config.uploadDir}/${hash}`;
  103. if (!await fs.pathExists(outFilename)) {
  104. await fs.move(file.path, outFilename);
  105. } else {
  106. await utils.touchFile(outFilename);
  107. await fs.remove(file.path);
  108. }
  109. return `file://${hash}`;
  110. }
  111. async periodicCleanDir(dir, maxSize, timeout) {
  112. try {
  113. log(`Start clean dir: ${dir}, maxSize=${maxSize}`);
  114. const list = await fs.readdir(dir);
  115. let size = 0;
  116. let files = [];
  117. for (const name of list) {
  118. const stat = await fs.stat(`${dir}/${name}`);
  119. if (!stat.isDirectory()) {
  120. size += stat.size;
  121. files.push({name, stat});
  122. }
  123. }
  124. log(`found ${files.length} files in dir ${dir}`);
  125. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  126. let i = 0;
  127. while (i < files.length && size > maxSize) {
  128. const file = files[i];
  129. log(`rm ${dir}/${file.name}`);
  130. await fs.remove(`${dir}/${file.name}`);
  131. size -= file.stat.size;
  132. i++;
  133. }
  134. log(`removed ${i} files`);
  135. } catch(e) {
  136. log(LM_ERR, e.message);
  137. } finally {
  138. setTimeout(() => {
  139. this.periodicCleanDir(dir, maxSize, timeout);
  140. }, timeout);
  141. }
  142. }
  143. }
  144. module.exports = ReaderWorker;