WebSocketController.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. const fs = require('fs-extra');
  2. const _ = require('lodash');
  3. const WebSocket = require ('ws');
  4. const WorkerState = require('../core/WorkerState');//singleton
  5. const WebWorker = require('../core/WebWorker');//singleton
  6. const log = new (require('../core/AppLogger'))().log;//singleton
  7. const utils = require('../core/utils');
  8. const cleanPeriod = 1*60*1000;//1 минута
  9. const closeSocketOnIdle = 5*60*1000;//5 минут
  10. class WebSocketController {
  11. constructor(wss, config) {
  12. this.config = config;
  13. this.isDevelopment = (config.branch == 'development');
  14. this.accessToken = '';
  15. if (config.accessPassword)
  16. this.accessToken = utils.getBufHash(config.accessPassword, 'sha256', 'hex');
  17. this.workerState = new WorkerState();
  18. this.webWorker = new WebWorker(config);
  19. this.wss = wss;
  20. wss.on('connection', (ws) => {
  21. ws.on('message', (message) => {
  22. this.onMessage(ws, message.toString());
  23. });
  24. ws.on('error', (err) => {
  25. log(LM_ERR, err);
  26. });
  27. });
  28. setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  29. }
  30. periodicClean() {
  31. try {
  32. const now = Date.now();
  33. this.wss.clients.forEach((ws) => {
  34. if (!ws.lastActivity || now - ws.lastActivity > closeSocketOnIdle - 50) {
  35. ws.terminate();
  36. }
  37. });
  38. } finally {
  39. setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  40. }
  41. }
  42. async onMessage(ws, message) {
  43. let req = {};
  44. try {
  45. if (this.isDevelopment) {
  46. log(`WebSocket-IN: ${message.substr(0, 4000)}`);
  47. }
  48. req = JSON.parse(message);
  49. ws.lastActivity = Date.now();
  50. //pong for WebSocketConnection
  51. this.send({_rok: 1}, req, ws);
  52. if (this.accessToken && req.accessToken !== this.accessToken) {
  53. await utils.sleep(1000);
  54. throw new Error('need_access_token');
  55. }
  56. switch (req.action) {
  57. case 'test':
  58. await this.test(req, ws); break;
  59. case 'get-config':
  60. await this.getConfig(req, ws); break;
  61. case 'get-worker-state':
  62. await this.getWorkerState(req, ws); break;
  63. case 'search':
  64. await this.search(req, ws); break;
  65. case 'get-book-list':
  66. await this.getBookList(req, ws); break;
  67. case 'get-series-book-list':
  68. await this.getSeriesBookList(req, ws); break;
  69. case 'get-genre-tree':
  70. await this.getGenreTree(req, ws); break;
  71. case 'get-book-link':
  72. await this.getBookLink(req, ws); break;
  73. case 'get-inpx-file':
  74. await this.getInpxFile(req, ws); break;
  75. default:
  76. throw new Error(`Action not found: ${req.action}`);
  77. }
  78. } catch (e) {
  79. this.send({error: e.message}, req, ws);
  80. }
  81. }
  82. send(res, req, ws) {
  83. if (ws.readyState == WebSocket.OPEN) {
  84. ws.lastActivity = Date.now();
  85. let r = res;
  86. if (req.requestId)
  87. r = Object.assign({requestId: req.requestId}, r);
  88. const message = JSON.stringify(r);
  89. ws.send(message);
  90. if (this.isDevelopment) {
  91. log(`WebSocket-OUT: ${message.substr(0, 4000)}`);
  92. }
  93. }
  94. }
  95. //Actions ------------------------------------------------------------------
  96. async test(req, ws) {
  97. this.send({message: `${this.config.name} project is awesome`}, req, ws);
  98. }
  99. async getConfig(req, ws) {
  100. const config = _.pick(this.config, this.config.webConfigParams);
  101. config.dbConfig = await this.webWorker.dbConfig();
  102. this.send(config, req, ws);
  103. }
  104. async getWorkerState(req, ws) {
  105. if (!req.workerId)
  106. throw new Error(`key 'workerId' is empty`);
  107. const state = this.workerState.getState(req.workerId);
  108. this.send((state ? state : {}), req, ws);
  109. }
  110. async search(req, ws) {
  111. if (!req.query)
  112. throw new Error(`query is empty`);
  113. const result = await this.webWorker.search(req.query);
  114. this.send(result, req, ws);
  115. }
  116. async getBookList(req, ws) {
  117. if (!utils.hasProp(req, 'authorId'))
  118. throw new Error(`authorId is empty`);
  119. const result = await this.webWorker.getBookList(req.authorId);
  120. this.send(result, req, ws);
  121. }
  122. async getSeriesBookList(req, ws) {
  123. if (!utils.hasProp(req, 'series'))
  124. throw new Error(`series is empty`);
  125. const result = await this.webWorker.getSeriesBookList(req.series);
  126. this.send(result, req, ws);
  127. }
  128. async getGenreTree(req, ws) {
  129. const result = await this.webWorker.getGenreTree();
  130. this.send(result, req, ws);
  131. }
  132. async getBookLink(req, ws) {
  133. if (!utils.hasProp(req, 'bookPath'))
  134. throw new Error(`bookPath is empty`);
  135. if (!utils.hasProp(req, 'downFileName'))
  136. throw new Error(`downFileName is empty`);
  137. const result = await this.webWorker.getBookLink({bookPath: req.bookPath, downFileName: req.downFileName});
  138. this.send(result, req, ws);
  139. }
  140. async getInpxFile(req, ws) {
  141. if (!this.config.allowRemoteLib)
  142. throw new Error('Remote lib access disabled');
  143. const data = await fs.readFile(this.config.inpxFile, 'base64');
  144. this.send({data}, req, ws);
  145. }
  146. }
  147. module.exports = WebSocketController;