Browse Source

Adding a Pusher container as a middleware/dispatcher between front and back

develop
David Négrier 6 months ago
parent
commit
4c1e566a6c
  1. 3
      back/package.json
  2. 148
      back/position-test.js
  3. 12
      back/server.ts
  4. 62
      back/src/Model/GameRoom.ts
  5. 60
      back/src/Model/PositionNotifier.ts
  6. 38
      back/src/Model/User.ts
  7. 12
      back/src/Model/Websocket/ProtobufUtils.ts
  8. 41
      back/src/Model/Zone.ts
  9. 114
      back/src/RoomManager.ts
  10. 12
      back/src/Services/IoSocketHelpers.ts
  11. 565
      back/src/Services/SocketManager.ts
  12. 458
      back/yarn.lock
  13. 30
      docker-compose.yaml
  14. 27
      docs/diagrams.md
  15. 3
      front/src/Connexion/ConnectionManager.ts
  16. 5
      front/src/Connexion/ConnexionModels.ts
  17. 19
      front/src/Connexion/RoomConnection.ts
  18. 2
      front/src/Enum/EnvironmentVariable.ts
  19. 26
      front/src/Phaser/Game/GameScene.ts
  20. 66
      messages/package.json
  21. 90
      messages/protos/messages.proto
  22. 4168
      messages/yarn.lock
  23. 5
      pusher/.dockerignore
  24. 30
      pusher/.eslintrc.json
  25. 4
      pusher/.gitignore
  26. 15
      pusher/Dockerfile
  27. 691
      pusher/LICENSE.txt
  28. 5
      pusher/README.md
  29. 5
      pusher/jasmine.json
  30. 75
      pusher/package.json
  31. 3
      pusher/server.ts
  32. 32
      pusher/src/App.ts
  33. 135
      pusher/src/Controller/AuthenticateController.ts
  34. 11
      pusher/src/Controller/BaseController.ts
  35. 45
      pusher/src/Controller/DebugController.ts
  36. 161
      pusher/src/Controller/FileController.ts
  37. 12
      pusher/src/Controller/IoSocketController.ts
  38. 73
      pusher/src/Controller/MapController.ts
  39. 20
      pusher/src/Controller/PrometheusController.ts
  40. 30
      pusher/src/Enum/EnvironmentVariable.ts
  41. 1
      pusher/src/Messages/.gitignore
  42. 7
      pusher/src/Model/Distance.ts
  43. 138
      pusher/src/Model/Group.ts
  44. 8
      pusher/src/Model/Movable.ts
  45. 120
      pusher/src/Model/PositionDispatcher.ts
  46. 4
      pusher/src/Model/PositionInterface.ts
  47. 68
      pusher/src/Model/PusherRoom.ts
  48. 30
      pusher/src/Model/RoomIdentifier.ts
  49. 35
      pusher/src/Model/User.ts
  50. 42
      pusher/src/Model/Websocket/ExSocketInterface.ts
  51. 6
      pusher/src/Model/Websocket/GroupUpdateInterface.ts
  52. 3
      pusher/src/Model/Websocket/Identificable.ts
  53. 10
      pusher/src/Model/Websocket/ItemEventMessage.ts
  54. 11
      pusher/src/Model/Websocket/JoinRoomMessage.ts
  55. 6
      pusher/src/Model/Websocket/MessageUserJoined.ts
  56. 11
      pusher/src/Model/Websocket/MessageUserPosition.ts
  57. 17
      pusher/src/Model/Websocket/PointInterface.ts
  58. 108
      pusher/src/Model/Websocket/ProtobufUtils.ts
  59. 8
      pusher/src/Model/Websocket/SetPlayerDetailsMessage.ts
  60. 5
      pusher/src/Model/Websocket/UserInGroupInterface.ts
  61. 10
      pusher/src/Model/Websocket/ViewportMessage.ts
  62. 18
      pusher/src/Model/Websocket/WebRtcSignalMessage.ts
  63. 333
      pusher/src/Model/Zone.ts
  64. 13
      pusher/src/Server/server/app.ts
  65. 116
      pusher/src/Server/server/baseapp.ts
  66. 100
      pusher/src/Server/server/formdata.ts
  67. 13
      pusher/src/Server/server/sslapp.ts
  68. 11
      pusher/src/Server/server/types.ts
  69. 37
      pusher/src/Server/server/utils.ts
  70. 19
      pusher/src/Server/sifrr.server.ts
  71. 115
      pusher/src/Services/AdminApi.ts
  72. 22
      pusher/src/Services/ApiClientRepository.ts
  73. 3
      pusher/src/Services/ArrayHelper.ts
  74. 32
      pusher/src/Services/ClientEventsEmitter.ts
  75. 55
      pusher/src/Services/CpuTracker.ts
  76. 54
      pusher/src/Services/GaugeManager.ts
  77. 35
      pusher/src/Services/IoSocketHelpers.ts
  78. 76
      pusher/src/Services/JWTTokenManager.ts
  79. 744
      pusher/src/Services/SocketManager.ts
  80. 14
      pusher/tests/ArrayHelperTest.ts
  81. 97
      pusher/tests/GameRoomTest.ts
  82. 176
      pusher/tests/PositionNotifierTest.ts
  83. 19
      pusher/tests/RoomIdentifierTest.ts
  84. 72
      pusher/tsconfig.json
  85. 3060
      pusher/yarn.lock
  86. 2
      website/dist/create-map.html

3
back/package.json

@ -40,8 +40,10 @@
"body-parser": "^1.19.0",
"busboy": "^0.3.1",
"circular-json": "^0.5.9",
"debug": "^4.3.1",
"generic-type-guard": "^3.2.0",
"google-protobuf": "^3.13.0",
"grpc": "^1.24.4",
"http-status-codes": "^1.4.0",
"iterall": "^1.3.0",
"jsonwebtoken": "^8.5.1",
@ -58,6 +60,7 @@
"devDependencies": {
"@types/busboy": "^0.2.3",
"@types/circular-json": "^0.4.0",
"@types/debug": "^4.1.5",
"@types/google-protobuf": "^3.7.3",
"@types/http-status-codes": "^1.2.0",
"@types/jasmine": "^3.5.10",

148
back/position-test.js

@ -1,148 +0,0 @@
// Constants
let MIN_DISTANCE = 12;
let MAX_PER_GROUP = 3;
let NB_USERS = 10;
// Utils
let rand = function(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
};
let compareDistances = function(distA, distB) {
if (distA.distance < distB.distance) {
return -1;
}
if (distA.distance > distB.distance) {
return 1;
}
return 0;
};
let computeDistance = function (user1, user2) {
return Math.sqrt(Math.pow(user2.X - user1.X, 2) + Math.pow(user2.Y - user1.Y, 2));
};
// Test Data
let users = [];
for(let i = 1; i <= NB_USERS; i++) {
let user = {};
user.id = rand(0,99999);
user.X = rand(0, 40);
user.Y = rand(0, 40);
users.push(user);
}
// Compute distance between each user
let getDistanceOfEachUser = function(users) {
let i = 0;
let distances = [];
users.forEach(function(user1, key1) {
users.forEach(function(user2, key2) {
if(key1 < key2) {
let distanceObj = {};
distanceObj.distance = computeDistance(user1, user2);
distanceObj.first = user1;
distanceObj.second = user2;
distances[i] = distanceObj;
i++;
}
});
});
return distances;
};
// Organise groups
let createGroups = function(distances) {
let i = 0;
let groups = [];
let alreadyInAGroup = [];
for(let j = 0; j < distances.length; j++) {
let dist = distances[j];
if(dist.distance <= MIN_DISTANCE) {
if(typeof groups[i] === 'undefined') {
groups[i] = [];
}
if(groups[i].indexOf(dist.first) === -1 && typeof alreadyInAGroup[dist.first.id] === 'undefined') {
if(groups[i].length > 1) {
// if group is not empty we check current user can be added in the group according to its distance to the others already in it
for(let l = 0; l < groups[i].length; l++) {
let userTotest = groups[i][l];
if(computeDistance(dist.first, userTotest) <= MIN_DISTANCE) {
groups[i].push(dist.first);
alreadyInAGroup[dist.first.id] = true;
break;
}
}
} else {
groups[i].push(dist.first);
alreadyInAGroup[dist.first.id] = true;
}
}
if(groups[i].length === MAX_PER_GROUP) {
i++; // on créé un nouveau groupe
if(i > (NB_USERS / MAX_PER_GROUP)) {
console.log('There is no room left for user ID : ' + dist.second.id + ' !');
break;
}
continue;
}
if(groups[i].indexOf(dist.second) === -1 && typeof alreadyInAGroup[dist.second.id] === 'undefined') {
if(groups[i].length > 1) {
// if group is not empty we check current user can be added in the group according to its distance to the others already in it
for(let l = 0; l < groups[i].length; l++) {
let userTotest = groups[i][l];
if(computeDistance(dist.second, userTotest) <= MIN_DISTANCE) {
groups[i].push(dist.second);
alreadyInAGroup[dist.second.id] = true;
break;
}
}
} else {
groups[i].push(dist.second);
alreadyInAGroup[dist.second.id] = true;
}
}
}
}
return groups;
};
let distances = getDistanceOfEachUser(users);
// ordonner par distance pour prioriser l'association en groupe des utilisateurs les plus proches
distances.sort(compareDistances);
let groups = createGroups(distances);
// Compute distance between each user of a already existing group
let checkGroupDistance = function(groups) {
for(let i = 0; i < groups.length; i++) {
let group = groups[i];
group.forEach(function(user1, key1) {
group.forEach(function(user2, key2) {
if(key1 < key2) {
let distance = computeDistance(user1, user2);
if(distance > MIN_DISTANCE) {
// TODO : message a user1 et user2
}
}
});
});
}
};
console.log(users);
console.log(distances);
console.log(groups);

12
back/server.ts

@ -1,3 +1,13 @@
// lib/server.ts
import App from "./src/App";
App.listen(8080, () => console.log(`WorkAdventure starting on port 8080!`))
import grpc from "grpc";
import {roomManager} from "./src/RoomManager";
import {IRoomManagerServer, RoomManagerService} from "./src/Messages/generated/messages_grpc_pb";
//App.listen(8080, () => console.log(`WorkAdventure starting on port 8080!`))
const server = new grpc.Server();
server.addService<IRoomManagerServer>(RoomManagerService, roomManager);
server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
server.start();

62
back/src/Model/GameRoom.ts

@ -1,6 +1,6 @@
import {PointInterface} from "./Websocket/PointInterface";
import {Group} from "./Group";
import {User} from "./User";
import {User, UserSocket} from "./User";
import {ExSocketInterface} from "_Model/Websocket/ExSocketInterface";
import {PositionInterface} from "_Model/PositionInterface";
import {Identificable} from "_Model/Websocket/Identificable";
@ -11,6 +11,9 @@ import {Movable} from "_Model/Movable";
import {extractDataFromPrivateRoomId, extractRoomSlugPublicRoomId, isRoomAnonymous} from "./RoomIdentifier";
import {arrayIntersect} from "../Services/ArrayHelper";
import {MAX_USERS_PER_ROOM} from "../Enum/EnvironmentVariable";
import {JoinRoomMessage} from "../Messages/generated/messages_pb";
import {ProtobufUtils} from "../Model/Websocket/ProtobufUtils";
import { ZoneSocket } from "src/RoomManager";
export type ConnectCallback = (user: User, group: Group) => void;
export type DisconnectCallback = (user: User, group: Group) => void;
@ -42,6 +45,7 @@ export class GameRoom {
public readonly roomSlug: string;
public readonly worldSlug: string = '';
public readonly organizationSlug: string = '';
private nextUserId: number = 1;
constructor(roomId: string,
connectCallback: ConnectCallback,
@ -85,26 +89,34 @@ export class GameRoom {
return this.users;
}
public join(socket : ExSocketInterface, userPosition: PointInterface): void {
const user = new User(socket.userId, socket.userUuid, userPosition, false, this.positionNotifier, socket);
this.users.set(socket.userId, user);
public join(socket : UserSocket, joinRoomMessage: JoinRoomMessage): User {
const positionMessage = joinRoomMessage.getPositionmessage();
if (positionMessage === undefined) {
throw new Error('Missing position message');
}
const position = ProtobufUtils.toPointInterface(positionMessage);
const user = new User(this.nextUserId, joinRoomMessage.getUseruuid(), position, false, this.positionNotifier, socket, joinRoomMessage.getTagList(), joinRoomMessage.getName(), ProtobufUtils.toCharacterLayerObjects(joinRoomMessage.getCharacterlayerList()));
this.nextUserId++;
this.users.set(user.id, user);
// Let's call update position to trigger the join / leave room
//this.updatePosition(socket, userPosition);
this.updateUserGroup(user);
return user;
}
public leave(user : Identificable){
const userObj = this.users.get(user.userId);
public leave(user : User){
const userObj = this.users.get(user.id);
if (userObj === undefined) {
console.warn('User ', user.userId, 'does not belong to world! It should!');
console.warn('User ', user.id, 'does not belong to this game room! It should!');
}
if (userObj !== undefined && typeof userObj.group !== 'undefined') {
this.leaveGroup(userObj);
}
this.users.delete(user.userId);
this.users.delete(user.id);
if (userObj !== undefined) {
this.positionNotifier.removeViewport(userObj);
this.positionNotifier.leave(userObj);
}
}
@ -117,12 +129,7 @@ export class GameRoom {
return this.users.size === 0;
}
public updatePosition(socket : Identificable, userPosition: PointInterface): void {
const user = this.users.get(socket.userId);
if(typeof user === 'undefined') {
return;
}
public updatePosition(user : User, userPosition: PointInterface): void {
user.setPosition(userPosition);
this.updateUserGroup(user);
@ -170,12 +177,7 @@ export class GameRoom {
}
}
setSilent(socket: Identificable, silent: boolean) {
const user = this.users.get(socket.userId);
if(typeof user === 'undefined') {
console.warn('In setSilent, could not find user with ID "'+socket.userId+'" in world.');
return;
}
setSilent(user: User, silent: boolean) {
if (user.silent === silent) {
return;
}
@ -186,7 +188,7 @@ export class GameRoom {
}
if (!silent) {
// If we are back to life, let's trigger a position update to see if we can join some group.
this.updatePosition(socket, user.getPosition());
this.updatePosition(user, user.getPosition());
}
}
@ -281,17 +283,15 @@ export class GameRoom {
return this.itemsState;
}
public canAccess(userTags: string[]): boolean {
return arrayIntersect(userTags, this.tags);
}
setViewport(socket : Identificable, viewport: ViewportInterface): Movable[] {
const user = this.users.get(socket.userId);
if(typeof user === 'undefined') {
console.warn('In setViewport, could not find user with ID "'+socket.userId+'" in world.');
return [];
}
return this.positionNotifier.setViewport(user, viewport);
public addZoneListener(call: ZoneSocket, x: number, y: number): Set<Movable> {
return this.positionNotifier.addZoneListener(call, x, y);
}
canAccess(userTags: string[]): boolean {
return arrayIntersect(userTags, this.tags);
public removeZoneListener(call: ZoneSocket, x: number, y: number): void {
return this.positionNotifier.removeZoneListener(call, x, y);
}
}

60
back/src/Model/PositionNotifier.ts

@ -9,11 +9,9 @@
* number of players around the current player.
*/
import {EntersCallback, LeavesCallback, MovesCallback, Zone} from "./Zone";
import {PointInterface} from "_Model/Websocket/PointInterface";
import {User} from "_Model/User";
import {ViewportInterface} from "_Model/Websocket/ViewportMessage";
import {Movable} from "_Model/Movable";
import {PositionInterface} from "_Model/PositionInterface";
import {ZoneSocket} from "../RoomManager";
interface ZoneDescriptor {
i: number;
@ -36,44 +34,6 @@ export class PositionNotifier {
}
}
/**
* Sets the viewport coordinates.
* Returns the list of new users to add
*/
public setViewport(user: User, viewport: ViewportInterface): Movable[] {
if (viewport.left > viewport.right || viewport.top > viewport.bottom) {
console.warn('Invalid viewport received: ', viewport);
return [];
}
const oldZones = user.listenedZones;
const newZones = new Set<Zone>();
const topLeftDesc = this.getZoneDescriptorFromCoordinates(viewport.left, viewport.top);
const bottomRightDesc = this.getZoneDescriptorFromCoordinates(viewport.right, viewport.bottom);
for (let j = topLeftDesc.j; j <= bottomRightDesc.j; j++) {
for (let i = topLeftDesc.i; i <= bottomRightDesc.i; i++) {
newZones.add(this.getZone(i, j));
}
}
const addedZones = [...newZones].filter(x => !oldZones.has(x));
const removedZones = [...oldZones].filter(x => !newZones.has(x));
let things: Movable[] = [];
for (const zone of addedZones) {
zone.startListening(user);
things = things.concat(Array.from(zone.getThings()))
}
for (const zone of removedZones) {
zone.stopListening(user);
}
return things;
}
public enter(thing: Movable): void {
const position = thing.getPosition();
const zoneDesc = this.getZoneDescriptorFromCoordinates(position.x, position.y);
@ -108,13 +68,6 @@ export class PositionNotifier {
oldZone.leave(thing, null);
}
public removeViewport(user: User): void {
// Also, let's stop listening on viewports
for (const zone of user.listenedZones) {
zone.stopListening(user);
}
}
private getZone(i: number, j: number): Zone {
let zoneRow = this.zones[j];
if (zoneRow === undefined) {
@ -129,4 +82,15 @@ export class PositionNotifier {
}
return zone;
}
public addZoneListener(call: ZoneSocket, x: number, y: number): Set<Movable> {
const zone = this.getZone(x, y);
zone.addListener(call);
return zone.getThings();
}
public removeZoneListener(call: ZoneSocket, x: number, y: number): void {
const zone = this.getZone(x, y);
zone.removeListener(call);
}
}

38
back/src/Model/User.ts

@ -2,9 +2,13 @@ import { Group } from "./Group";
import { PointInterface } from "./Websocket/PointInterface";
import {Zone} from "_Model/Zone";
import {Movable} from "_Model/Movable";
import {PositionInterface} from "_Model/PositionInterface";
import {PositionNotifier} from "_Model/PositionNotifier";
import {ExSocketInterface} from "_Model/Websocket/ExSocketInterface";
import {ServerDuplexStream, ServerWritableStream} from "grpc";
import {BatchMessage, PusherToBackMessage, ServerToClientMessage, SubMessage} from "../Messages/generated/messages_pb";
import {ProtobufUtils} from "_Model/Websocket/ProtobufUtils";
import {CharacterLayer, ExSocketInterface} from "_Model/Websocket/ExSocketInterface";
export type UserSocket = ServerDuplexStream<PusherToBackMessage, ServerToClientMessage>;
export class User implements Movable {
public listenedZones: Set<Zone>;
@ -12,11 +16,14 @@ export class User implements Movable {
public constructor(
public id: number,
public uuid: string,
public readonly uuid: string,
private position: PointInterface,
public silent: boolean,
private positionNotifier: PositionNotifier,
public readonly socket: ExSocketInterface
public readonly socket: UserSocket,
public readonly tags: string[],
public readonly name: string,
public readonly characterLayers: CharacterLayer[]
) {
this.listenedZones = new Set<Zone>();
@ -32,4 +39,27 @@ export class User implements Movable {
this.position = position;
this.positionNotifier.updatePosition(this, position, oldPosition);
}
private batchedMessages: BatchMessage = new BatchMessage();
private batchTimeout: NodeJS.Timeout|null = null;
public emitInBatch(payload: SubMessage): void {
this.batchedMessages.addPayload(payload);
if (this.batchTimeout === null) {
this.batchTimeout = setTimeout(() => {
/*if (socket.disconnecting) {
return;
}*/
const serverToClientMessage = new ServerToClientMessage();
serverToClientMessage.setBatchmessage(this.batchedMessages);
this.socket.write(serverToClientMessage);
this.batchedMessages = new BatchMessage();
this.batchTimeout = null;
}, 100);
}
}
}

12
back/src/Model/Websocket/ProtobufUtils.ts

@ -13,7 +13,7 @@ import {PositionInterface} from "_Model/PositionInterface";
export class ProtobufUtils {
public static toPositionMessage(point: PointInterface): PositionMessage {
let direction: PositionMessage.DirectionMap[keyof PositionMessage.DirectionMap];
let direction: Direction;
switch (point.direction) {
case 'up':
direction = Direction.UP;
@ -105,4 +105,14 @@ export class ProtobufUtils {
return message;
});
}
public static toCharacterLayerObjects(characterLayers: CharacterLayerMessage[]): CharacterLayer[] {
return characterLayers.map(function(characterLayer): CharacterLayer {
const url = characterLayer.getUrl();
return {
name: characterLayer.getName(),
url: url ? url : undefined,
};
});
}
}

41
back/src/Model/Zone.ts

@ -2,20 +2,21 @@ import {User} from "./User";
import {PositionInterface} from "_Model/PositionInterface";
import {Movable} from "./Movable";
import {Group} from "./Group";
import {ZoneSocket} from "../RoomManager";
export type EntersCallback = (thing: Movable, listener: User) => void;
export type MovesCallback = (thing: Movable, position: PositionInterface, listener: User) => void;
export type LeavesCallback = (thing: Movable, listener: User) => void;
export type EntersCallback = (thing: Movable, fromZone: Zone|null, listener: ZoneSocket) => void;
export type MovesCallback = (thing: Movable, position: PositionInterface, listener: ZoneSocket) => void;
export type LeavesCallback = (thing: Movable, newZone: Zone|null, listener: ZoneSocket) => void;
export class Zone {
private things: Set<Movable> = new Set<Movable>();
private listeners: Set<User> = new Set<User>();
private listeners: Set<ZoneSocket> = new Set<ZoneSocket>();
/**
* @param x For debugging purpose only
* @param y For debugging purpose only
*/
constructor(private onEnters: EntersCallback, private onMoves: MovesCallback, private onLeaves: LeavesCallback, private x: number, private y: number) {
constructor(private onEnters: EntersCallback, private onMoves: MovesCallback, private onLeaves: LeavesCallback, public readonly x: number, public readonly y: number) {
}
/**
@ -40,9 +41,9 @@ export class Zone {
*/
private notifyLeft(thing: Movable, newZone: Zone|null) {
for (const listener of this.listeners) {
if (listener !== thing && (newZone === null || !listener.listenedZones.has(newZone))) {
this.onLeaves(thing, listener);
}
//if (listener !== thing && (newZone === null || !listener.listenedZones.has(newZone))) {
this.onLeaves(thing, newZone, listener);
//}
}
}
@ -56,17 +57,20 @@ export class Zone {
*/
private notifyEnter(thing: Movable, oldZone: Zone|null, position: PositionInterface) {
for (const listener of this.listeners) {
if (listener === thing) {
/*if (listener === thing) {
continue;
}
if (oldZone === null || !listener.listenedZones.has(oldZone)) {
this.onEnters(thing, listener);
} else {
this.onMoves(thing, position, listener);
}
}*/
this.onEnters(thing, oldZone, listener);
}
}
public move(thing: Movable, position: PositionInterface) {
if (!this.things.has(thing)) {
this.things.add(thing);
@ -75,13 +79,13 @@ export class Zone {
}
for (const listener of this.listeners) {
if (listener !== thing) {
//if (listener !== thing) {
this.onMoves(thing,position, listener);
}
//}
}
}
public startListening(listener: User): void {
/*public startListening(listener: User): void {
for (const thing of this.things) {
if (thing !== listener) {
this.onEnters(thing, listener);
@ -101,9 +105,18 @@ export class Zone {
this.listeners.delete(listener);
listener.listenedZones.delete(this);
}
}*/
public getThings(): Set<Movable> {
return this.things;
}
public addListener(socket: ZoneSocket): void {
this.listeners.add(socket);
// TODO: here, we should trigger in some way the sending of current items
}
public removeListener(socket: ZoneSocket): void {
this.listeners.delete(socket);
}
}

114
back/src/RoomManager.ts

@ -0,0 +1,114 @@
import {IRoomManagerServer} from "./Messages/generated/messages_grpc_pb";
import {
ClientToServerMessage, ItemEventMessage,
JoinRoomMessage, PlayGlobalMessage, PusherToBackMessage, QueryJitsiJwtMessage, ReportPlayerMessage,
RoomJoinedMessage,
ServerToClientMessage, SilentMessage, UserMovesMessage, ViewportMessage, WebRtcSignalToServerMessage, ZoneMessage
} from "./Messages/generated/messages_pb";
import grpc, {ServerWritableStream} from "grpc";
import {Empty} from "google-protobuf/google/protobuf/empty_pb";
import {socketManager} from "./Services/SocketManager";
import {emitError} from "./Services/IoSocketHelpers";
import {User, UserSocket} from "./Model/User";
import {GameRoom} from "./Model/GameRoom";
import Debug from "debug";
const debug = Debug('roommanager');
export type ZoneSocket = ServerWritableStream<ZoneMessage, ServerToClientMessage>;
const roomManager: IRoomManagerServer = {
joinRoom: (call: UserSocket): void => {
console.log('joinRoom called');
let room: GameRoom|null = null;
let user: User|null = null;
call.on('data', (message: PusherToBackMessage) => {
try {
if (room === null || user === null) {
if (message.hasJoinroommessage()) {
socketManager.handleJoinRoom(call, message.getJoinroommessage() as JoinRoomMessage).then(({room: gameRoom, user: myUser}) => {
room = gameRoom;
user = myUser;
});
} else {
throw new Error('The first message sent MUST be of type JoinRoomMessage');
}
} else {
if (message.hasJoinroommessage()) {
throw new Error('Cannot call JoinRoomMessage twice!');
/*} else if (message.hasViewportmessage()) {
socketManager.handleViewport(client, message.getViewportmessage() as ViewportMessage);*/
} else if (message.hasUsermovesmessage()) {
socketManager.handleUserMovesMessage(room, user, message.getUsermovesmessage() as UserMovesMessage);
/*} else if (message.hasSetplayerdetailsmessage()) {
socketManager.handleSetPlayerDetails(client, message.getSetplayerdetailsmessage() as SetPlayerDetailsMessage);*/
} else if (message.hasSilentmessage()) {
socketManager.handleSilentMessage(room, user, message.getSilentmessage() as SilentMessage);
} else if (message.hasItemeventmessage()) {
socketManager.handleItemEvent(room, user, message.getItemeventmessage() as ItemEventMessage);
} else if (message.hasWebrtcsignaltoservermessage()) {
socketManager.emitVideo(room, user, message.getWebrtcsignaltoservermessage() as WebRtcSignalToServerMessage);
} else if (message.hasWebrtcscreensharingsignaltoservermessage()) {
socketManager.emitScreenSharing(room, user, message.getWebrtcscreensharingsignaltoservermessage() as WebRtcSignalToServerMessage);
} else if (message.hasPlayglobalmessage()) {
socketManager.emitPlayGlobalMessage(room, message.getPlayglobalmessage() as PlayGlobalMessage);
/*} else if (message.hasReportplayermessage()){
socketManager.handleReportMessage(client, message.getReportplayermessage() as ReportPlayerMessage);*/
} else if (message.hasQueryjitsijwtmessage()){
socketManager.handleQueryJitsiJwtMessage(user, message.getQueryjitsijwtmessage() as QueryJitsiJwtMessage);
} else {
throw new Error('Unhandled message type');
}
}
} catch (e) {
emitError(call, e);
call.end();
}
});
call.on('end', () => {
debug('joinRoom ended');
if (user !== null && room !== null) {
socketManager.leaveRoom(room, user);
}
call.end();
room = null;
user = null;
});
call.on('error', (err: Error) => {
console.error('An error occurred in joinRoom stream:', err);
});
},
listenZone(call: ZoneSocket): void {
debug('listenZone called');
const zoneMessage = call.request;
socketManager.addZoneListener(call, zoneMessage.getRoomid(), zoneMessage.getX(), zoneMessage.getY());
call.on('cancelled', () => {
debug('listenZone cancelled');
socketManager.removeZoneListener(call, zoneMessage.getRoomid(), zoneMessage.getX(), zoneMessage.getY());
call.end();
})
/*call.on('finish', () => {
debug('listenZone finish');
})*/
call.on('close', () => {
debug('listenZone connection closed');
socketManager.removeZoneListener(call, zoneMessage.getRoomid(), zoneMessage.getX(), zoneMessage.getY());
}).on('error', (e) => {
console.error('An error occurred in listenZone stream:', e);
socketManager.removeZoneListener(call, zoneMessage.getRoomid(), zoneMessage.getX(), zoneMessage.getY());
call.end();
});
},
};
export {roomManager};

12
back/src/Services/IoSocketHelpers.ts

@ -1,6 +1,10 @@
import {ExSocketInterface} from "_Model/Websocket/ExSocketInterface";
import {BatchMessage, ErrorMessage, ServerToClientMessage, SubMessage} from "../Messages/generated/messages_pb";
import {UserSocket} from "_Model/User";
/**
* @deprecated use User.emitInBatch instead
*/
export function emitInBatch(socket: ExSocketInterface, payload: SubMessage): void {
socket.batchedMessages.addPayload(payload);
@ -20,16 +24,16 @@ export function emitInBatch(socket: ExSocketInterface, payload: SubMessage): voi
}
}
export function emitError(Client: ExSocketInterface, message: string): void {
export function emitError(Client: UserSocket, message: string): void {
const errorMessage = new ErrorMessage();
errorMessage.setMessage(message);
const serverToClientMessage = new ServerToClientMessage();
serverToClientMessage.setErrormessage(errorMessage);
if (!Client.disconnecting) {
Client.send(serverToClientMessage.serializeBinary().buffer, true);
}
//if (!Client.disconnecting) {
Client.write(serverToClientMessage);
//}
console.warn(message);
}

565
back/src/Services/SocketManager.ts

@ -14,33 +14,47 @@ import {
SilentMessage,
SubMessage,
ReportPlayerMessage,
UserJoinedMessage, UserLeftMessage,
UserJoinedMessage,
UserLeftMessage,
UserMovedMessage,
UserMovesMessage,
ViewportMessage, WebRtcDisconnectMessage,
ViewportMessage,
WebRtcDisconnectMessage,
WebRtcSignalToClientMessage,
WebRtcSignalToServerMessage,
WebRtcStartMessage,
QueryJitsiJwtMessage,
SendJitsiJwtMessage,
SendUserMessage
SendUserMessage,
JoinRoomMessage,
Zone as ProtoZone,
BatchMessage,
BatchToPusherMessage,
SubToPusherMessage,
UserJoinedZoneMessage, GroupUpdateZoneMessage, GroupLeftZoneMessage, UserLeftZoneMessage
} from "../Messages/generated/messages_pb";
import {PointInterface} from "../Model/Websocket/PointInterface";
import {User} from "../Model/User";
import {User, UserSocket} from "../Model/User";
import {ProtobufUtils} from "../Model/Websocket/ProtobufUtils";
import {Group} from "../Model/Group";
import {cpuTracker} from "./CpuTracker";
import {isSetPlayerDetailsMessage} from "../Model/Websocket/SetPlayerDetailsMessage";
import {GROUP_RADIUS, JITSI_ISS, MINIMUM_DISTANCE, SECRET_JITSI_KEY} from "../Enum/EnvironmentVariable";
import {ADMIN_API_URL, GROUP_RADIUS, JITSI_ISS, MINIMUM_DISTANCE, SECRET_JITSI_KEY} from "../Enum/EnvironmentVariable";
import {Movable} from "../Model/Movable";
import {PositionInterface} from "../Model/PositionInterface";
import {adminApi, CharacterTexture} from "./AdminApi";
import {adminApi, CharacterTexture, FetchMemberDataByUuidResponse} from "./AdminApi";
import Direction = PositionMessage.Direction;
import {emitError, emitInBatch} from "./IoSocketHelpers";
import Jwt from "jsonwebtoken";
import {JITSI_URL} from "../Enum/EnvironmentVariable";
import {clientEventsEmitter} from "./ClientEventsEmitter";
import {gaugeManager} from "./GaugeManager";
import {ServerWritableStream} from "grpc";
import {ZoneSocket} from "../RoomManager";
import {Zone} from "_Model/Zone";
import Debug from "debug";
const debug = Debug('sockermanager');
interface AdminSocketRoomsList {
[index: string]: number;
@ -54,10 +68,18 @@ export interface AdminSocketData {
users: AdminSocketUsersList,
}
function emitZoneMessage(subMessage: SubToPusherMessage, socket: ZoneSocket): void {
// TODO: should we batch those every 100ms?
const batchMessage = new BatchToPusherMessage();
batchMessage.addPayload(subMessage);
socket.write(batchMessage);
}
export class SocketManager {
private Worlds: Map<string, GameRoom> = new Map<string, GameRoom>();
private sockets: Map<number, ExSocketInterface> = new Map<number, ExSocketInterface>();
private rooms: Map<string, GameRoom> = new Map<string, GameRoom>();
//private sockets: Map<number, ExSocketInterface> = new Map<number, ExSocketInterface>();
constructor() {
clientEventsEmitter.registerToClientJoin((clientUUid: string, roomId: string) => {
gaugeManager.incNbClientPerRoomGauge(roomId);
@ -72,7 +94,7 @@ export class SocketManager {
rooms: {},
users: {},
}
const room = this.Worlds.get(roomId);
const room = this.rooms.get(roomId);
if (room === undefined) {
return data;
}
@ -84,95 +106,112 @@ export class SocketManager {
return data;
}
handleJoinRoom(client: ExSocketInterface): void {
const position = client.position;
const viewport = client.viewport;
try {
this.sockets.set(client.userId, client); //todo: should this be at the end of the function?
//join new previous room
const gameRoom = this.joinRoom(client, position);
public async handleJoinRoom(socket: UserSocket, joinRoomMessage: JoinRoomMessage): Promise<{ room: GameRoom; user: User }> {
/*const positionMessage = joinRoomMessage.getPositionmessage();
if (positionMessage === undefined) {
// TODO: send error message?
throw new Error('Empty pointMessage found in JoinRoomMessage');
}*/
const things = gameRoom.setViewport(client, viewport);
//const position = ProtobufUtils.toPointInterface(positionMessage);
//const viewport = client.viewport;
const roomJoinedMessage = new RoomJoinedMessage();
//this.sockets.set(client.userId, client); //todo: should this be at the end of the function?
for (const thing of things) {
if (thing instanceof User) {
const player: ExSocketInterface|undefined = this.sockets.get(thing.id);
if (player === undefined) {
console.warn('Something went wrong. The World contains a user "'+thing.id+"' but this user does not exist in the sockets list!");
continue;
}
//join new previous room
const {room, user} = await this.joinRoom(socket, joinRoomMessage);
const userJoinedMessage = new UserJoinedMessage();
userJoinedMessage.setUserid(thing.id);
userJoinedMessage.setName(player.name);
userJoinedMessage.setCharacterlayersList(ProtobufUtils.toCharacterLayerMessages(player.characterLayers));
userJoinedMessage.setPosition(ProtobufUtils.toPositionMessage(player.position));
roomJoinedMessage.addUser(userJoinedMessage);
roomJoinedMessage.setTagList(client.tags);
} else if (thing instanceof Group) {
const groupUpdateMessage = new GroupUpdateMessage();
groupUpdateMessage.setGroupid(thing.getId());
groupUpdateMessage.setPosition(ProtobufUtils.toPointMessage(thing.getPosition()));
roomJoinedMessage.addGroup(groupUpdateMessage);
} else {
console.error("Unexpected type for Movable returned by setViewport");
}
}
//const things = room.setViewport(client, viewport);
for (const [itemId, item] of gameRoom.getItemsState().entries()) {
const itemStateMessage = new ItemStateMessage();
itemStateMessage.setItemid(itemId);
itemStateMessage.setStatejson(JSON.stringify(item));
const roomJoinedMessage = new RoomJoinedMessage();
roomJoinedMessage.addItem(itemStateMessage);
}
/*for (const thing of things) {
if (thing instanceof User) {
const player: ExSocketInterface|undefined = this.sockets.get(thing.id);
if (player === undefined) {
console.warn('Something went wrong. The World contains a user "'+thing.id+"' but this user does not exist in the sockets list!");
continue;
}
roomJoinedMessage.setCurrentuserid(client.userId);
const userJoinedMessage = new UserJoinedMessage();
userJoinedMessage.setUserid(thing.id);
userJoinedMessage.setName(player.name);
userJoinedMessage.setCharacterlayersList(ProtobufUtils.toCharacterLayerMessages(player.characterLayers));
userJoinedMessage.setPosition(ProtobufUtils.toPositionMessage(player.position));
const serverToClientMessage = new ServerToClientMessage();
serverToClientMessage.setRoomjoinedmessage(roomJoinedMessage);
roomJoinedMessage.addUser(userJoinedMessage);
roomJoinedMessage.setTagList(joinRoomMessage.getTagList());
} else if (thing instanceof Group) {
const groupUpdateMessage = new GroupUpdateMessage();
groupUpdateMessage.setGroupid(thing.getId());
groupUpdateMessage.setPosition(ProtobufUtils.toPointMessage(thing.getPosition()));
if (!client.disconnecting) {
client.send(serverToClientMessage.serializeBinary().buffer, true);
roomJoinedMessage.addGroup(groupUpdateMessage);
} else {
console.error("Unexpected type for Movable returned by setViewport");
}
} catch (e) {
console.error('An error occurred on "join_room" event');
console.error(e);
}*/
for (const [itemId, item] of room.getItemsState().entries()) {
const itemStateMessage = new ItemStateMessage();
itemStateMessage.setItemid(itemId);
itemStateMessage.setStatejson(JSON.stringify(item));
roomJoinedMessage.addItem(itemStateMessage);
}
}
handleViewport(client: ExSocketInterface, viewportMessage: ViewportMessage) {
try {
const viewport = viewportMessage.toObject();
roomJoinedMessage.setCurrentuserid(user.id);
client.viewport = viewport;
const serverToClientMessage = new ServerToClientMessage();
serverToClientMessage.setRoomjoinedmessage(roomJoinedMessage);
const world = this.Worlds.get(client.roomId);
if (!world) {
console.error("In SET_VIEWPORT, could not find world with id '", client.roomId, "'");
return;
}
world.setViewport(client, client.viewport);
} catch (e) {
console.error('An error occurred on "SET_VIEWPORT" event');
console.error(e);
//user.socket.write(serverToClientMessage);
console.log('SENDING MESSAGE roomJoinedMessage');
socket.write(serverToClientMessage);
//get data information and show messages
if (ADMIN_API_URL) {
adminApi.fetchMemberDataByUuid(user.uuid).then((res: FetchMemberDataByUuidResponse) => {
if (!res.messages) {
return;
}
res.messages.forEach((c: unknown) => {
const messageToSend = c as { type: string, message: string };
socketManager.emitSendUserMessage({
userUuid: user.uuid,
type: messageToSend.type,
message: messageToSend.message
})
});
}).catch((err) => {
console.error('fetchMemberDataByUuid => err', err);
});
}
return {
room,
user
};
/*const serverToClientMessage = new ServerToClientMessage();
serverToClientMessage.setRoomjoinedmessage(roomJoinedMessage);
if (!client.disconnecting) {
client.send(serverToClientMessage.serializeBinary().buffer, true);
}*/
}
handleUserMovesMessage(client: ExSocketInterface, userMovesMessage: UserMovesMessage) {
handleUserMovesMessage(room: GameRoom, user: User, userMovesMessage: UserMovesMessage) {
try {
const userMoves = userMovesMessage.toObject();
const position = userMovesMessage.getPosition();
// If CPU is high, let's drop messages of users moving (we will only dispatch the final position)
if (cpuTracker.isOverHeating() && userMoves.position?.moving === true) {
return;
}
const position = userMoves.position;
if (position === undefined) {
throw new Error('Position not found in message');
}
@ -181,41 +220,18 @@ export class SocketManager {
throw new Error('Viewport not found in message');
}
let direction: string;
switch (position.direction) {
case Direction.UP:
direction = 'up';
break;
case Direction.DOWN:
direction = 'down';
break;
case Direction.LEFT:
direction = 'left';
break;
case Direction.RIGHT:
direction = 'right';
break;
default:
throw new Error("Unexpected direction");
}
// sending to all clients in room except sender
client.position = {
/*client.position = {
x: position.x,
y: position.y,
direction,
moving: position.moving,
};
client.viewport = viewport;
client.viewport = viewport;*/
// update position in the world
const world = this.Worlds.get(client.roomId);
if (!world) {
console.error("In USER_POSITION, could not find world with id '", client.roomId, "'");
return;
}
world.updatePosition(client, client.position);
world.setViewport(client, client.viewport);
room.updatePosition(user, ProtobufUtils.toPointInterface(position));
//room.setViewport(client, client.viewport);
} catch (e) {
console.error('An error occurred on "user_position" event');
console.error(e);
@ -223,7 +239,7 @@ export class SocketManager {
}
// Useless now, will be useful again if we allow editing details in game
handleSetPlayerDetails(client: ExSocketInterface, playerDetailsMessage: SetPlayerDetailsMessage) {
/*handleSetPlayerDetails(client: UserSocket, playerDetailsMessage: SetPlayerDetailsMessage) {
const playerDetails = {
name: playerDetailsMessage.getName(),
characterLayers: playerDetailsMessage.getCharacterlayersList()
@ -235,51 +251,39 @@ export class SocketManager {
}
client.name = playerDetails.name;
client.characterLayers = SocketManager.mergeCharacterLayersAndCustomTextures(playerDetails.characterLayers, client.textures);
}
}*/
handleSilentMessage(client: ExSocketInterface, silentMessage: SilentMessage) {
handleSilentMessage(room: GameRoom, user: User, silentMessage: SilentMessage) {
try {
// update position in the world
const world = this.Worlds.get(client.roomId);
if (!world) {
console.error("In handleSilentMessage, could not find world with id '", client.roomId, "'");
return;
}
world.setSilent(client, silentMessage.getSilent());
room.setSilent(user, silentMessage.getSilent());
} catch (e) {
console.error('An error occurred on "handleSilentMessage"');
console.error(e);
}
}
handleItemEvent(ws: ExSocketInterface, itemEventMessage: ItemEventMessage) {
handleItemEvent(room: GameRoom, user: User, itemEventMessage: ItemEventMessage) {
const itemEvent = ProtobufUtils.toItemEvent(itemEventMessage);
try {
const world = this.Worlds.get(ws.roomId);
if (!world) {
console.error("Could not find world with id '", ws.roomId, "'");
return;
}
const subMessage = new SubMessage();
subMessage.setItemeventmessage(itemEventMessage);
// Let's send the event without using the SocketIO room.
for (const user of world.getUsers().values()) {
const client = this.searchClientByIdOrFail(user.id);
//client.emit(SocketIoEvent.ITEM_EVENT, itemEvent);
emitInBatch(client, subMessage);
// TODO: move this in the GameRoom class.
for (const user of room.getUsers().values()) {
user.emitInBatch(subMessage);
}
world.setItemState(itemEvent.itemId, itemEvent.state);
room.setItemState(itemEvent.itemId, itemEvent.state);
} catch (e) {
console.error('An error occurred on "item_event"');
console.error(e);
}
}
async handleReportMessage(client: ExSocketInterface, reportPlayerMessage: ReportPlayerMessage) {
// TODO: handle this message in pusher
/*async handleReportMessage(client: ExSocketInterface, reportPlayerMessage: ReportPlayerMessage) {
try {
const reportedSocket = this.sockets.get(reportPlayerMessage.getReporteduserid());
if (!reportedSocket) {
@ -291,82 +295,68 @@ export class SocketManager {
console.error('An error occurred on "handleReportMessage"');
console.error(e);
}
}
}*/
emitVideo(socket: ExSocketInterface, data: WebRtcSignalToServerMessage): void {
emitVideo(room: GameRoom, user: User, data: WebRtcSignalToServerMessage): void {
//send only at user
const client = this.sockets.get(data.getReceiverid());
if (client === undefined) {
const remoteUser = room.getUsers().get(data.getReceiverid());
if (remoteUser === undefined) {
console.warn("While exchanging a WebRTC signal: client with id ", data.getReceiverid(), " does not exist. This might be a race condition.");
return;
}
const webrtcSignalToClient = new WebRtcSignalToClientMessage();
webrtcSignalToClient.setUserid(socket.userId);
webrtcSignalToClient.setUserid(user.id);
webrtcSignalToClient.setSignal(data.getSignal());
const serverToClientMessage = new ServerToClientMessage();
serverToClientMessage.setWebrtcsignaltoclientmessage(webrtcSignalToClient);
if (!client.disconnecting) {
client.send(serverToClientMessage.serializeBinary().buffer, true);
}
//if (!client.disconnecting) {
remoteUser.socket.write(serverToClientMessage);
//}
}
emitScreenSharing(socket: ExSocketInterface, data: WebRtcSignalToServerMessage): void {
emitScreenSharing(room: GameRoom, user: User, data: WebRtcSignalToServerMessage): void {
//send only at user
const client = this.sockets.get(data.getReceiverid());
if (client === undefined) {
const remoteUser = room.getUsers().get(data.getReceiverid());
if (remoteUser === undefined) {
console.warn("While exchanging a WEBRTC_SCREEN_SHARING signal: client with id ", data.getReceiverid(), " does not exist. This might be a race condition.");
return;
}
const webrtcSignalToClient = new WebRtcSignalToClientMessage();
webrtcSignalToClient.setUserid(socket.userId);
webrtcSignalToClient.setUserid(user.id);
webrtcSignalToClient.setSignal(data.getSignal());
const serverToClientMessage = new ServerToClientMessage();
serverToClientMessage.setWebrtcscreensharingsignaltoclientmessage(webrtcSignalToClient);
if (!client.disconnecting) {
client.send(serverToClientMessage.serializeBinary().buffer, true);
}
}
private searchClientByIdOrFail(userId: number): ExSocketInterface {
const client: ExSocketInterface|undefined = this.sockets.get(userId);
if (client === undefined) {
throw new Error("Could not find user with id " + userId);
}
return client;
//if (!client.disconnecting) {
remoteUser.socket.write(serverToClientMessage);
//}
}
leaveRoom(Client : ExSocketInterface){
leaveRoom(room: GameRoom, user: User){
// leave previous room and world
if(Client.roomId){
try {
//user leave previous world
const world: GameRoom | undefined = this.Worlds.get(Client.roomId);
if (world) {
world.leave(Client);
if (world.isEmpty()) {
this.Worlds.delete(Client.roomId);
}
}
//user leave previous room
//Client.leave(Client.roomId);
} finally {
//delete Client.roomId;
this.sockets.delete(Client.userId);
clientEventsEmitter.emitClientLeave(Client.userUuid, Client.roomId);
console.log('A user left (', this.sockets.size, ' connected users)');
try {
//user leave previous world
room.leave(user);
if (room.isEmpty()) {
this.rooms.delete(room.roomId);
debug('Room is empty. Deleting room "%s"', room.roomId);
}
} finally {
//delete Client.roomId;
//this.sockets.delete(Client.userId);
clientEventsEmitter.emitClientLeave(user.uuid, room.roomId);
console.log('A user left');
}
}
async getOrCreateRoom(roomId: string): Promise<GameRoom> {
//check and create new world for a room
let world = this.Worlds.get(roomId)
let world = this.rooms.get(roomId)
if(world === undefined){
world = new GameRoom(
roomId,
@ -374,134 +364,141 @@ export class SocketManager {
(user: User, group: Group) => this.disConnectedUser(user, group),
MINIMUM_DISTANCE,
GROUP_RADIUS,
(thing: Movable, listener: User) => this.onRoomEnter(thing, listener),
(thing: Movable, position:PositionInterface, listener:User) => this.onClientMove(thing, position, listener),
(thing: Movable, listener:User) => this.onClientLeave(thing, listener)
(thing: Movable, fromZone: Zone|null, listener: ZoneSocket) => this.onZoneEnter(thing, fromZone, listener),
(thing: Movable, position:PositionInterface, listener: ZoneSocket) => this.onClientMove(thing, position, listener),
(thing: Movable, newZone: Zone|null, listener: ZoneSocket) => this.onClientLeave(thing, newZone, listener)
);
if (!world.anonymous) {
const data = await adminApi.fetchMapDetails(world.organizationSlug, world.worldSlug, world.roomSlug)
world.tags = data.tags
world.policyType = Number(data.policy_type)
}
this.Worlds.set(roomId, world);
this.rooms.set(roomId, world);
}
return Promise.resolve(world)
}
private joinRoom(client : ExSocketInterface, position: PointInterface): GameRoom {
private async joinRoom(socket: UserSocket, joinRoomMessage: JoinRoomMessage): Promise<{ room: GameRoom; user: User }> {
const roomId = client.roomId;
client.position = position;
const roomId = joinRoomMessage.getRoomid();
const world = this.Worlds.get(roomId)
if(world === undefined){
throw new Error('Could not find room for ID: '+client.roomId)
}
const world = await socketManager.getOrCreateRoom(roomId);
// Dispatch groups position to newly connected user
world.getGroups().forEach((group: Group) => {
this.emitCreateUpdateGroupEvent(client, group);
});
/*world.getGroups().forEach((group: Group) => {
this.emitCreateUpdateGroupEvent(socket, group);
});*/
//join world
world.join(client, client.position);
clientEventsEmitter.emitClientJoin(client.userUuid, client.roomId);
console.log(new Date().toISOString() + ' A user joined (', this.sockets.size, ' connected users)');
return world;
const user = world.join(socket, joinRoomMessage);
clientEventsEmitter.emitClientJoin(user.uuid, roomId);
//console.log(new Date().toISOString() + ' A user joined (', this.sockets.size, ' connected users)');
console.log(new Date().toISOString() + ' A user joined');
return {room: world, user};
}
private onRoomEnter(thing: Movable, listener: User) {
const clientListener = this.searchClientByIdOrFail(listener.id);
private onZoneEnter(thing: Movable, fromZone: Zone|null, listener: ZoneSocket) {
if (thing instanceof User) {
const clientUser = this.searchClientByIdOrFail(thing.id);
const userJoinedMessage = new UserJoinedMessage();
if (!Number.isInteger(clientUser.userId)) {
throw new Error('clientUser.userId is not an integer '+clientUser.userId);
const userJoinedZoneMessage = new UserJoinedZoneMessage();
if (!Number.isInteger(thing.id)) {
throw new Error('clientUser.userId is not an integer '+thing.id);
}
userJoinedMessage.setUserid(clientUser.userId);
userJoinedMessage.setName(clientUser.name);
userJoinedMessage.setCharacterlayersList(ProtobufUtils.toCharacterLayerMessages(clientUser.characterLayers));
userJoinedMessage.setPosition(ProtobufUtils.toPositionMessage(clientUser.position));
userJoinedZoneMessage.setUserid(thing.id);
userJoinedZoneMessage.setName(thing.name);
userJoinedZoneMessage.setCharacterlayersList(ProtobufUtils.toCharacterLayerMessages(thing.characterLayers));
userJoinedZoneMessage.setPosition(ProtobufUtils.toPositionMessage(thing.getPosition()));
userJoinedZoneMessage.setFromzone(this.toProtoZone(fromZone));
const subMessage = new SubMessage();
subMessage.setUserjoinedmessage(userJoinedMessage);
const subMessage = new SubToPusherMessage();
subMessage.setUserjoinedzonemessage(userJoinedZoneMessage);
emitInBatch(clientListener, subMessage);
emitZoneMessage(subMessage, listener);
//listener.emitInBatch(subMessage);
} else if (thing instanceof Group) {
this.emitCreateUpdateGroupEvent(clientListener, thing);
this.emitCreateUpdateGroupEvent(listener, fromZone, thing);
} else {
console.error('Unexpected type for Movable.');
}
}
private onClientMove(thing: Movable, position:PositionInterface, listener:User): void {
const clientListener = this.searchClientByIdOrFail(listener.id);
private onClientMove(thing: Movable, position:PositionInterface, listener: ZoneSocket): void {
if (thing instanceof User) {
const clientUser = this.searchClientByIdOrFail(thing.id);
const userMovedMessage = new UserMovedMessage();
userMovedMessage.setUserid(clientUser.userId);
userMovedMessage.setPosition(ProtobufUtils.toPositionMessage(clientUser.position));
userMovedMessage.setUserid(thing.id);
userMovedMessage.setPosition(ProtobufUtils.toPositionMessage(thing.getPosition()));
const subMessage = new SubMessage();
const subMessage = new SubToPusherMessage();
subMessage.setUsermovedmessage(userMovedMessage);