| 1 | import { ProtocolCommand, ProtocolRequest, ProtocolVersion } from '../types/UIProtocol'; |
| 2 | |
| 3 | import AbstractUIService from './WebSocketServices/ui/AbstractUIService'; |
| 4 | import { IncomingMessage } from 'http'; |
| 5 | import UIService from './WebSocketServices/ui/0.0.1/UIService'; |
| 6 | import Utils from '../utils/Utils'; |
| 7 | import WebSocket from 'ws'; |
| 8 | import logger from '../utils/Logger'; |
| 9 | |
| 10 | export default class WebSocketServer extends WebSocket.Server { |
| 11 | private webSocketServerService: AbstractUIService; |
| 12 | |
| 13 | public constructor(options?: WebSocket.ServerOptions, callback?: () => void) { |
| 14 | // Create the WebSocket Server |
| 15 | super(options, callback); |
| 16 | // FIXME: version the instantiation |
| 17 | this.webSocketServerService = new UIService(this); |
| 18 | } |
| 19 | |
| 20 | public broadcastToClients(message: Record<string, unknown>): void { |
| 21 | for (const client of this.clients) { |
| 22 | if (client?.readyState === WebSocket.OPEN) { |
| 23 | client.send(message); |
| 24 | } |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | public start(): void { |
| 29 | this.on('connection', (socket: WebSocket, request: IncomingMessage): void => { |
| 30 | // FIXME: Check connection validity |
| 31 | socket.on('message', (messageData) => { |
| 32 | let [version, command, payload]: ProtocolRequest = [ProtocolVersion['0.0.1'], ProtocolCommand.UNKNOWN, {}]; |
| 33 | // FIXME: check for iterable object |
| 34 | [version, command, payload] = JSON.parse(messageData.toString()) as ProtocolRequest; |
| 35 | switch (version) { |
| 36 | case ProtocolVersion['0.0.1']: |
| 37 | this.webSocketServerService.handleMessage(command, payload).catch(() => { |
| 38 | logger.error(`${this.logPrefix()} Error while handling command %s message: %j`, command, payload); |
| 39 | }); |
| 40 | break; |
| 41 | default: |
| 42 | logger.error(`${this.logPrefix()} Unknown protocol version: ${version}`); |
| 43 | } |
| 44 | }); |
| 45 | socket.on('error', (error) => { |
| 46 | logger.error(`${this.logPrefix()} Error on WebSocket: %j`, error); |
| 47 | }); |
| 48 | }); |
| 49 | } |
| 50 | |
| 51 | public stop(): void { |
| 52 | this.close(); |
| 53 | } |
| 54 | |
| 55 | public logPrefix(): string { |
| 56 | return Utils.logPrefix('WebSocket Server:'); |
| 57 | } |
| 58 | } |