partey_workadventure/pusher/src/Controller/IoSocketController.ts

442 lines
21 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 } from "../Model/PusherRoom";
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,
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 { 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_TOKEN, ADMIN_API_URL, SOCKET_IDLE_TIMER } from "../Enum/EnvironmentVariable";
import { Zone } from "_Model/Zone";
import { ExAdminSocketInterface } from "_Model/Websocket/ExAdminSocketInterface";
import { v4 } from "uuid";
import { CharacterTexture } from "../Services/AdminApi/CharacterTexture";
2021-11-08 19:05:25 +01:00
import log from "../Services/Logger";
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) => {
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 token = query.token;
if (token !== ADMIN_API_TOKEN) {
2021-11-08 19:05:25 +01:00
log.info("Admin access refused for token: " + token);
2021-06-24 10:09:10 +02:00
res.writeStatus("401 Unauthorized").end("Incorrect token");
return;
}
const roomId = query.roomId;
2021-06-24 10:09:10 +02:00
if (typeof roomId !== "string") {
2021-11-08 19:05:25 +01:00
log.error("Received");
2021-06-24 10:09:10 +02:00
res.writeStatus("400 Bad Request").end("Missing room id");
return;
}
2021-06-24 10:09:10 +02:00
res.upgrade({ roomId }, websocketKey, websocketProtocol, websocketExtensions, context);
},
open: (ws) => {
2021-11-08 19:05:25 +01:00
log.info("Admin socket connect for room: " + ws.roomId);
ws.disconnecting = false;
socketManager.handleAdminRoom(ws as ExAdminSocketInterface, ws.roomId as string);
},
message: (ws, arrayBuffer, isBinary): void => {
try {
2020-12-11 12:23:50 +01:00
const roomId = ws.roomId as string;
//TODO refactor message type and data
2021-06-24 10:09:10 +02:00
const message: { event: string; message: { type: string; message: unknown; userUuid: string } } =
JSON.parse(new TextDecoder("utf-8").decode(new Uint8Array(arrayBuffer)));
2021-06-24 10:09:10 +02:00
if (message.event === "user-message") {
const messageToEmit = message.message as { message: string; type: string; userUuid: string };
if (messageToEmit.type === "banned") {
socketManager.emitBan(
messageToEmit.userUuid,
messageToEmit.message,
messageToEmit.type,
ws.roomId as string
);
2021-01-17 03:07:46 +01:00
}
2021-06-24 10:09:10 +02:00
if (messageToEmit.type === "ban") {
socketManager.emitSendUserMessage(
messageToEmit.userUuid,
messageToEmit.message,
messageToEmit.type,
ws.roomId as string
);
2020-10-20 08:20:21 +02:00
}
}
2021-06-24 10:09:10 +02:00
} catch (err) {
2021-11-08 19:05:25 +01:00
log.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) {
2021-11-08 19:05:25 +01:00
log.error('An error occurred on admin "disconnect"');
log.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;
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;
2020-10-20 16:39:23 +02:00
let memberTextures: CharacterTexture[] = [];
const room = await socketManager.getOrCreateRoom(roomId);
let userData: FetchMemberDataByUuidResponse = {
userUuid: userIdentifier,
tags: [],
visitCardUrl: null,
textures: [],
messages: [],
anonymous: true,
};
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) {
2021-03-01 22:21:52 +01:00
if (err?.response?.status == 404) {
// If we get an HTTP 404, the token is invalid. Let's perform an anonymous login!
2021-11-08 19:05:25 +01:00
log.warn(
'Cannot find user with email "' +
(userIdentifier || "anonymous") +
2021-06-24 10:09:10 +02:00
'". 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.
2021-06-24 10:09:10 +02:00
return res.upgrade(
{
rejected: true,
message: err?.response?.data.message,
status: err?.response?.status,
},
websocketKey,
websocketProtocol,
websocketExtensions,
context
);
} else {
2021-03-01 22:21:52 +01:00
throw err;
}
}
memberMessages = userData.messages;
memberTags = userData.tags;
memberVisitCardUrl = userData.visitCardUrl;
memberTextures = userData.textures;
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) {
2021-11-08 19:05:25 +01:00
log.info(
"access not granted for user " +
(userIdentifier || "anonymous") +
" and room " +
roomId
);
2021-11-08 19:05:25 +01:00
log.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) {
2021-11-08 19:05:25 +01:00
log.info("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,
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) {
res.upgrade(
2021-06-24 10:09:10 +02:00
{
rejected: true,
reason: e.reason || null,
2021-06-24 10:09:10 +02:00
message: e.message ? e.message : "500 Internal Server Error",
},
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) {
//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
);
}
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-11-08 19:05:25 +01:00
log.info("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) {
2021-11-08 19:05:25 +01:00
log.error('An error occurred on "disconnect"');
log.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
}