BookUpdateCheckerController.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. const WebSocket = require('ws');
  2. //const _ = require('lodash');
  3. const BUCServer = require('../core/BookUpdateChecker/BUCServer');
  4. const log = new (require('../core/AppLogger'))().log;//singleton
  5. //const utils = require('../core/utils');
  6. const cleanPeriod = 1*60*1000;//1 минута
  7. const closeSocketOnIdle = 5*60*1000;//5 минут
  8. class BookUpdateCheckerController {
  9. constructor(wss, config) {
  10. this.config = config;
  11. this.isDevelopment = (config.branch == 'development');
  12. //this.readerStorage = new JembaReaderStorage();
  13. this.bucServer = new BUCServer(config);
  14. this.bucServer.main(); //no await
  15. this.wss = wss;
  16. wss.on('connection', (ws) => {
  17. ws.on('message', (message) => {
  18. this.onMessage(ws, message.toString());
  19. });
  20. ws.on('error', (err) => {
  21. log(LM_ERR, err);
  22. });
  23. });
  24. setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  25. }
  26. periodicClean() {
  27. try {
  28. const now = Date.now();
  29. this.wss.clients.forEach((ws) => {
  30. if (!ws.lastActivity || now - ws.lastActivity > closeSocketOnIdle - 50) {
  31. ws.terminate();
  32. }
  33. });
  34. } finally {
  35. setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  36. }
  37. }
  38. async onMessage(ws, message) {
  39. let req = {};
  40. try {
  41. if (this.isDevelopment) {
  42. log(`WebSocket-IN: ${message.substr(0, 4000)}`);
  43. }
  44. req = JSON.parse(message);
  45. ws.lastActivity = Date.now();
  46. //pong for WebSocketConnection
  47. this.send({_rok: 1}, req, ws);
  48. switch (req.action) {
  49. case 'test':
  50. await this.test(req, ws); break;
  51. default:
  52. throw new Error(`Action not found: ${req.action}`);
  53. }
  54. } catch (e) {
  55. this.send({error: e.message}, req, ws);
  56. }
  57. }
  58. send(res, req, ws) {
  59. if (ws.readyState == WebSocket.OPEN) {
  60. ws.lastActivity = Date.now();
  61. let r = res;
  62. if (req.requestId)
  63. r = Object.assign({requestId: req.requestId}, r);
  64. const message = JSON.stringify(r);
  65. ws.send(message);
  66. if (this.isDevelopment) {
  67. log(`WebSocket-OUT: ${message.substr(0, 4000)}`);
  68. }
  69. }
  70. }
  71. //Actions ------------------------------------------------------------------
  72. async test(req, ws) {
  73. this.send({message: 'Liberama project is awesome'}, req, ws);
  74. }
  75. }
  76. module.exports = BookUpdateCheckerController;