RemoteLib.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 publicPath = `${this.config.publicDir}${link}`;
  49. await fs.writeFile(publicPath, buf);
  50. return path.basename(link);
  51. } catch (e) {
  52. log(LM_ERR, `RemoteLib.downloadBook: ${e.message}`);
  53. throw new Error('502 Bad Gateway');
  54. }
  55. }
  56. }
  57. module.exports = RemoteLib;