1
0
mirror of https://gitlab.com/comunic/comunicapiv2 synced 2024-11-22 13:29:22 +00:00
comunicapiv2/src/controllers/RTCRelayController.ts

148 lines
3.0 KiB
TypeScript

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());
ws.addEventListener("error", (e) => console.error("RTC WS error !", e))
ws.addEventListener("message", (msg) => this.OnMessage(msg.data))
// Send ice configuration to server
this.SendMessage({
title: "config",
data: {
allowVideo: cnf.allowVideo,
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) {
if(this.currWs)
this.currWs.send(JSON.stringify({
title: msg.title,
callHash: msg.callHash,
peerId: msg.peerId,
data: msg.data
}));
}
/**
* Handles new messages data
*
* @param data Message data
*/
private static async OnMessage(data: any) {
try {
const message: RTCSocketMessage = JSON.parse(data);
switch(message.title){
case "signal":
await EventsHelper.Emit("rtc_relay_signal", {
peerID: message.peerId,
callHash: message.callHash,
data: message.data
})
break;
default:
console.error("Unkown message type: " + message.title)
break;
}
} catch(e) {
console.error("RTC WS message error", e)
}
}
}