RemoteLib.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. const fs = require('fs-extra');
  2. const path = require('path');
  3. const utils = require('./utils');
  4. const FileDownloader = require('./FileDownloader');
  5. const WebSocketConnection = require('./WebSocketConnection');
  6. const log = new (require('./AppLogger'))().log;//singleton
  7. //singleton
  8. let instance = null;
  9. class RemoteLib {
  10. constructor(config) {
  11. if (!instance) {
  12. this.config = config;
  13. this.wsc = new WebSocketConnection(config.remoteLib.url, 10, 30, {rejectUnauthorized: false});
  14. if (config.remoteLib.accessPassword)
  15. this.accessToken = utils.getBufHash(config.remoteLib.accessPassword, 'sha256', 'hex');
  16. this.remoteHost = config.remoteLib.url.replace(/^ws:\/\//, 'http://').replace(/^wss:\/\//, 'https://');
  17. this.inpxFile = `${config.tempDir}/${utils.randomHexString(20)}`;
  18. this.lastUpdateTime = 0;
  19. this.down = new FileDownloader(config.maxPayloadSize*1024*1024);
  20. instance = this;
  21. }
  22. return instance;
  23. }
  24. async wsRequest(query) {
  25. if (this.accessToken)
  26. query.accessToken = this.accessToken;
  27. const response = await this.wsc.message(
  28. await this.wsc.send(query),
  29. 120
  30. );
  31. if (response.error)
  32. throw new Error(response.error);
  33. return response;
  34. }
  35. async downloadInpxFile(getPeriod = 0) {
  36. if (getPeriod && Date.now() - this.lastUpdateTime < getPeriod)
  37. return this.inpxFile;
  38. const response = await this.wsRequest({action: 'get-inpx-file'});
  39. await fs.writeFile(this.inpxFile, response.data, 'base64');
  40. this.lastUpdateTime = Date.now();
  41. return this.inpxFile;
  42. }
  43. async downloadBook(bookPath, downFileName) {
  44. try {
  45. const response = await await this.wsRequest({action: 'get-book-link', bookPath, downFileName});
  46. const link = response.link;
  47. const buf = await this.down.load(`${this.remoteHost}${link}`);
  48. const tmpFile = `${this.config.tempDir}/${utils.randomHexString(30)}`;
  49. const tmpFile2 = `${this.config.tempDir}/${utils.randomHexString(30)}`;
  50. const publicPath = `${this.config.publicDir}${link}`;
  51. await fs.writeFile(tmpFile, buf);
  52. await utils.gzipFile(tmpFile, tmpFile2, 4);
  53. await fs.remove(tmpFile);
  54. await fs.move(tmpFile2, publicPath, {overwrite: true});
  55. return path.basename(link);
  56. } catch (e) {
  57. log(LM_ERR, `RemoteLib.downloadBook: ${e.message}`);
  58. throw new Error('502 Bad Gateway');
  59. }
  60. }
  61. }
  62. module.exports = RemoteLib;