import * as ws from 'ws'; import { Request } from 'express'; import { conf } from '../helpers/ConfigHelper'; /** * RTC WebSocket relay controller * * @author Pierre HUBERT */ export interface RTCSocketMessage { title: string, callId ?: string, peerId ?: string, data: any } export class RTCRelayController { /** * Current WebSocket connection */ private static currWs: ws; /** * Open new websocket * * @param req Request * @param ws Websocket */ public static async OpenWS(req: Request, ws: ws) { // First, check if sockets are enabled if (!conf().rtc_relay) { ws.send("rtc relay not configured!"); ws.close(); return; } const cnf = conf().rtc_relay; // Then check remote IP address if (cnf.ip && cnf.ip != req.ip) { ws.send("unkown IP address : " + req.ip) ws.close(); return; } // Finally, check access token if (!req.query.hasOwnProperty("token") || req.query.token !== cnf.token) { ws.send("invalid token!"); ws.close(); return; } // Close previous connection if (this.currWs && this.currWs.readyState == ws.OPEN) { this.currWs.close(); } console.info("Connected to RTC relay."); this.currWs = ws; // Register to events ws.addEventListener("close", () => this.WSClosed()); // Send ice configuration to server this.SendMessage({ title: "config", data: { iceServers: cnf.iceServers }, }) } /** * Method called when a websocket connection is closed */ private static async WSClosed() { // Check if this is caused to a new connection if (this.currWs.readyState != ws.OPEN) this.currWs = null; console.info("Closed a connection to RTC relay"); // TODO : do cleanup } /** * Send a new message to the server * * @param title The title of the message to send * @param content The content of the message */ private static async SendMessage(msg: RTCSocketMessage) { this.currWs.send(JSON.stringify({ title: msg.title, callId: msg.callId, peerId: msg.peerId, data: msg.data })); } }