ReaderWorker.js 8.2 KB

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