ReaderWorker.js 10 KB

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