partey_workadventure/pusher/src/Controller/IoSocketController.ts

544 lines
26 KiB
TypeScript
Raw Normal View History

2021-06-24 10:09:10 +02:00
import { CharacterLayer, ExSocketInterface } from "../Model/Websocket/ExSocketInterface"; //TODO fix import by "_Model/.."
import { GameRoomPolicyTypes, PusherRoom } from "../Model/PusherRoom";
2021-06-24 10:09:10 +02:00
import { PointInterface } from "../Model/Websocket/PointInterface";
import {
SetPlayerDetailsMessage,
SubMessage,
2020-09-24 17:24:37 +02:00
BatchMessage,
2020-09-28 18:52:54 +02:00
ItemEventMessage,
ViewportMessage,
ClientToServerMessage,
2020-09-29 16:01:22 +02:00
SilentMessage,
WebRtcSignalToServerMessage,
2020-10-06 15:37:00 +02:00
PlayGlobalMessage,
ReportPlayerMessage,
QueryJitsiJwtMessage,
SendUserMessage,
ServerToClientMessage,
CompanionMessage,
EmotePromptMessage,
FollowRequestMessage,
FollowConfirmationMessage,
FollowAbortMessage,
VariableMessage,
} from "../Messages/generated/messages_pb";
2021-06-24 10:09:10 +02:00
import { UserMovesMessage } from "../Messages/generated/messages_pb";
import { TemplatedApp } from "uWebSockets.js";
import { parse } from "query-string";
import { AdminSocketTokenData, jwtTokenManager, tokenInvalidException } from "../Services/JWTTokenManager";
import { adminApi, FetchMemberDataByUuidResponse } from "../Services/AdminApi";
2021-06-24 10:09:10 +02:00
import { SocketManager, socketManager } from "../Services/SocketManager";
import { emitInBatch } from "../Services/IoSocketHelpers";
import { ADMIN_API_URL, DISABLE_ANONYMOUS, SOCKET_IDLE_TIMER } from "../Enum/EnvironmentVariable";
2021-06-24 10:09:10 +02:00
import { Zone } from "_Model/Zone";
import { ExAdminSocketInterface } from "_Model/Websocket/ExAdminSocketInterface";
import { CharacterTexture } from "../Messages/JsonMessages/CharacterTexture";
import { isAdminMessageInterface } from "../Model/Websocket/Admin/AdminMessages";
import Axios from "axios";
import { InvalidTokenError } from "../Controller/InvalidTokenError";
2020-05-03 16:28:18 +02:00
export class IoSocketController {
private nextUserId: number = 1;
2020-05-03 16:28:18 +02:00
2020-09-28 18:52:54 +02:00
constructor(private readonly app: TemplatedApp) {
this.ioConnection();
this.adminRoomSocket();
}
adminRoomSocket() {
2021-06-24 10:09:10 +02:00
this.app.ws("/admin/rooms", {
upgrade: (res, req, context) => {
2021-06-24 10:09:10 +02:00
const websocketKey = req.getHeader("sec-websocket-key");
const websocketProtocol = req.getHeader("sec-websocket-protocol");
const websocketExtensions = req.getHeader("sec-websocket-extensions");
res.upgrade({}, websocketKey, websocketProtocol, websocketExtensions, context);
},
open: (ws) => {
console.log("Admin socket connect to client on " + Buffer.from(ws.getRemoteAddressAsText()).toString());
ws.disconnecting = false;
},
message: (ws, arrayBuffer, isBinary): void => {
try {
const message = JSON.parse(new TextDecoder("utf-8").decode(new Uint8Array(arrayBuffer)));
if (!isAdminMessageInterface(message)) {
console.error("Invalid message received.", message);
ws.send(
JSON.stringify({
type: "Error",
data: {
message: "Invalid message received! The connection has been closed.",
},
})
);
ws.close();
return;
}
const token = message.jwt;
let data: AdminSocketTokenData;
try {
data = jwtTokenManager.verifyAdminSocketToken(token);
} catch (e) {
console.error("Admin socket access refused for token: " + token, e);
ws.send(
JSON.stringify({
type: "Error",
data: {
message: "Admin socket access refused! The connection has been closed.",
},
})
);
ws.close();
return;
}
const authorizedRoomIds = data.authorizedRoomIds;
if (message.event === "listen") {
const notAuthorizedRoom = message.roomIds.filter(
(roomId) => !authorizedRoomIds.includes(roomId)
);
if (notAuthorizedRoom.length > 0) {
const errorMessage = `Admin socket refused for client on ${Buffer.from(
ws.getRemoteAddressAsText()
).toString()} listening of : \n${JSON.stringify(notAuthorizedRoom)}`;
console.error();
ws.send(
JSON.stringify({
type: "Error",
data: {
message: errorMessage,
},
})
2021-06-24 10:09:10 +02:00
);
ws.close();
return;
2021-01-17 03:07:46 +01:00
}
for (const roomId of message.roomIds) {
socketManager
.handleAdminRoom(ws as ExAdminSocketInterface, roomId)
.catch((e) => console.error(e));
}
} else if (message.event === "user-message") {
const messageToEmit = message.message;
// Get roomIds of the world where we want broadcast the message
const roomIds = authorizedRoomIds.filter(
(authorizeRoomId) => authorizeRoomId.split("/")[5] === message.world
);
for (const roomId of roomIds) {
if (messageToEmit.type === "banned") {
socketManager
.emitBan(messageToEmit.userUuid, messageToEmit.message, messageToEmit.type, roomId)
.catch((error) => console.error(error));
} else if (messageToEmit.type === "ban") {
socketManager
.emitSendUserMessage(
messageToEmit.userUuid,
messageToEmit.message,
messageToEmit.type,
roomId
)
.catch((error) => console.error(error));
}
2020-10-20 08:20:21 +02:00
}
} else {
const tmp: never = message.event;
}
2021-06-24 10:09:10 +02:00
} catch (err) {
console.error(err);
}
},
close: (ws, code, message) => {
2021-06-24 10:09:10 +02:00
const Client = ws as ExAdminSocketInterface;
try {
Client.disconnecting = true;
socketManager.leaveAdminRoom(Client);
} catch (e) {
console.error('An error occurred on admin "disconnect"');
console.error(e);
}
2021-06-24 10:09:10 +02:00
},
});
}
2020-09-28 18:52:54 +02:00
ioConnection() {
2021-06-24 10:09:10 +02:00
this.app.ws("/room", {
2020-09-28 18:52:54 +02:00
/* Options */
//compression: uWS.SHARED_COMPRESSOR,
idleTimeout: SOCKET_IDLE_TIMER,
2020-09-28 18:52:54 +02:00
maxPayloadLength: 16 * 1024 * 1024,
2020-09-30 12:16:39 +02:00
maxBackpressure: 65536, // Maximum 64kB of data in the buffer.
2020-09-29 16:01:22 +02:00
//idleTimeout: 10,
upgrade: (res, req, context) => {
(async () => {
/* Keep track of abortions */
2021-06-24 10:09:10 +02:00
const upgradeAborted = { aborted: false };
res.onAborted(() => {
/* We can simply signal that we were aborted */
upgradeAborted.aborted = true;
2020-07-27 22:36:07 +02:00
});
const url = req.getUrl();
const query = parse(req.getQuery());
2021-06-24 10:09:10 +02:00
const websocketKey = req.getHeader("sec-websocket-key");
const websocketProtocol = req.getHeader("sec-websocket-protocol");
const websocketExtensions = req.getHeader("sec-websocket-extensions");
const IPAddress = req.getHeader("x-forwarded-for");
2020-10-06 15:37:00 +02:00
const roomId = query.roomId;
try {
2021-06-24 10:09:10 +02:00
if (typeof roomId !== "string") {
throw new Error("Undefined room ID: ");
}
2020-10-06 15:37:00 +02:00
const token = query.token;
const x = Number(query.x);
const y = Number(query.y);
const top = Number(query.top);
const bottom = Number(query.bottom);
const left = Number(query.left);
const right = Number(query.right);
const name = query.name;
2021-04-02 21:21:11 +02:00
2021-06-24 10:09:10 +02:00
let companion: CompanionMessage | undefined = undefined;
2021-04-02 21:21:11 +02:00
2021-06-24 10:09:10 +02:00
if (typeof query.companion === "string") {
2021-04-06 18:54:45 +02:00
companion = new CompanionMessage();
2021-04-02 21:21:11 +02:00
companion.setName(query.companion);
}
2021-06-24 10:09:10 +02:00
if (typeof name !== "string") {
throw new Error("Expecting name");
}
2021-06-24 10:09:10 +02:00
if (name === "") {
throw new Error("No empty name");
}
let characterLayers = query.characterLayers;
if (characterLayers === null) {
2021-06-24 10:09:10 +02:00
throw new Error("Expecting skin");
}
2021-06-24 10:09:10 +02:00
if (typeof characterLayers === "string") {
characterLayers = [characterLayers];
}
2020-10-06 15:37:00 +02:00
const tokenData =
token && typeof token === "string" ? jwtTokenManager.verifyJWTToken(token) : null;
2021-01-16 20:14:21 +01:00
if (DISABLE_ANONYMOUS && !tokenData) {
throw new Error("Expecting token");
}
const userIdentifier = tokenData ? tokenData.identifier : "";
2021-01-16 20:14:21 +01:00
let memberTags: string[] = [];
2021-06-24 10:09:10 +02:00
let memberVisitCardUrl: string | null = null;
let memberMessages: unknown;
let memberUserRoomToken: string | undefined;
2020-10-20 16:39:23 +02:00
let memberTextures: CharacterTexture[] = [];
const room = await socketManager.getOrCreateRoom(roomId);
let userData: FetchMemberDataByUuidResponse = {
email: userIdentifier,
userUuid: userIdentifier,
tags: [],
visitCardUrl: null,
textures: [],
messages: [],
anonymous: true,
userRoomToken: undefined,
};
if (ADMIN_API_URL) {
try {
2021-03-01 22:21:52 +01:00
try {
userData = await adminApi.fetchMemberDataByUuid(userIdentifier, roomId, IPAddress);
2021-06-24 10:09:10 +02:00
} catch (err) {
if (Axios.isAxiosError(err)) {
if (err?.response?.status == 404) {
// If we get an HTTP 404, the token is invalid. Let's perform an anonymous login!
console.warn(
'Cannot find user with email "' +
(userIdentifier || "anonymous") +
'". Performing an anonymous login instead.'
);
} else if (err?.response?.status == 403) {
// If we get an HTTP 403, the world is full. We need to broadcast a special error to the client.
// we finish immediately the upgrade then we will close the socket as soon as it starts opening.
return res.upgrade(
{
rejected: true,
message: err?.response?.data.message,
status: err?.response?.status,
roomId,
},
websocketKey,
websocketProtocol,
websocketExtensions,
context
);
}
2021-06-24 10:09:10 +02:00
} else {
2021-03-01 22:21:52 +01:00
throw err;
}
}
memberMessages = userData.messages;
memberTags = userData.tags;
memberVisitCardUrl = userData.visitCardUrl;
memberTextures = userData.textures;
memberUserRoomToken = userData.userRoomToken;
2021-06-24 10:09:10 +02:00
if (
room.policyType === GameRoomPolicyTypes.USE_TAGS_POLICY &&
(userData.anonymous === true || !room.canAccess(memberTags))
) {
throw new Error("Insufficient privileges to access this room");
}
2021-06-24 10:09:10 +02:00
if (
room.policyType === GameRoomPolicyTypes.MEMBERS_ONLY_POLICY &&
userData.anonymous === true
) {
throw new Error("Use the login URL to connect");
2021-03-01 22:21:52 +01:00
}
} catch (e) {
console.log(
"access not granted for user " +
(userIdentifier || "anonymous") +
" and room " +
roomId
);
console.error(e);
2021-06-24 10:09:10 +02:00
throw new Error("User cannot access this world");
}
2020-10-09 14:53:18 +02:00
}
2020-10-20 16:39:23 +02:00
// Generate characterLayers objects from characterLayers string[]
2021-06-24 10:09:10 +02:00
const characterLayerObjs: CharacterLayer[] =
SocketManager.mergeCharacterLayersAndCustomTextures(characterLayers, memberTextures);
2020-10-20 16:39:23 +02:00
if (upgradeAborted.aborted) {
console.log("Ouch! Client disconnected before we could upgrade it!");
/* You must not upgrade now */
return;
}
/* This immediately calls open handler, you must not use res after this call */
2021-06-24 10:09:10 +02:00
res.upgrade(
{
// Data passed here is accessible on the "websocket" socket object.
2020-10-09 16:18:25 +02:00
url,
2020-10-06 15:37:00 +02:00
token,
userUuid: userData.userUuid,
2021-01-15 03:19:58 +01:00
IPAddress,
roomId,
name,
2021-04-02 21:21:11 +02:00
companion,
2020-10-20 16:39:23 +02:00
characterLayers: characterLayerObjs,
messages: memberMessages,
tags: memberTags,
visitCardUrl: memberVisitCardUrl,
userRoomToken: memberUserRoomToken,
2020-10-20 16:39:23 +02:00
textures: memberTextures,
position: {
x: x,
y: y,
2021-06-24 10:09:10 +02:00
direction: "down",
moving: false,
} as PointInterface,
viewport: {
top,
right,
bottom,
2021-06-24 10:09:10 +02:00
left,
},
},
/* Spell these correctly */
2020-10-09 16:18:25 +02:00
websocketKey,
websocketProtocol,
websocketExtensions,
2021-06-24 10:09:10 +02:00
context
);
2020-09-30 10:17:01 +02:00
} catch (e) {
if (e instanceof Error) {
res.upgrade(
{
rejected: true,
reason: e instanceof InvalidTokenError ? tokenInvalidException : null,
message: e.message,
roomId,
},
websocketKey,
websocketProtocol,
websocketExtensions,
context
);
} else {
res.upgrade(
{
rejected: true,
reason: null,
message: "500 Internal Server Error",
roomId,
},
websocketKey,
websocketProtocol,
websocketExtensions,
context
);
}
}
})();
},
2020-09-28 18:52:54 +02:00
/* Handlers */
open: (ws) => {
2021-06-24 10:09:10 +02:00
if (ws.rejected === true) {
// If there is a room in the error, let's check if we need to clean it.
if (ws.roomId) {
socketManager.deleteRoomIfEmptyFromId(ws.roomId as string);
}
//FIX ME to use status code
if (ws.reason === tokenInvalidException) {
socketManager.emitTokenExpiredMessage(ws);
} else if (ws.message === "World is full") {
socketManager.emitWorldFullMessage(ws);
2021-06-24 10:09:10 +02:00
} else {
socketManager.emitConnexionErrorMessage(ws, ws.message as string);
}
setTimeout(() => ws.close(), 0);
return;
}
// Let's join the room
const client = this.initClient(ws);
socketManager.handleJoinRoom(client);
//get data information and show messages
if (client.messages && Array.isArray(client.messages)) {
client.messages.forEach((c: unknown) => {
2021-06-24 10:09:10 +02:00
const messageToSend = c as { type: string; message: string };
2020-12-11 12:23:50 +01:00
const sendUserMessage = new SendUserMessage();
sendUserMessage.setType(messageToSend.type);
sendUserMessage.setMessage(messageToSend.message);
2020-12-11 12:23:50 +01:00
const serverToClientMessage = new ServerToClientMessage();
serverToClientMessage.setSendusermessage(sendUserMessage);
2020-12-11 12:23:50 +01:00
if (!client.disconnecting) {
client.send(serverToClientMessage.serializeBinary().buffer, true);
}
});
}
2020-09-28 18:52:54 +02:00
},
2020-10-06 15:37:00 +02:00
message: (ws, arrayBuffer, isBinary): void => {
2020-09-28 18:52:54 +02:00
const client = ws as ExSocketInterface;
const message = ClientToServerMessage.deserializeBinary(new Uint8Array(arrayBuffer));
2020-10-06 15:37:00 +02:00
if (message.hasViewportmessage()) {
socketManager.handleViewport(client, (message.getViewportmessage() as ViewportMessage).toObject());
2020-09-28 18:52:54 +02:00
} else if (message.hasUsermovesmessage()) {
socketManager.handleUserMovesMessage(client, message.getUsermovesmessage() as UserMovesMessage);
2020-09-28 18:52:54 +02:00
} else if (message.hasSetplayerdetailsmessage()) {
2021-06-24 10:09:10 +02:00
socketManager.handleSetPlayerDetails(
client,
message.getSetplayerdetailsmessage() as SetPlayerDetailsMessage
);
2020-09-28 18:52:54 +02:00
} else if (message.hasSilentmessage()) {
socketManager.handleSilentMessage(client, message.getSilentmessage() as SilentMessage);
2020-09-28 18:52:54 +02:00
} else if (message.hasItemeventmessage()) {
socketManager.handleItemEvent(client, message.getItemeventmessage() as ItemEventMessage);
2021-07-06 15:30:49 +02:00
} else if (message.hasVariablemessage()) {
socketManager.handleVariableEvent(client, message.getVariablemessage() as VariableMessage);
2020-09-29 16:01:22 +02:00
} else if (message.hasWebrtcsignaltoservermessage()) {
2021-06-24 10:09:10 +02:00
socketManager.emitVideo(
client,
message.getWebrtcsignaltoservermessage() as WebRtcSignalToServerMessage
);
2020-09-29 16:01:22 +02:00
} else if (message.hasWebrtcscreensharingsignaltoservermessage()) {
2021-06-24 10:09:10 +02:00
socketManager.emitScreenSharing(
client,
message.getWebrtcscreensharingsignaltoservermessage() as WebRtcSignalToServerMessage
);
} else if (message.hasPlayglobalmessage()) {
socketManager.emitPlayGlobalMessage(client, message.getPlayglobalmessage() as PlayGlobalMessage);
2021-06-24 10:09:10 +02:00
} else if (message.hasReportplayermessage()) {
socketManager.handleReportMessage(client, message.getReportplayermessage() as ReportPlayerMessage);
2021-06-24 10:09:10 +02:00
} else if (message.hasQueryjitsijwtmessage()) {
socketManager.handleQueryJitsiJwtMessage(
client,
message.getQueryjitsijwtmessage() as QueryJitsiJwtMessage
);
} else if (message.hasEmotepromptmessage()) {
socketManager.handleEmotePromptMessage(
client,
message.getEmotepromptmessage() as EmotePromptMessage
);
} else if (message.hasFollowrequestmessage()) {
socketManager.handleFollowRequest(
2021-12-12 00:24:39 +01:00
client,
message.getFollowrequestmessage() as FollowRequestMessage
2021-12-12 00:24:39 +01:00
);
} else if (message.hasFollowconfirmationmessage()) {
socketManager.handleFollowConfirmation(
client,
message.getFollowconfirmationmessage() as FollowConfirmationMessage
);
} else if (message.hasFollowabortmessage()) {
socketManager.handleFollowAbort(client, message.getFollowabortmessage() as FollowAbortMessage);
}
2020-06-11 23:18:06 +02:00
2021-06-24 10:09:10 +02:00
/* Ok is false if backpressure was built up, wait for drain */
2020-09-28 18:52:54 +02:00
//let ok = ws.send(message, isBinary);
},
drain: (ws) => {
2021-06-24 10:09:10 +02:00
console.log("WebSocket backpressure: " + ws.getBufferedAmount());
2020-09-28 18:52:54 +02:00
},
close: (ws, code, message) => {
2021-06-24 10:09:10 +02:00
const Client = ws as ExSocketInterface;
try {
2020-09-28 18:52:54 +02:00
Client.disconnecting = true;
//leave room
socketManager.leaveRoom(Client);
} catch (e) {
console.error('An error occurred on "disconnect"');
console.error(e);
}
2021-06-24 10:09:10 +02:00
},
});
2020-09-28 18:52:54 +02:00
}
//eslint-disable-next-line @typescript-eslint/no-explicit-any
private initClient(ws: any): ExSocketInterface {
2021-06-24 10:09:10 +02:00
const client: ExSocketInterface = ws;
client.userId = this.nextUserId;
this.nextUserId++;
client.userUuid = ws.userUuid;
2021-01-15 03:19:58 +01:00
client.IPAddress = ws.IPAddress;
client.token = ws.token;
client.batchedMessages = new BatchMessage();
client.batchTimeout = null;
client.emitInBatch = (payload: SubMessage): void => {
emitInBatch(client, payload);
2021-06-24 10:09:10 +02:00
};
client.disconnecting = false;
client.messages = ws.messages;
client.name = ws.name;
client.tags = ws.tags;
client.visitCardUrl = ws.visitCardUrl;
2020-10-20 16:39:23 +02:00
client.textures = ws.textures;
client.characterLayers = ws.characterLayers;
2021-04-02 21:21:11 +02:00
client.companion = ws.companion;
client.roomId = ws.roomId;
client.listenedZones = new Set<Zone>();
return client;
2020-05-03 16:28:18 +02:00
}
2020-04-04 22:35:20 +02:00
}