WebSocketController.js 5.4 KB

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