1
0
mirror of https://gitlab.com/comunic/comunicapiv2 synced 2025-03-13 01:22:38 +00:00
comunicapiv2/src/entities/WebSocketRequestHandler.ts

99 lines
2.4 KiB
TypeScript

/**
* User Web Sockets requests handler implementation
*
* @author Pierre Hubert
*/
import { BaseRequestsHandler } from "./BaseRequestsHandler";
import { ActiveClient, UserWebSocketController } from "../controllers/UserWebSocketController";
import { WsMessage } from "./WsMessage";
export class UserWebSocketRequestsHandler extends BaseRequestsHandler {
private sentResponse = false;
constructor(public wsClient: ActiveClient, private req: WsMessage) {
super();
}
public get isResponseSent() : boolean {
return this.sentResponse;
}
protected get userID(): number {
return this.wsClient.userID;
}
protected getPostParam(name: string) {
return this.req.data[name];
}
public hasPostParameter(name: string): boolean {
return this.req.data.hasOwnProperty(name)
&& this.req.data[name] != null
&& this.req.data[name] != undefined;
}
public error(code: number, message: string): void {
this.sendResponse("error", {
code: code,
message: message
});
throw new Error("User WS error ("+code+"): "+message);
}
public success(message: string = ""): void {
this.sendResponse("success", message);
}
public send(data: any): void {
this.sendResponse("success", data);
}
public sendResponse(title: string, data: any) {
if(this.sentResponse)
throw new Error("Trying to send a response to a request to which a response has already been sent!")
// Send the response
UserWebSocketController.SendToClient(this.wsClient, new WsMessage({
title: title,
data: data,
id: this.req.id
}))
this.sentResponse = true;
}
/**
* Get the ID of a call included in WebSocket request
*
* @param name The name of the parameter
*/
public postCallId(name: string) : number {
const convID = this.postInt(name);
// Check if the user is a member of this call
if(!this.wsClient.activeCalls.has(convID))
this.error(401, "You do not belong to this call!")
return convID;
}
/**
* Get the ID of a peer of a call included in the WebSocket request
*
* @param callID Target call ID
* @param name The name of the POST field
*/
public postCallPeerID(callID: number, name: string) : number{
const peerID = this.postInt(name);
if(peerID != this.getUserId() && UserWebSocketController.active_clients.find(
(e) => e.userID == peerID && e.activeCalls.has(callID)) === undefined)
this.error(401, "This peer is not a member of the call!");
return peerID;
}
}