ReaderWorker.js 6.5 KB

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