ReaderWorker.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. const workerState = require('./workerState');
  2. const utils = require('./utils');
  3. const fs = require('fs-extra');
  4. const util = require('util');
  5. const stream = require('stream');
  6. const pipeline = util.promisify(stream.pipeline);
  7. const download = require('download');
  8. class ReaderWorker {
  9. constructor(config) {
  10. this.config = config;
  11. this.tempDownloadDir = `${config.tempDir}/download`;
  12. fs.ensureDirSync(this.tempDownloadDir);
  13. }
  14. async loadBook(wState, url) {
  15. const maxDownloadSize = 10*1024*1024;
  16. let errMes = '';
  17. try {
  18. wState.set({state: 'download', step: 1, totalSteps: 3, url});
  19. const tempFilename = utils.randomHexString(30);
  20. const d = download(url);
  21. d.on('downloadProgress', progress => {
  22. wState.set({progress: Math.round(progress.percent*100)});
  23. if (progress.transferred > maxDownloadSize) {
  24. errMes = 'file too big';
  25. d.destroy();
  26. }
  27. });
  28. await pipeline(d, fs.createWriteStream(`${this.tempDownloadDir}/${tempFilename}`));
  29. wState.finish({step: 3, file: tempFilename});
  30. } catch (e) {
  31. wState.set({state: 'error', error: (errMes ? errMes : e.message)});
  32. }
  33. }
  34. loadBookUrl(url) {
  35. const workerId = workerState.generateWorkerId();
  36. const wState = workerState.getControl(workerId);
  37. wState.set({state: 'start'});
  38. this.loadBook(wState, url);
  39. return workerId;
  40. }
  41. }
  42. module.exports = ReaderWorker;