WebSocketController.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. const WebSocket = require ('ws');
  2. const _ = require('lodash');
  3. const ReaderWorker = require('../core/Reader/ReaderWorker');//singleton
  4. const JembaReaderStorage = require('../core/Reader/JembaReaderStorage');//singleton
  5. const WorkerState = require('../core/WorkerState');//singleton
  6. const BUCClient = require('../core/BookUpdateChecker/BUCClient');//singleton
  7. const log = new (require('../core/AppLogger'))().log;//singleton
  8. const utils = require('../core/utils');
  9. const cleanPeriod = 1*60*1000;//1 минута
  10. const closeSocketOnIdle = 5*60*1000;//5 минут
  11. class WebSocketController {
  12. constructor(wss, config) {
  13. this.config = config;
  14. this.isDevelopment = (config.branch == 'development');
  15. this.readerStorage = new JembaReaderStorage();
  16. this.readerWorker = new ReaderWorker(config);
  17. this.workerState = new WorkerState();
  18. if (config.bucEnabled) {
  19. this.bucClient = new BUCClient(config);
  20. }
  21. this.wss = wss;
  22. wss.on('connection', (ws) => {
  23. ws.on('message', (message) => {
  24. this.onMessage(ws, message.toString());
  25. });
  26. ws.on('error', (err) => {
  27. log(LM_ERR, err);
  28. });
  29. });
  30. setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  31. }
  32. periodicClean() {
  33. try {
  34. const now = Date.now();
  35. this.wss.clients.forEach((ws) => {
  36. if (!ws.lastActivity || now - ws.lastActivity > closeSocketOnIdle - 50) {
  37. ws.terminate();
  38. }
  39. });
  40. } finally {
  41. setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  42. }
  43. }
  44. async onMessage(ws, message) {
  45. let req = {};
  46. try {
  47. if (this.isDevelopment) {
  48. log(`WebSocket-IN: ${message.substr(0, 4000)}`);
  49. }
  50. req = JSON.parse(message);
  51. ws.lastActivity = Date.now();
  52. //pong for WebSocketConnection
  53. this.send({_rok: 1}, req, ws);
  54. switch (req.action) {
  55. case 'test':
  56. await this.test(req, ws); break;
  57. case 'get-config':
  58. await this.getConfig(req, ws); break;
  59. case 'worker-get-state':
  60. await this.workerGetState(req, ws); break;
  61. case 'worker-get-state-finish':
  62. await this.workerGetStateFinish(req, ws); break;
  63. case 'reader-storage':
  64. await this.readerStorageDo(req, ws); break;
  65. case 'upload-file-buf':
  66. await this.uploadFileBuf(req, ws); break;
  67. case 'upload-file-touch':
  68. await this.uploadFileTouch(req, ws); break;
  69. case 'check-buc':
  70. await this.checkBuc(req, ws); break;
  71. default:
  72. throw new Error(`Action not found: ${req.action}`);
  73. }
  74. } catch (e) {
  75. this.send({error: e.message}, req, ws);
  76. }
  77. }
  78. send(res, req, ws) {
  79. if (ws.readyState == WebSocket.OPEN) {
  80. ws.lastActivity = Date.now();
  81. let r = res;
  82. if (req.requestId)
  83. r = Object.assign({requestId: req.requestId}, r);
  84. const message = JSON.stringify(r);
  85. ws.send(message);
  86. if (this.isDevelopment) {
  87. log(`WebSocket-OUT: ${message.substr(0, 4000)}`);
  88. }
  89. }
  90. }
  91. //Actions ------------------------------------------------------------------
  92. async test(req, ws) {
  93. this.send({message: 'Liberama project is awesome'}, req, ws);
  94. }
  95. async getConfig(req, ws) {
  96. if (Array.isArray(req.params)) {
  97. const paramsSet = new Set(req.params);
  98. this.send(_.pick(this.config, this.config.webConfigParams.filter(x => paramsSet.has(x))), req, ws);
  99. } else {
  100. throw new Error('params is not an array');
  101. }
  102. }
  103. async workerGetState(req, ws) {
  104. if (!req.workerId)
  105. throw new Error(`key 'workerId' is wrong`);
  106. const state = this.workerState.getState(req.workerId);
  107. this.send((state ? state : {}), req, ws);
  108. }
  109. async workerGetStateFinish(req, ws) {
  110. if (!req.workerId)
  111. throw new Error(`key 'workerId' is wrong`);
  112. const refreshPause = 200;
  113. let i = 0;
  114. let state = {};
  115. while (1) {// eslint-disable-line no-constant-condition
  116. const prevProgress = state.progress || -1;
  117. const prevState = state.state || '';
  118. const lastModified = state.lastModified || 0;
  119. state = this.workerState.getState(req.workerId);
  120. this.send((state && lastModified != state.lastModified ? state : {}), req, ws);
  121. if (!state) break;
  122. if (state.state != 'finish' && state.state != 'error')
  123. await utils.sleep(refreshPause);
  124. else
  125. break;
  126. i++;
  127. if (i > 3*60*1000/refreshPause) {//3 мин ждем телодвижений воркера
  128. this.send({state: 'error', error: 'Время ожидания процесса истекло'}, req, ws);
  129. break;
  130. }
  131. i = (prevProgress != state.progress || prevState != state.state ? 1 : i);
  132. }
  133. }
  134. async readerStorageDo(req, ws) {
  135. if (!req.body)
  136. throw new Error(`key 'body' is empty`);
  137. if (!req.body.action)
  138. throw new Error(`key 'action' is empty`);
  139. if (!req.body.items || Array.isArray(req.body.data))
  140. throw new Error(`key 'items' is empty`);
  141. this.send(await this.readerStorage.doAction(req.body), req, ws);
  142. }
  143. async uploadFileBuf(req, ws) {
  144. if (!req.buf)
  145. throw new Error(`key 'buf' is empty`);
  146. this.send({url: await this.readerWorker.saveFileBuf(req.buf)}, req, ws);
  147. }
  148. async uploadFileTouch(req, ws) {
  149. if (!req.url)
  150. throw new Error(`key 'url' is empty`);
  151. this.send({url: await this.readerWorker.uploadFileTouch(req.url)}, req, ws);
  152. }
  153. async checkBuc(req, ws) {
  154. if (!this.config.bucEnabled)
  155. throw new Error('BookUpdateChecker disabled');
  156. if (!req.bookUrls)
  157. throw new Error(`key 'bookUrls' is empty`);
  158. if (!Array.isArray(req.bookUrls))
  159. throw new Error(`key 'bookUrls' must be array`);
  160. const data = await this.bucClient.checkBuc(req.bookUrls);
  161. this.send({state: 'success', data}, req, ws);
  162. }
  163. }
  164. module.exports = WebSocketController;