BookUpdateCheckerController.js 2.5 KB

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