RemoteLib.js 2.4 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 InpxHashCreator = require('./InpxHashCreator');
  7. const log = new (require('./AppLogger'))().log;//singleton
  8. //singleton
  9. let instance = null;
  10. class RemoteLib {
  11. constructor(config) {
  12. if (!instance) {
  13. this.config = config;
  14. this.wsc = new WebSocketConnection(config.remoteLib.url, 10, 30, {rejectUnauthorized: false});
  15. if (config.remoteLib.accessPassword)
  16. this.accessToken = utils.getBufHash(config.remoteLib.accessPassword, 'sha256', 'hex');
  17. this.remoteHost = config.remoteLib.url.replace(/^ws:\/\//, 'http://').replace(/^wss:\/\//, 'https://');
  18. this.down = new FileDownloader(config.maxPayloadSize*1024*1024);
  19. this.inpxHashCreator = new InpxHashCreator(config);
  20. this.inpxFileHash = '';
  21. instance = this;
  22. }
  23. return instance;
  24. }
  25. async wsRequest(query) {
  26. if (this.accessToken)
  27. query.accessToken = this.accessToken;
  28. const response = await this.wsc.message(
  29. await this.wsc.send(query),
  30. 120
  31. );
  32. if (response.error)
  33. throw new Error(response.error);
  34. return response;
  35. }
  36. async downloadInpxFile() {
  37. if (!this.inpxFileHash)
  38. this.inpxFileHash = await this.inpxHashCreator.getInpxFileHash();
  39. const response = await this.wsRequest({action: 'get-inpx-file', inpxFileHash: this.inpxFileHash});
  40. if (response.data) {
  41. await fs.writeFile(this.config.inpxFile, response.data, 'base64');
  42. this.inpxFileHash = '';
  43. }
  44. }
  45. async downloadBook(bookId) {
  46. try {
  47. const response = await await this.wsRequest({action: 'get-book-link', bookId});
  48. const link = response.link;
  49. const buf = await this.down.load(`${this.remoteHost}${link}`, {decompress: false});
  50. const publicPath = `${this.config.publicFilesDir}${link}`;
  51. await fs.writeFile(publicPath, buf);
  52. return path.basename(link);
  53. } catch (e) {
  54. log(LM_ERR, `RemoteLib.downloadBook: ${e.message}`);
  55. throw new Error('502 Bad Gateway');
  56. }
  57. }
  58. }
  59. module.exports = RemoteLib;