ReaderWorker.js 9.8 KB

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