WebSocketController.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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 'author-search':
  63. await this.authorSearch(req, ws); break;
  64. case 'series-search':
  65. await this.seriesSearch(req, ws); break;
  66. case 'get-author-book-list':
  67. await this.getAuthorBookList(req, ws); break;
  68. case 'get-series-book-list':
  69. await this.getSeriesBookList(req, ws); break;
  70. case 'get-genre-tree':
  71. await this.getGenreTree(req, ws); break;
  72. case 'get-book-link':
  73. await this.getBookLink(req, ws); break;
  74. case 'get-inpx-file':
  75. await this.getInpxFile(req, ws); break;
  76. default:
  77. throw new Error(`Action not found: ${req.action}`);
  78. }
  79. } catch (e) {
  80. this.send({error: e.message}, req, ws);
  81. }
  82. }
  83. send(res, req, ws) {
  84. if (ws.readyState == WebSocket.OPEN) {
  85. ws.lastActivity = Date.now();
  86. let r = res;
  87. if (req.requestId)
  88. r = Object.assign({requestId: req.requestId}, r);
  89. const message = JSON.stringify(r);
  90. ws.send(message);
  91. if (this.isDevelopment) {
  92. log(`WebSocket-OUT: ${message.substr(0, 200)}`);
  93. }
  94. }
  95. }
  96. //Actions ------------------------------------------------------------------
  97. async test(req, ws) {
  98. this.send({message: `${this.config.name} project is awesome`}, req, ws);
  99. }
  100. async getConfig(req, ws) {
  101. const config = _.pick(this.config, this.config.webConfigParams);
  102. config.dbConfig = await this.webWorker.dbConfig();
  103. this.send(config, req, ws);
  104. }
  105. async getWorkerState(req, ws) {
  106. if (!req.workerId)
  107. throw new Error(`key 'workerId' is empty`);
  108. const state = this.workerState.getState(req.workerId);
  109. this.send((state ? state : {}), req, ws);
  110. }
  111. async authorSearch(req, ws) {
  112. if (!req.query)
  113. throw new Error(`query is empty`);
  114. const result = await this.webWorker.authorSearch(req.query);
  115. this.send(result, req, ws);
  116. }
  117. async seriesSearch(req, ws) {
  118. if (!this.config.extendedSearch)
  119. throw new Error(`Extended search disabled`);
  120. if (!req.query)
  121. throw new Error(`query is empty`);
  122. const result = await this.webWorker.seriesSearch(req.query);
  123. this.send(result, req, ws);
  124. }
  125. async getAuthorBookList(req, ws) {
  126. const result = await this.webWorker.getAuthorBookList(req.authorId);
  127. this.send(result, req, ws);
  128. }
  129. async getSeriesBookList(req, ws) {
  130. const result = await this.webWorker.getSeriesBookList(req.series, req.seriesId);
  131. this.send(result, req, ws);
  132. }
  133. async getGenreTree(req, ws) {
  134. const result = await this.webWorker.getGenreTree();
  135. this.send(result, req, ws);
  136. }
  137. async getBookLink(req, ws) {
  138. if (!utils.hasProp(req, 'bookPath'))
  139. throw new Error(`bookPath is empty`);
  140. if (!utils.hasProp(req, 'downFileName'))
  141. throw new Error(`downFileName is empty`);
  142. const result = await this.webWorker.getBookLink({bookPath: req.bookPath, downFileName: req.downFileName});
  143. this.send(result, req, ws);
  144. }
  145. async getInpxFile(req, ws) {
  146. if (!this.config.allowRemoteLib)
  147. throw new Error('Remote lib access disabled');
  148. const result = await this.webWorker.getInpxFile(req);
  149. this.send(result, req, ws);
  150. }
  151. }
  152. module.exports = WebSocketController;