ReaderWorker.js 12 KB

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