ReaderWorker.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. //лениво сохраним compFilename в удаленном хранилище
  87. if (this.remoteWebDavStorage) {
  88. (async() => {
  89. await utils.sleep(20*1000);
  90. try {
  91. //log(`remoteWebDavStorage.putFile ${path.basename(compFilename)}`);
  92. await this.remoteWebDavStorage.putFile(compFilename);
  93. } catch (e) {
  94. log(LM_ERR, e.stack);
  95. }
  96. })();
  97. }
  98. } catch (e) {
  99. log(LM_ERR, e.stack);
  100. wState.set({state: 'error', error: e.message});
  101. } finally {
  102. //clean
  103. if (decompDir)
  104. await fs.remove(decompDir);
  105. if (downloadedFilename && !isUploaded)
  106. await fs.remove(downloadedFilename);
  107. if (convertFilename)
  108. await fs.remove(convertFilename);
  109. }
  110. }
  111. loadBookUrl(opts) {
  112. const workerId = this.workerState.generateWorkerId();
  113. const wState = this.workerState.getControl(workerId);
  114. wState.set({state: 'start'});
  115. this.loadBook(opts, wState);
  116. return workerId;
  117. }
  118. async saveFile(file) {
  119. const hash = await utils.getFileHash(file.path, 'sha256', 'hex');
  120. const outFilename = `${this.config.uploadDir}/${hash}`;
  121. if (!await fs.pathExists(outFilename)) {
  122. await fs.move(file.path, outFilename);
  123. } else {
  124. await utils.touchFile(outFilename);
  125. await fs.remove(file.path);
  126. }
  127. return `file://${hash}`;
  128. }
  129. restoreCachedFile(filename) {
  130. const workerId = this.workerState.generateWorkerId();
  131. const wState = this.workerState.getControl(workerId);
  132. wState.set({state: 'start'});
  133. (async() => {
  134. try {
  135. wState.set({state: 'download', step: 1, totalSteps: 1, path: filename, progress: 0});
  136. const basename = path.basename(filename);
  137. const targetName = `${this.config.tempPublicDir}/${basename}`;
  138. if (!await fs.pathExists(targetName)) {
  139. let found = false;
  140. if (this.remoteWebDavStorage) {
  141. found = await this.remoteWebDavStorage.getFileSuccess(targetName);
  142. }
  143. if (!found) {
  144. throw new Error('404 Файл не найден');
  145. }
  146. }
  147. const stat = await fs.stat(targetName);
  148. wState.finish({path: `/tmp/${basename}`, size: stat.size, progress: 100});
  149. } catch (e) {
  150. if (e.message.indexOf('404') < 0)
  151. log(LM_ERR, e.stack);
  152. wState.set({state: 'error', error: e.message});
  153. }
  154. })();
  155. return workerId;
  156. }
  157. async periodicCleanDir(dir, maxSize, timeout) {
  158. try {
  159. const list = await fs.readdir(dir);
  160. let size = 0;
  161. let files = [];
  162. for (const name of list) {
  163. const stat = await fs.stat(`${dir}/${name}`);
  164. if (!stat.isDirectory()) {
  165. size += stat.size;
  166. files.push({name, stat});
  167. }
  168. }
  169. log(`clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files`);
  170. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  171. let i = 0;
  172. while (i < files.length && size > maxSize) {
  173. const file = files[i];
  174. const oldFile = `${dir}/${file.name}`;
  175. if (this.remoteWebDavStorage) {
  176. try {
  177. //log(`remoteWebDavStorage.putFile ${path.basename(oldFile)}`);
  178. await this.remoteWebDavStorage.putFile(oldFile);
  179. } catch (e) {
  180. log(LM_ERR, e.stack);
  181. }
  182. }
  183. await fs.remove(oldFile);
  184. size -= file.stat.size;
  185. i++;
  186. }
  187. log(`removed ${i} files`);
  188. } catch(e) {
  189. log(LM_ERR, e.stack);
  190. } finally {
  191. setTimeout(() => {
  192. this.periodicCleanDir(dir, maxSize, timeout);
  193. }, timeout);
  194. }
  195. }
  196. }
  197. module.exports = ReaderWorker;