RemoteLib.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. const fs = require('fs-extra');
  2. const utils = require('./utils');
  3. const WebSocketConnection = require('./WebSocketConnection');
  4. //singleton
  5. let instance = null;
  6. class RemoteLib {
  7. constructor(config) {
  8. if (!instance) {
  9. this.config = config;
  10. this.wsc = new WebSocketConnection(config.remoteLib.url, 10, 30, {rejectUnauthorized: false});
  11. if (config.remoteLib.accessPassword)
  12. this.accessToken = utils.getBufHash(config.remoteLib.accessPassword, 'sha256', 'hex');
  13. this.inpxFile = `${config.tempDir}/${utils.randomHexString(20)}`;
  14. this.lastUpdateTime = 0;
  15. instance = this;
  16. }
  17. return instance;
  18. }
  19. async wsRequest(query) {
  20. if (this.accessToken)
  21. query.accessToken = this.accessToken;
  22. const response = await this.wsc.message(
  23. await this.wsc.send(query, 60),
  24. 60
  25. );
  26. if (response.error)
  27. throw new Error(response.error);
  28. return response;
  29. }
  30. async getInpxFile(getPeriod = 0) {
  31. if (getPeriod && Date.now() - this.lastUpdateTime < getPeriod)
  32. return this.inpxFile;
  33. const response = await this.wsRequest({action: 'get-inpx-file'});
  34. await fs.writeFile(this.inpxFile, response.data, 'base64');
  35. this.lastUpdateTime = Date.now();
  36. return this.inpxFile;
  37. }
  38. }
  39. module.exports = RemoteLib;