WebSocketController.js 5.6 KB

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