WebSocketController.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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, webAccess, config) {
  11. this.config = config;
  12. this.isDevelopment = (config.branch == 'development');
  13. this.webAccess = webAccess;
  14. this.workerState = new WorkerState();
  15. this.webWorker = new WebWorker(config);
  16. this.wss = wss;
  17. wss.on('connection', (ws) => {
  18. ws.on('message', (message) => {
  19. this.onMessage(ws, message.toString());
  20. });
  21. ws.on('error', (err) => {
  22. log(LM_ERR, err);
  23. });
  24. });
  25. this.periodicClean();//no await
  26. }
  27. async periodicClean() {
  28. while (1) {//eslint-disable-line no-constant-condition
  29. try {
  30. const now = Date.now();
  31. //почистим ws-клиентов
  32. this.wss.clients.forEach((ws) => {
  33. if (!ws.lastActivity || now - ws.lastActivity > closeSocketOnIdle - 50) {
  34. ws.terminate();
  35. }
  36. });
  37. } catch(e) {
  38. log(LM_ERR, `WebSocketController.periodicClean error: ${e.message}`);
  39. }
  40. await utils.sleep(cleanPeriod);
  41. }
  42. }
  43. async onMessage(ws, message) {
  44. let req = {};
  45. try {
  46. if (this.isDevelopment) {
  47. log(`WebSocket-IN: ${message.substr(0, 4000)}`);
  48. }
  49. req = JSON.parse(message);
  50. ws.lastActivity = Date.now();
  51. //pong for WebSocketConnection
  52. this.send({_rok: 1}, req, ws);
  53. //access
  54. if (!await this.webAccess.hasAccess(req.accessToken)) {
  55. await utils.sleep(500);
  56. const salt = this.webAccess.newToken();
  57. this.send({error: 'need_access_token', salt}, req, ws);
  58. return;
  59. }
  60. //api
  61. switch (req.action) {
  62. case 'test':
  63. await this.test(req, ws); break;
  64. case 'logout':
  65. await this.logout(req, ws); break;
  66. case 'get-config':
  67. await this.getConfig(req, ws); break;
  68. case 'get-worker-state':
  69. await this.getWorkerState(req, ws); break;
  70. case 'search':
  71. await this.search(req, ws); break;
  72. case 'bookSearch':
  73. await this.bookSearch(req, ws); break;
  74. case 'get-author-book-list':
  75. await this.getAuthorBookList(req, ws); break;
  76. case 'get-author-series-list':
  77. await this.getAuthorSeriesList(req, ws); break;
  78. case 'get-series-book-list':
  79. await this.getSeriesBookList(req, ws); break;
  80. case 'get-genre-tree':
  81. await this.getGenreTree(req, ws); break;
  82. case 'get-book-link':
  83. await this.getBookLink(req, ws); break;
  84. case 'get-book-info':
  85. await this.getBookInfo(req, ws); break;
  86. case 'get-inpx-file':
  87. await this.getInpxFile(req, ws); break;
  88. default:
  89. throw new Error(`Action not found: ${req.action}`);
  90. }
  91. } catch (e) {
  92. this.send({error: e.message}, req, ws);
  93. }
  94. }
  95. send(res, req, ws) {
  96. if (ws.readyState == WebSocket.OPEN) {
  97. ws.lastActivity = Date.now();
  98. let r = res;
  99. if (req.requestId)
  100. r = Object.assign({requestId: req.requestId}, r);
  101. const message = JSON.stringify(r);
  102. ws.send(message);
  103. if (this.isDevelopment) {
  104. log(`WebSocket-OUT: ${message.substr(0, 200)}`);
  105. }
  106. }
  107. }
  108. //Actions ------------------------------------------------------------------
  109. async test(req, ws) {
  110. this.send({message: `${this.config.name} project is awesome`}, req, ws);
  111. }
  112. async logout(req, ws) {
  113. await this.webAccess.deleteAccess(req.accessToken);
  114. this.send({success: true}, req, ws);
  115. }
  116. async getConfig(req, ws) {
  117. const config = _.pick(this.config, this.config.webConfigParams);
  118. config.dbConfig = await this.webWorker.dbConfig();
  119. config.freeAccess = this.webAccess.freeAccess;
  120. this.send(config, req, ws);
  121. }
  122. async getWorkerState(req, ws) {
  123. if (!req.workerId)
  124. throw new Error(`key 'workerId' is empty`);
  125. const state = this.workerState.getState(req.workerId);
  126. this.send((state ? state : {}), req, ws);
  127. }
  128. async search(req, ws) {
  129. if (!req.query)
  130. throw new Error(`query is empty`);
  131. if (!req.from)
  132. throw new Error(`from is empty`);
  133. const result = await this.webWorker.search(req.from, req.query);
  134. this.send(result, req, ws);
  135. }
  136. async bookSearch(req, ws) {
  137. if (!this.config.extendedSearch)
  138. throw new Error('config.extendedSearch disabled');
  139. if (!req.query)
  140. throw new Error(`query is empty`);
  141. const result = await this.webWorker.bookSearch(req.query);
  142. this.send(result, req, ws);
  143. }
  144. async getAuthorBookList(req, ws) {
  145. const result = await this.webWorker.getAuthorBookList(req.authorId);
  146. this.send(result, req, ws);
  147. }
  148. async getAuthorSeriesList(req, ws) {
  149. const result = await this.webWorker.getAuthorSeriesList(req.authorId);
  150. this.send(result, req, ws);
  151. }
  152. async getSeriesBookList(req, ws) {
  153. const result = await this.webWorker.getSeriesBookList(req.series);
  154. this.send(result, req, ws);
  155. }
  156. async getGenreTree(req, ws) {
  157. const result = await this.webWorker.getGenreTree();
  158. this.send(result, req, ws);
  159. }
  160. async getBookLink(req, ws) {
  161. if (!utils.hasProp(req, 'bookUid'))
  162. throw new Error(`bookUid is empty`);
  163. const result = await this.webWorker.getBookLink(req.bookUid);
  164. this.send(result, req, ws);
  165. }
  166. async getBookInfo(req, ws) {
  167. if (!utils.hasProp(req, 'bookUid'))
  168. throw new Error(`bookUid is empty`);
  169. const result = await this.webWorker.getBookInfo(req.bookUid);
  170. this.send(result, req, ws);
  171. }
  172. async getInpxFile(req, ws) {
  173. if (!this.config.allowRemoteLib)
  174. throw new Error('Remote lib access disabled');
  175. const result = await this.webWorker.getInpxFile(req);
  176. this.send(result, req, ws);
  177. }
  178. }
  179. module.exports = WebSocketController;