ReaderWorker.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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, 4*60*1000);//4 минуты ожидание подвижек
  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(3*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('disk://') != 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.resetTimeout();
  111. }, q.abort);
  112. //сжимаем файл в tmp, если там уже нет с тем же именем-sha256
  113. const compFilename = await this.decomp.gzipFileIfNotExists(convertFilename, this.config.tempPublicDir);
  114. const stat = await fs.stat(compFilename);
  115. wState.set({progress: 100});
  116. //finish
  117. const finishFilename = path.basename(compFilename);
  118. wState.finish({path: `/tmp/${finishFilename}`, size: stat.size});
  119. //лениво сохраним compFilename в удаленном хранилище
  120. if (this.remoteWebDavStorage) {
  121. (async() => {
  122. await utils.sleep(20*1000);
  123. try {
  124. //log(`remoteWebDavStorage.putFile ${path.basename(compFilename)}`);
  125. await this.remoteWebDavStorage.putFile(compFilename);
  126. } catch (e) {
  127. log(LM_ERR, e.stack);
  128. }
  129. })();
  130. }
  131. //лениво сохраним downloadedFilename в tmp и в удаленном хранилище в случае isUploaded
  132. if (this.remoteWebDavStorage && isUploaded && !isRestored) {
  133. (async() => {
  134. await utils.sleep(30*1000);
  135. try {
  136. //сжимаем файл в tmp, если там уже нет с тем же именем-sha256
  137. const compDownloadedFilename = await this.decomp.gzipFileIfNotExists(downloadedFilename, this.config.tempPublicDir, true);
  138. await this.remoteWebDavStorage.putFile(compDownloadedFilename);
  139. } catch (e) {
  140. log(LM_ERR, e.stack);
  141. }
  142. })();
  143. }
  144. } catch (e) {
  145. log(LM_ERR, e.stack);
  146. let mes = e.message.split('|FORLOG|');
  147. if (mes[1])
  148. log(LM_ERR, mes[0] + mes[1]);
  149. log(LM_ERR, `downloadedFilename: ${downloadedFilename}`);
  150. mes = mes[0];
  151. if (mes == 'abort')
  152. mes = overLoadMes;
  153. wState.set({state: 'error', error: mes});
  154. } finally {
  155. //clean
  156. if (q)
  157. q.ret();
  158. if (decompDir)
  159. await fs.remove(decompDir);
  160. if (downloadedFilename && !isUploaded)
  161. await fs.remove(downloadedFilename);
  162. if (convertFilename)
  163. await fs.remove(convertFilename);
  164. }
  165. }
  166. loadBookUrl(opts) {
  167. const workerId = this.workerState.generateWorkerId();
  168. const wState = this.workerState.getControl(workerId);
  169. wState.set({state: 'start'});
  170. this.loadBook(opts, wState);
  171. return workerId;
  172. }
  173. async saveFile(file) {
  174. const hash = await utils.getFileHash(file.path, 'sha256', 'hex');
  175. const outFilename = `${this.config.uploadDir}/${hash}`;
  176. if (!await fs.pathExists(outFilename)) {
  177. await fs.move(file.path, outFilename);
  178. } else {
  179. await utils.touchFile(outFilename);
  180. await fs.remove(file.path);
  181. }
  182. return `disk://${hash}`;
  183. }
  184. async restoreRemoteFile(filename) {
  185. const basename = path.basename(filename);
  186. const targetName = `${this.config.tempPublicDir}/${basename}`;
  187. if (!await fs.pathExists(targetName)) {
  188. let found = false;
  189. if (this.remoteWebDavStorage) {
  190. found = await this.remoteWebDavStorage.getFileSuccess(targetName);
  191. }
  192. if (!found) {
  193. throw new Error('404 Файл не найден');
  194. }
  195. }
  196. return targetName;
  197. }
  198. restoreCachedFile(filename) {
  199. const workerId = this.workerState.generateWorkerId();
  200. const wState = this.workerState.getControl(workerId);
  201. wState.set({state: 'start'});
  202. (async() => {
  203. try {
  204. wState.set({state: 'download', step: 1, totalSteps: 1, path: filename, progress: 0});
  205. const targetName = await this.restoreRemoteFile(filename);
  206. const stat = await fs.stat(targetName);
  207. const basename = path.basename(filename);
  208. wState.finish({path: `/tmp/${basename}`, size: stat.size, progress: 100});
  209. } catch (e) {
  210. if (e.message.indexOf('404') < 0)
  211. log(LM_ERR, e.stack);
  212. wState.set({state: 'error', error: e.message});
  213. }
  214. })();
  215. return workerId;
  216. }
  217. async periodicCleanDir(dir, maxSize, timeout) {
  218. try {
  219. const list = await fs.readdir(dir);
  220. let size = 0;
  221. let files = [];
  222. for (const name of list) {
  223. const stat = await fs.stat(`${dir}/${name}`);
  224. if (!stat.isDirectory()) {
  225. size += stat.size;
  226. files.push({name, stat});
  227. }
  228. }
  229. log(`clean dir ${dir}, maxSize=${maxSize}, found ${files.length} files, total size=${size}`);
  230. files.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  231. let i = 0;
  232. let j = 0;
  233. while (i < files.length && size > maxSize) {
  234. const file = files[i];
  235. const oldFile = `${dir}/${file.name}`;
  236. let remoteSuccess = true;
  237. //отправляем только this.config.tempPublicDir
  238. if (this.remoteWebDavStorage && dir === this.config.tempPublicDir) {
  239. remoteSuccess = false;
  240. try {
  241. //log(`remoteWebDavStorage.putFile ${path.basename(oldFile)}`);
  242. await this.remoteWebDavStorage.putFile(oldFile);
  243. remoteSuccess = true;
  244. } catch (e) {
  245. log(LM_ERR, e.stack);
  246. }
  247. }
  248. //реально удаляем только если сохранили в хранилище
  249. if (remoteSuccess || size > maxSize*1.2) {
  250. await fs.remove(oldFile);
  251. j++;
  252. }
  253. size -= file.stat.size;
  254. i++;
  255. }
  256. log(`removed ${j} files`);
  257. } catch(e) {
  258. log(LM_ERR, e.stack);
  259. } finally {
  260. setTimeout(() => {
  261. this.periodicCleanDir(dir, maxSize, timeout);
  262. }, timeout);
  263. }
  264. }
  265. }
  266. module.exports = ReaderWorker;