import * as ws from 'ws'; import { Request } from 'express'; import { conf } from '../helpers/ConfigHelper'; import { EventsHelper } from '../helpers/EventsHelper'; /** * RTC WebSocket relay controller * * @author Pierre HUBERT */ export interface RTCSocketMessage { title: string, callHash ?: 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 }, }) } /** * Check out wheter a relay is currently connected to the API */ public static get IsConnected() : boolean { return this.currWs && this.currWs.readyState == ws.OPEN; } /** * 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"); // Propagate information await EventsHelper.Emit("rtc_relay_ws_closed", {}); } /** * Send a new message to the server * * @param title The title of the message to send * @param content The content of the message */ public static async SendMessage(msg: RTCSocketMessage) { this.currWs.send(JSON.stringify({ title: msg.title, callHash: msg.callHash, peerId: msg.peerId, data: msg.data })); } }