ReaderWorker.js 11 KB

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