WebSocketController.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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 cleanUnusedTokenTimeout = 5*60*1000;//5 минут
  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.freeAccess = (config.accessPassword === '');
  15. this.accessTimeout = config.accessTimeout*60*1000;
  16. this.accessMap = new Map();
  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. //почистим accessMap
  34. if (!this.freeAccess) {
  35. for (const [accessToken, accessRec] of this.accessMap) {
  36. if ( !(accessRec.used > 0 || now - accessRec.time < cleanUnusedTokenTimeout)
  37. || !(this.accessTimeout === 0 || now - accessRec.time < this.accessTimeout)
  38. ) {
  39. this.accessMap.delete(accessToken);
  40. }
  41. }
  42. }
  43. //почистим ws-клиентов
  44. this.wss.clients.forEach((ws) => {
  45. if (!ws.lastActivity || now - ws.lastActivity > closeSocketOnIdle - 50) {
  46. ws.terminate();
  47. }
  48. });
  49. } finally {
  50. setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  51. }
  52. }
  53. hasAccess(accessToken) {
  54. if (this.freeAccess)
  55. return true;
  56. const accessRec = this.accessMap.get(accessToken);
  57. if (accessRec) {
  58. const now = Date.now();
  59. if (this.accessTimeout === 0 || now - accessRec.time < this.accessTimeout) {
  60. accessRec.used++;
  61. accessRec.time = now;
  62. return true;
  63. }
  64. }
  65. return false;
  66. }
  67. async onMessage(ws, message) {
  68. let req = {};
  69. try {
  70. if (this.isDevelopment) {
  71. log(`WebSocket-IN: ${message.substr(0, 4000)}`);
  72. }
  73. req = JSON.parse(message);
  74. ws.lastActivity = Date.now();
  75. //pong for WebSocketConnection
  76. this.send({_rok: 1}, req, ws);
  77. //access
  78. if (!this.hasAccess(req.accessToken)) {
  79. await utils.sleep(500);
  80. const salt = utils.randomHexString(32);
  81. const accessToken = utils.getBufHash(this.config.accessPassword + salt, 'sha256', 'hex');
  82. this.accessMap.set(accessToken, {time: Date.now(), used: 0});
  83. this.send({error: 'need_access_token', salt}, req, ws);
  84. return;
  85. }
  86. //api
  87. switch (req.action) {
  88. case 'test':
  89. await this.test(req, ws); break;
  90. case 'logout':
  91. await this.logout(req, ws); break;
  92. case 'get-config':
  93. await this.getConfig(req, ws); break;
  94. case 'get-worker-state':
  95. await this.getWorkerState(req, ws); break;
  96. case 'search':
  97. await this.search(req, ws); break;
  98. case 'get-author-book-list':
  99. await this.getAuthorBookList(req, ws); break;
  100. case 'get-series-book-list':
  101. await this.getSeriesBookList(req, ws); break;
  102. case 'get-genre-tree':
  103. await this.getGenreTree(req, ws); break;
  104. case 'get-book-link':
  105. await this.getBookLink(req, ws); break;
  106. case 'get-book-info':
  107. await this.getBookInfo(req, ws); break;
  108. case 'get-inpx-file':
  109. await this.getInpxFile(req, ws); break;
  110. default:
  111. throw new Error(`Action not found: ${req.action}`);
  112. }
  113. } catch (e) {
  114. this.send({error: e.message}, req, ws);
  115. }
  116. }
  117. send(res, req, ws) {
  118. if (ws.readyState == WebSocket.OPEN) {
  119. ws.lastActivity = Date.now();
  120. let r = res;
  121. if (req.requestId)
  122. r = Object.assign({requestId: req.requestId}, r);
  123. const message = JSON.stringify(r);
  124. ws.send(message);
  125. if (this.isDevelopment) {
  126. log(`WebSocket-OUT: ${message.substr(0, 200)}`);
  127. }
  128. }
  129. }
  130. //Actions ------------------------------------------------------------------
  131. async test(req, ws) {
  132. this.send({message: `${this.config.name} project is awesome`}, req, ws);
  133. }
  134. async logout(req, ws) {
  135. this.accessMap.delete(req.accessToken);
  136. this.send({success: true}, req, ws);
  137. }
  138. async getConfig(req, ws) {
  139. const config = _.pick(this.config, this.config.webConfigParams);
  140. config.dbConfig = await this.webWorker.dbConfig();
  141. config.freeAccess = this.freeAccess;
  142. this.send(config, req, ws);
  143. }
  144. async getWorkerState(req, ws) {
  145. if (!req.workerId)
  146. throw new Error(`key 'workerId' is empty`);
  147. const state = this.workerState.getState(req.workerId);
  148. this.send((state ? state : {}), req, ws);
  149. }
  150. async search(req, ws) {
  151. if (!req.query)
  152. throw new Error(`query is empty`);
  153. if (!req.from)
  154. throw new Error(`from is empty`);
  155. const result = await this.webWorker.search(req.from, req.query);
  156. this.send(result, req, ws);
  157. }
  158. async getAuthorBookList(req, ws) {
  159. const result = await this.webWorker.getAuthorBookList(req.authorId);
  160. this.send(result, req, ws);
  161. }
  162. async getSeriesBookList(req, ws) {
  163. const result = await this.webWorker.getSeriesBookList(req.series);
  164. this.send(result, req, ws);
  165. }
  166. async getGenreTree(req, ws) {
  167. const result = await this.webWorker.getGenreTree();
  168. this.send(result, req, ws);
  169. }
  170. async getBookLink(req, ws) {
  171. if (!utils.hasProp(req, 'bookUid'))
  172. throw new Error(`bookUid is empty`);
  173. const result = await this.webWorker.getBookLink(req.bookUid);
  174. this.send(result, req, ws);
  175. }
  176. async getBookInfo(req, ws) {
  177. if (!utils.hasProp(req, 'bookUid'))
  178. throw new Error(`bookUid is empty`);
  179. const result = await this.webWorker.getBookInfo(req.bookUid);
  180. this.send(result, req, ws);
  181. }
  182. async getInpxFile(req, ws) {
  183. if (!this.config.allowRemoteLib)
  184. throw new Error('Remote lib access disabled');
  185. const result = await this.webWorker.getInpxFile(req);
  186. this.send(result, req, ws);
  187. }
  188. }
  189. module.exports = WebSocketController;