ReaderWorker.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. const fs = require('fs-extra');
  2. const workerState = require('./workerState');
  3. const FileDownloader = require('./FileDownloader');
  4. const FileDecompressor = require('./FileDecompressor');
  5. const BookConverter = require('./BookConverter');
  6. const utils = require('./utils');
  7. class ReaderWorker {
  8. constructor(config) {
  9. this.config = Object.assign({}, config);
  10. this.config.tempDownloadDir = `${config.tempDir}/download`;
  11. fs.ensureDirSync(this.config.tempDownloadDir);
  12. this.config.tempPublicDir = `${config.publicDir}/tmp`;
  13. fs.ensureDirSync(this.config.tempPublicDir);
  14. this.down = new FileDownloader();
  15. this.decomp = new FileDecompressor();
  16. this.bookConverter = new BookConverter();
  17. }
  18. async loadBook(url, wState) {
  19. let errMes = '';
  20. let decompDir = '';
  21. let downloadedFilename = '';
  22. try {
  23. wState.set({state: 'download', step: 1, totalSteps: 3, url});
  24. const tempFilename = utils.randomHexString(30);
  25. const tempFilename2 = utils.randomHexString(30);
  26. const decompDirname = utils.randomHexString(30);
  27. //download
  28. const downdata = await this.down.load(url, (progress) => {
  29. wState.set({progress});
  30. });
  31. downloadedFilename = `${this.config.tempDownloadDir}/${tempFilename}`;
  32. await fs.writeFile(downloadedFilename, downdata);
  33. wState.set({progress: 100});
  34. //decompress
  35. wState.set({state: 'decompress', step: 2, progress: 0});
  36. decompDir = `${this.config.tempDownloadDir}/${decompDirname}`;
  37. const decompFilename = await this.decomp.decompressFile(downloadedFilename, decompDir);
  38. wState.set({progress: 100});
  39. //parse book
  40. wState.set({state: 'parse', step: 3, progress: 0});
  41. let resultFilename = `${this.config.tempPublicDir}/${tempFilename2}`;
  42. await this.bookConverter.convertToFb2(decompFilename, resultFilename, url, progress => {
  43. wState.set({progress});
  44. });
  45. wState.set({progress: 100});
  46. //finish
  47. wState.finish({path: `/tmp/${tempFilename2}`});
  48. } catch (e) {
  49. wState.set({state: 'error', error: (errMes ? errMes : e.message)});
  50. } finally {
  51. //clean
  52. if (decompDir)
  53. await fs.remove(decompDir);
  54. if (downloadedFilename)
  55. await fs.remove(downloadedFilename);
  56. }
  57. }
  58. loadBookUrl(url) {
  59. const workerId = workerState.generateWorkerId();
  60. const wState = workerState.getControl(workerId);
  61. wState.set({state: 'start'});
  62. this.loadBook(url, wState);
  63. return workerId;
  64. }
  65. }
  66. module.exports = ReaderWorker;