ReaderWorker.js 8.1 KB

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