RemoteLib.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. this.remoteHost = config.remoteLib.url.replace(/^ws:\/\//, 'http://').replace(/^wss:\/\//, 'https://');
  16. this.down = new FileDownloader(config.maxPayloadSize*1024*1024);
  17. this.inpxHashCreator = new InpxHashCreator(config);
  18. this.inpxFileHash = '';
  19. instance = this;
  20. }
  21. return instance;
  22. }
  23. async wsRequest(query, recurse = false) {
  24. if (this.accessToken)
  25. query.accessToken = this.accessToken;
  26. const response = await this.wsc.message(
  27. await this.wsc.send(query),
  28. 120
  29. );
  30. if (!recurse && response && response.error == 'need_access_token' && this.config.remoteLib.accessPassword) {
  31. this.accessToken = utils.getBufHash(this.config.remoteLib.accessPassword + response.salt, 'sha256', 'hex');
  32. return await this.wsRequest(query, true);
  33. }
  34. if (response.error)
  35. throw new Error(response.error);
  36. return response;
  37. }
  38. async downloadInpxFile() {
  39. if (!this.inpxFileHash)
  40. this.inpxFileHash = await this.inpxHashCreator.getInpxFileHash();
  41. const response = await this.wsRequest({action: 'get-inpx-file', inpxFileHash: this.inpxFileHash});
  42. if (response.data) {
  43. await fs.writeFile(this.config.inpxFile, response.data, 'base64');
  44. this.inpxFileHash = '';
  45. }
  46. }
  47. async downloadBook(bookUid) {
  48. try {
  49. const response = await await this.wsRequest({action: 'get-book-link', bookUid});
  50. const link = response.link;
  51. const buf = await this.down.load(`${this.remoteHost}${link}`, {decompress: false});
  52. const hash = path.basename(link);
  53. const publicPath = `${this.config.bookDir}/${hash}`;
  54. await fs.writeFile(publicPath, buf);
  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;