From 5a3668a12e8c75d6b8220f1bdeec4375cef2a883 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Fri, 15 May 2020 22:04:49 +0200 Subject: [PATCH 01/13] Refactoring messages Socket.io can stringify JSON messages itself, so there is no need to pass a string to "emit". You can pass a serializable object! This commit removes all the useless toJson() methods, JSON.serialize and JSON.parse! Woot! --- back/src/Controller/IoSocketController.ts | 26 +++++++--------- front/src/Connexion.ts | 38 +++-------------------- front/src/WebRtc/SimplePeer.ts | 16 +++++----- 3 files changed, 25 insertions(+), 55 deletions(-) diff --git a/back/src/Controller/IoSocketController.ts b/back/src/Controller/IoSocketController.ts index 6349b352..781d811d 100644 --- a/back/src/Controller/IoSocketController.ts +++ b/back/src/Controller/IoSocketController.ts @@ -97,7 +97,7 @@ export class IoSocketController { try { let messageUserPosition = this.hydrateMessageReceive(message); if (messageUserPosition instanceof Error) { - return socket.emit(SockerIoEvent.MESSAGE_ERROR, JSON.stringify({message: messageUserPosition.message})) + return socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: messageUserPosition.message}) } let Client = (socket as ExSocketInterface); @@ -129,7 +129,7 @@ export class IoSocketController { try { let messageUserPosition = this.hydrateMessageReceive(message); if (messageUserPosition instanceof Error) { - return socket.emit(SockerIoEvent.MESSAGE_ERROR, JSON.stringify({message: messageUserPosition.message})); + return socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: messageUserPosition.message}); } let Client = (socket as ExSocketInterface); @@ -145,19 +145,17 @@ export class IoSocketController { } }); - socket.on(SockerIoEvent.WEBRTC_SIGNAL, (message: string) => { - let data: any = JSON.parse(message); + socket.on(SockerIoEvent.WEBRTC_SIGNAL, (data: any) => { //send only at user let client = this.searchClientById(data.receiverId); if (!client) { console.error("client doesn't exist for ", data.receiverId); return; } - return client.emit(SockerIoEvent.WEBRTC_SIGNAL, message); + return client.emit(SockerIoEvent.WEBRTC_SIGNAL, data); }); - socket.on(SockerIoEvent.WEBRTC_OFFER, (message: string) => { - let data: any = JSON.parse(message); + socket.on(SockerIoEvent.WEBRTC_OFFER, (data: any) => { //send only at user let client = this.searchClientById(data.receiverId); @@ -165,7 +163,7 @@ export class IoSocketController { console.error("client doesn't exist for ", data.receiverId); return; } - client.emit(SockerIoEvent.WEBRTC_OFFER, message); + client.emit(SockerIoEvent.WEBRTC_OFFER, data); }); socket.on(SockerIoEvent.DISCONNECT, () => { @@ -212,6 +210,7 @@ export class IoSocketController { return client; } console.log("Could not find user with id ", userId); + throw new Error("Could not find user with id " + userId); return null; } @@ -235,9 +234,9 @@ export class IoSocketController { * @param Client: ExSocketInterface */ sendDisconnectedEvent(Client: ExSocketInterface) { - Client.broadcast.emit(SockerIoEvent.WEBRTC_DISCONNECT, JSON.stringify({ + Client.broadcast.emit(SockerIoEvent.WEBRTC_DISCONNECT, { userId: Client.id - })); + }); //disconnect webrtc room if(!Client.webRtcRoomId){ @@ -257,7 +256,6 @@ export class IoSocketController { //user leave previous world let world : World|undefined = this.Worlds.get(Client.roomId); if(world){ - console.log('Entering world.leave') world.leave(Client); //this.Worlds.set(Client.roomId, world); } @@ -341,7 +339,7 @@ export class IoSocketController { return tabs; }, []); - client.emit(SockerIoEvent.WEBRTC_START, JSON.stringify({clients: clientsId, roomId: roomId})); + client.emit(SockerIoEvent.WEBRTC_START, {clients: clientsId, roomId: roomId}); }); } @@ -382,7 +380,7 @@ export class IoSocketController { //Hydrate and manage error hydrateMessageReceive(message: string): MessageUserPosition | Error { try { - return new MessageUserPosition(JSON.parse(message)); + return new MessageUserPosition(message); } catch (err) { //TODO log error return new Error(err); @@ -421,7 +419,7 @@ export class IoSocketController { } arrayMap.forEach((value: any) => { let roomId = value[0]; - this.Io.in(roomId).emit(SockerIoEvent.USER_POSITION, JSON.stringify(value)); + this.Io.in(roomId).emit(SockerIoEvent.USER_POSITION, value); }); this.seTimeOutInProgress = setTimeout(() => { this.shareUsersPosition(); diff --git a/front/src/Connexion.ts b/front/src/Connexion.ts index f29bef2e..b071c101 100644 --- a/front/src/Connexion.ts +++ b/front/src/Connexion.ts @@ -34,22 +34,12 @@ class Message { this.name = name; this.character = character; } - - toJson() { - return { - userId: this.userId, - roomId: this.roomId, - name: this.name, - character: this.character - } - } } export interface PointInterface { x: number; y: number; direction : string; - toJson() : object; } class Point implements PointInterface{ @@ -65,14 +55,6 @@ class Point implements PointInterface{ this.y = y; this.direction = direction; } - - toJson(){ - return { - x : this.x, - y: this.y, - direction: this.direction - } - } } export interface MessageUserPositionInterface { @@ -90,16 +72,6 @@ class MessageUserPosition extends Message implements MessageUserPositionInterfac super(userId, roomId, name, character); this.position = point; } - - toString() { - return JSON.stringify( - Object.assign( - super.toJson(), - { - position: this.position.toJson() - }) - ); - } } export interface ListMessageUserPositionInterface { @@ -274,7 +246,7 @@ export class Connexion implements ConnexionInterface { this.email, character ); - this.socket.emit(EventMessage.JOIN_ROOM, messageUserPosition.toString()); + this.socket.emit(EventMessage.JOIN_ROOM, messageUserPosition); } /** @@ -297,7 +269,7 @@ export class Connexion implements ConnexionInterface { character ); this.lastPositionShared = messageUserPosition; - this.socket.emit(EventMessage.USER_POSITION, messageUserPosition.toString()); + this.socket.emit(EventMessage.USER_POSITION, messageUserPosition); } attributeUserId(): void { @@ -326,7 +298,7 @@ export class Connexion implements ConnexionInterface { **/ positionOfAllUser(): void { this.socket.on(EventMessage.USER_POSITION, (message: string) => { - let dataList = JSON.parse(message); + let dataList = message; let UserPositions : Array = Object.values(dataList); let listMessageUserPosition = new ListMessageUserPosition(UserPositions[0], UserPositions[1]); this.GameManager.shareUserPosition(listMessageUserPosition); @@ -347,12 +319,12 @@ export class Connexion implements ConnexionInterface { } sendWebrtcSignal(signal: any, roomId: string, userId? : string, receiverId? : string) { - return this.socket.emit(EventMessage.WEBRTC_SIGNAL, JSON.stringify({ + return this.socket.emit(EventMessage.WEBRTC_SIGNAL, { userId: userId ? userId : this.userId, receiverId: receiverId ? receiverId : this.userId, roomId: roomId, signal: signal - })); + }); } receiveWebrtcStart(callback: Function) { diff --git a/front/src/WebRtc/SimplePeer.ts b/front/src/WebRtc/SimplePeer.ts index 02f35329..54b7e0ed 100644 --- a/front/src/WebRtc/SimplePeer.ts +++ b/front/src/WebRtc/SimplePeer.ts @@ -32,7 +32,7 @@ export class SimplePeer implements SimplePeerInterface{ private initialise() { //receive signal by gemer - this.Connexion.receiveWebrtcSignal((message: string) => { + this.Connexion.receiveWebrtcSignal((message: any) => { this.receiveWebrtcSignal(message); }); @@ -40,7 +40,7 @@ export class SimplePeer implements SimplePeerInterface{ this.MediaManager.getCamera().then(() => { //receive message start - this.Connexion.receiveWebrtcStart((message: string) => { + this.Connexion.receiveWebrtcStart((message: any) => { this.receiveWebrtcStart(message); }); @@ -49,8 +49,8 @@ export class SimplePeer implements SimplePeerInterface{ }); //receive signal by gemer - this.Connexion.disconnectMessage((message: string) => { - let data = JSON.parse(message); + this.Connexion.disconnectMessage((message: any) => { + let data = message; this.closeConnexion(data.userId); }); } @@ -59,8 +59,8 @@ export class SimplePeer implements SimplePeerInterface{ * * @param message */ - private receiveWebrtcStart(message: string) { - let data = JSON.parse(message); + private receiveWebrtcStart(message: any) { + let data = message; this.WebRtcRoomId = data.roomId; this.Users = data.clients; @@ -197,8 +197,8 @@ export class SimplePeer implements SimplePeerInterface{ * * @param message */ - private receiveWebrtcSignal(message: string) { - let data = JSON.parse(message); + private receiveWebrtcSignal(message: any) { + let data = message; try { //if offer type, create peer connexion if(data.signal.type === "offer"){ From 4e745f20f7143bccee3d1f4538a2f14498dc4d31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Fri, 15 May 2020 22:08:53 +0200 Subject: [PATCH 02/13] More code removal --- .../src/Model/Websocket/MessageUserPosition.ts | 18 ------------------ back/src/Model/Websocket/PointInterface.ts | 3 +-- 2 files changed, 1 insertion(+), 20 deletions(-) diff --git a/back/src/Model/Websocket/MessageUserPosition.ts b/back/src/Model/Websocket/MessageUserPosition.ts index 1b534620..4f27c26a 100644 --- a/back/src/Model/Websocket/MessageUserPosition.ts +++ b/back/src/Model/Websocket/MessageUserPosition.ts @@ -14,14 +14,6 @@ export class Point implements PointInterface{ this.y = y; this.direction = direction; } - - toJson(){ - return { - x : this.x, - y: this.y, - direction: this.direction - } - } } export class MessageUserPosition extends Message{ @@ -31,14 +23,4 @@ export class MessageUserPosition extends Message{ super(message); this.position = new Point(message.position.x, message.position.y, message.position.direction); } - - toString() { - return JSON.stringify( - Object.assign( - super.toJson(), - { - position: this.position.toJson() - }) - ); - } } diff --git a/back/src/Model/Websocket/PointInterface.ts b/back/src/Model/Websocket/PointInterface.ts index 7b464a5d..9243acbe 100644 --- a/back/src/Model/Websocket/PointInterface.ts +++ b/back/src/Model/Websocket/PointInterface.ts @@ -2,5 +2,4 @@ export interface PointInterface { x: number; y: number; direction: string; - toJson() : object; -} \ No newline at end of file +} From fff0e13a2eb199db19f7cdeee1bc0ad1a78a0103 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Fri, 15 May 2020 22:09:21 +0200 Subject: [PATCH 03/13] More code removal --- back/src/Model/Websocket/Message.ts | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/back/src/Model/Websocket/Message.ts b/back/src/Model/Websocket/Message.ts index f4bdead8..70775d2b 100644 --- a/back/src/Model/Websocket/Message.ts +++ b/back/src/Model/Websocket/Message.ts @@ -14,14 +14,4 @@ export class Message { this.name = data.name; this.character = data.character; } - - toJson() { - - return { - userId: this.userId, - roomId: this.roomId, - name: this.name, - character: this.character - } - } } From b80e3e07d8bea3095e1ed90989fb6c5dd393c9df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Fri, 15 May 2020 22:40:06 +0200 Subject: [PATCH 04/13] Sending player details (name + character selected) on connection --- back/src/Controller/IoSocketController.ts | 12 +++- .../Websocket/SetPlayerDetailsMessage.ts | 4 ++ front/src/Connexion.ts | 69 ++++++++----------- front/src/Messages/SetPlayerDetailsMessage.ts | 4 ++ front/src/Phaser/Game/GameManager.ts | 4 +- 5 files changed, 48 insertions(+), 45 deletions(-) create mode 100644 back/src/Model/Websocket/SetPlayerDetailsMessage.ts create mode 100644 front/src/Messages/SetPlayerDetailsMessage.ts diff --git a/back/src/Controller/IoSocketController.ts b/back/src/Controller/IoSocketController.ts index 781d811d..511c6b42 100644 --- a/back/src/Controller/IoSocketController.ts +++ b/back/src/Controller/IoSocketController.ts @@ -10,11 +10,11 @@ import {ExtRoomsInterface} from "../Model/Websocket/ExtRoomsInterface"; import {World} from "../Model/World"; import {Group} from "_Model/Group"; import {UserInterface} from "_Model/UserInterface"; +import {SetPlayerDetailsMessage} from "_Model/Websocket/SetPlayerDetailsMessage"; enum SockerIoEvent { CONNECTION = "connection", DISCONNECT = "disconnect", - ATTRIBUTE_USER_ID = "attribute-user-id", // Sent from server to client just after the connexion is established to give the client its unique id. JOIN_ROOM = "join-room", USER_POSITION = "user-position", WEBRTC_SIGNAL = "webrtc-signal", @@ -24,6 +24,7 @@ enum SockerIoEvent { MESSAGE_ERROR = "message-error", GROUP_CREATE_UPDATE = "group-create-update", GROUP_DELETE = "group-delete", + SET_PLAYER_DETAILS = "set-player-details" } export class IoSocketController { @@ -125,7 +126,7 @@ export class IoSocketController { } }); - socket.on(SockerIoEvent.USER_POSITION, (message: string) => { + socket.on(SockerIoEvent.USER_POSITION, (message: any) => { try { let messageUserPosition = this.hydrateMessageReceive(message); if (messageUserPosition instanceof Error) { @@ -192,7 +193,12 @@ export class IoSocketController { }); // Let's send the user id to the user - socket.emit(SockerIoEvent.ATTRIBUTE_USER_ID, socket.id); + socket.on(SockerIoEvent.SET_PLAYER_DETAILS, (playerDetails: SetPlayerDetailsMessage, answerFn) => { + let Client = (socket as ExSocketInterface); + Client.name = playerDetails.name; + Client.character = playerDetails.character; + answerFn(socket.id); + }); }); } diff --git a/back/src/Model/Websocket/SetPlayerDetailsMessage.ts b/back/src/Model/Websocket/SetPlayerDetailsMessage.ts new file mode 100644 index 00000000..2f3cc707 --- /dev/null +++ b/back/src/Model/Websocket/SetPlayerDetailsMessage.ts @@ -0,0 +1,4 @@ +export interface SetPlayerDetailsMessage { + name: string, + character: string +} diff --git a/front/src/Connexion.ts b/front/src/Connexion.ts index b071c101..6b6049d2 100644 --- a/front/src/Connexion.ts +++ b/front/src/Connexion.ts @@ -1,10 +1,12 @@ import {GameManager} from "./Phaser/Game/GameManager"; - -const SocketIo = require('socket.io-client'); import Axios from "axios"; import {API_URL} from "./Enum/EnvironmentVariable"; -import {getMapKeyByUrl} from "./Phaser/Login/LogincScene"; import {MessageUI} from "./Logger/MessageUI"; +import {SetPlayerDetailsMessage} from "./Messages/SetPlayerDetailsMessage"; + +const SocketIo = require('socket.io-client'); +import Socket = SocketIOClient.Socket; + enum EventMessage{ WEBRTC_SIGNAL = "webrtc-signal", @@ -19,7 +21,7 @@ enum EventMessage{ CONNECT_ERROR = "connect_error", RECONNECT = "reconnect", - ATTRIBUTE_USER_ID = "attribute-user-id" // Sent from server to client just after the connexion is established to give the client its unique id. + SET_PLAYER_DETAILS = "set-player-details" // Send the name and character to the server (on connect), receive back the id. } class Message { @@ -115,10 +117,10 @@ export interface GroupCreatedUpdatedMessageInterface { export interface ConnexionInterface { socket: any; token: string; - email: string; + name: string; userId: string; - createConnexion(characterSelected: string): Promise; + createConnexion(name: string, characterSelected: string): Promise; loadMaps(): Promise; @@ -139,24 +141,23 @@ export interface ConnexionInterface { } export class Connexion implements ConnexionInterface { - socket: any; + socket: Socket; token: string; - email: string; + name: string; // TODO: drop "name" storage here + character: string; userId: string; GameManager: GameManager; lastPositionShared: MessageUserPosition = null; - constructor(email : string, GameManager: GameManager) { - this.email = email; + constructor(GameManager: GameManager) { this.GameManager = GameManager; } - /** - * @param characterSelected - */ - createConnexion(characterSelected: string): Promise { + createConnexion(name: string, characterSelected: string): Promise { + this.name = name; + this.character = characterSelected; /*return Axios.post(`${API_URL}/login`, {email: this.email}) .then((res) => { this.token = res.data.token; @@ -168,19 +169,7 @@ export class Connexion implements ConnexionInterface { }*/ }); - this.connectSocketServer(); - - // TODO: maybe trigger promise only when connexion is established? - let promise = new Promise((resolve, reject) => { - /*console.log('PROMISE CREATED') - this.socket.on('connection', () => { - console.log('CONNECTED'); - resolve(this); - });*/ - resolve(this); - }); - - return promise; + return this.connectSocketServer(); /* return res.data; }) @@ -194,7 +183,7 @@ export class Connexion implements ConnexionInterface { * * @param character */ - connectSocketServer(character : string = null){ + connectSocketServer(): Promise{ //if try to reconnect with last position if(this.lastPositionShared) { //join the room @@ -214,12 +203,21 @@ export class Connexion implements ConnexionInterface { } //listen event - this.attributeUserId(); this.positionOfAllUser(); this.disconnectServer(); this.errorMessage(); this.groupUpdatedOrCreated(); this.groupDeleted(); + + return new Promise((resolve, reject) => { + this.socket.emit(EventMessage.SET_PLAYER_DETAILS, { + name: this.name, + character: this.character + } as SetPlayerDetailsMessage, (id: string) => { + this.userId = id; + }); + resolve(this); + }); } //TODO add middleware with access token to secure api @@ -243,7 +241,7 @@ export class Connexion implements ConnexionInterface { this.userId, roomId, new Point(0, 0), - this.email, + this.name, character ); this.socket.emit(EventMessage.JOIN_ROOM, messageUserPosition); @@ -265,22 +263,13 @@ export class Connexion implements ConnexionInterface { this.userId, roomId, new Point(x, y, direction), - this.email, + this.name, character ); this.lastPositionShared = messageUserPosition; this.socket.emit(EventMessage.USER_POSITION, messageUserPosition); } - attributeUserId(): void { - // This event is received as soon as the connexion is established. - // It allows informing the browser of its own user id. - this.socket.on(EventMessage.ATTRIBUTE_USER_ID, (userId: string) => { - console.log('Received my user id: ', userId); - this.userId = userId; - }); - } - /** * The data sent is an array with information for each user : * [ diff --git a/front/src/Messages/SetPlayerDetailsMessage.ts b/front/src/Messages/SetPlayerDetailsMessage.ts new file mode 100644 index 00000000..2f3cc707 --- /dev/null +++ b/front/src/Messages/SetPlayerDetailsMessage.ts @@ -0,0 +1,4 @@ +export interface SetPlayerDetailsMessage { + name: string, + character: string +} diff --git a/front/src/Phaser/Game/GameManager.ts b/front/src/Phaser/Game/GameManager.ts index b886de9e..1728d0d9 100644 --- a/front/src/Phaser/Game/GameManager.ts +++ b/front/src/Phaser/Game/GameManager.ts @@ -40,8 +40,8 @@ export class GameManager { connect(name: string, characterUserSelected : string) { this.playerName = name; this.characterUserSelected = characterUserSelected; - this.ConnexionInstance = new Connexion(name, this); - return this.ConnexionInstance.createConnexion(characterUserSelected).then((data : any) => { + this.ConnexionInstance = new Connexion(this); + return this.ConnexionInstance.createConnexion(name, characterUserSelected).then((data : any) => { this.SimplePeer = new SimplePeer(this.ConnexionInstance); return data; }).catch((err) => { From 7e00d61f9484a949e598cec903dba4aab38d49aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Fri, 15 May 2020 23:17:58 +0200 Subject: [PATCH 05/13] Fixing test --- back/tests/MessageTest.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/back/tests/MessageTest.ts b/back/tests/MessageTest.ts index d908e12e..ab7d6476 100644 --- a/back/tests/MessageTest.ts +++ b/back/tests/MessageTest.ts @@ -11,12 +11,6 @@ describe("Message Model", () => { expect(messageObject.character).toBe("user"); }) - it("should expose a toJson method", () => { - let message = {userId: "test1", roomId: "test2", name: "foo", character: "user"}; - let messageObject = new Message(message); - expect(messageObject.toJson()).toEqual({userId: "test1", roomId: "test2", name: "foo", character: "user"}); - }); - it("should find throw error when no userId", () => { let message = {roomId: "test2"}; expect(() => { From cdfa9acf01d942d69f965d690f1d271f9a5abfc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Fri, 15 May 2020 23:24:04 +0200 Subject: [PATCH 06/13] JoinRoom now ONLY sends the roomId. --- back/src/Controller/IoSocketController.ts | 64 +++++++++---------- back/src/Model/World.ts | 10 +-- back/tests/WorldTest.ts | 78 ++++------------------- front/src/Connexion.ts | 21 +++--- 4 files changed, 57 insertions(+), 116 deletions(-) diff --git a/back/src/Controller/IoSocketController.ts b/back/src/Controller/IoSocketController.ts index 511c6b42..459fd5f2 100644 --- a/back/src/Controller/IoSocketController.ts +++ b/back/src/Controller/IoSocketController.ts @@ -1,7 +1,7 @@ import socketIO = require('socket.io'); import {Socket} from "socket.io"; import * as http from "http"; -import {MessageUserPosition} from "../Model/Websocket/MessageUserPosition"; //TODO fix import by "_Model/.." +import {MessageUserPosition, Point} from "../Model/Websocket/MessageUserPosition"; //TODO fix import by "_Model/.." import {ExSocketInterface} from "../Model/Websocket/ExSocketInterface"; //TODO fix import by "_Model/.." import Jwt, {JsonWebTokenError} from "jsonwebtoken"; import {SECRET_KEY, MINIMUM_DISTANCE, GROUP_RADIUS} from "../Enum/EnvironmentVariable"; //TODO fix import by "_Enum/..." @@ -11,6 +11,7 @@ import {World} from "../Model/World"; import {Group} from "_Model/Group"; import {UserInterface} from "_Model/UserInterface"; import {SetPlayerDetailsMessage} from "_Model/Websocket/SetPlayerDetailsMessage"; +import {MessageUserPositionInterface} from "../../../front/src/Connexion"; enum SockerIoEvent { CONNECTION = "connection", @@ -94,16 +95,15 @@ export class IoSocketController { x: user x position on map y: user y position on map */ - socket.on(SockerIoEvent.JOIN_ROOM, (message: string) => { + socket.on(SockerIoEvent.JOIN_ROOM, (roomId: any) => { try { - let messageUserPosition = this.hydrateMessageReceive(message); - if (messageUserPosition instanceof Error) { - return socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: messageUserPosition.message}) + if (typeof(roomId) !== 'string') { + return socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: 'Expected roomId as a string.'}) } let Client = (socket as ExSocketInterface); - if (Client.roomId === messageUserPosition.roomId) { + if (Client.roomId === roomId) { return; } @@ -111,15 +111,20 @@ export class IoSocketController { this.leaveRoom(Client); //join new previous room - this.joinRoom(Client, messageUserPosition); - - // sending to all clients in room except sender - this.saveUserInformation(Client, messageUserPosition); + this.joinRoom(Client, roomId); //add function to refresh position user in real time. this.refreshUserPosition(Client); - socket.to(messageUserPosition.roomId).emit(SockerIoEvent.JOIN_ROOM, messageUserPosition.toString()); + let messageUserPosition = new MessageUserPosition({ + userId: Client.id, + roomId: Client.roomId, + name: Client.name, + character: Client.character, + position: new Point(0, 0, 'none') + }); + + socket.to(roomId).emit(SockerIoEvent.JOIN_ROOM, messageUserPosition); } catch (e) { console.error('An error occurred on "join_room" event'); console.error(e); @@ -150,7 +155,7 @@ export class IoSocketController { //send only at user let client = this.searchClientById(data.receiverId); if (!client) { - console.error("client doesn't exist for ", data.receiverId); + console.error("While exchanging a WebRTC signal: client doesn't exist for ", data.receiverId); return; } return client.emit(SockerIoEvent.WEBRTC_SIGNAL, data); @@ -216,7 +221,7 @@ export class IoSocketController { return client; } console.log("Could not find user with id ", userId); - throw new Error("Could not find user with id " + userId); + //throw new Error("Could not find user with id " + userId); return null; } @@ -252,10 +257,6 @@ export class IoSocketController { delete Client.webRtcRoomId; } - /** - * - * @param Client - */ leaveRoom(Client : ExSocketInterface){ //lease previous room and world if(Client.roomId){ @@ -270,17 +271,15 @@ export class IoSocketController { delete Client.roomId; } } - /** - * - * @param Client - * @param messageUserPosition - */ - joinRoom(Client : ExSocketInterface, messageUserPosition: MessageUserPosition){ + + joinRoom(Client : ExSocketInterface, roomId: string){ //join user in room - Client.join(messageUserPosition.roomId); + Client.join(roomId); + Client.roomId = roomId; + Client.position = new Point(-1000, -1000); //check and create new world for a room - if(!this.Worlds.get(messageUserPosition.roomId)){ + if(!this.Worlds.get(roomId)){ let world = new World((user1: string, group: Group) => { this.connectedUser(user1, group); }, (user1: string, group: Group) => { @@ -290,11 +289,10 @@ export class IoSocketController { }, (groupUuid: string, lastUser: UserInterface) => { this.sendDeleteGroupEvent(groupUuid, lastUser); }); - this.Worlds.set(messageUserPosition.roomId, world); + this.Worlds.set(roomId, world); } - let world : World|undefined = this.Worlds.get(messageUserPosition.roomId); - + let world : World|undefined = this.Worlds.get(roomId); if(world) { // Dispatch groups position to newly connected user @@ -305,11 +303,9 @@ export class IoSocketController { }); }); //join world - world.join(Client, messageUserPosition); - this.Worlds.set(messageUserPosition.roomId, world); + world.join(Client, Client.position); + this.Worlds.set(roomId, world); } - - } /** @@ -373,13 +369,13 @@ export class IoSocketController { position: Client.position, name: Client.name, character: Client.character, - }; + } as MessageUserPositionInterface; let messageUserPosition = new MessageUserPosition(data); let world = this.Worlds.get(messageUserPosition.roomId); if (!world) { return; } - world.updatePosition(Client, messageUserPosition); + world.updatePosition(Client, messageUserPosition.position); this.Worlds.set(messageUserPosition.roomId, world); } diff --git a/back/src/Model/World.ts b/back/src/Model/World.ts index 19e8c194..39233271 100644 --- a/back/src/Model/World.ts +++ b/back/src/Model/World.ts @@ -48,10 +48,10 @@ export class World { return this.groups; } - public join(socket : Identificable, userPosition: MessageUserPosition): void { + public join(socket : Identificable, userPosition: PointInterface): void { this.users.set(socket.id, { id: socket.id, - position: userPosition.position + position: userPosition }); // Let's call update position to trigger the join / leave room this.updatePosition(socket, userPosition); @@ -69,14 +69,14 @@ export class World { this.users.delete(user.id); } - public updatePosition(socket : Identificable, userPosition: MessageUserPosition): void { + public updatePosition(socket : Identificable, userPosition: PointInterface): void { let user = this.users.get(socket.id); if(typeof user === 'undefined') { return; } - user.position.x = userPosition.position.x; - user.position.y = userPosition.position.y; + user.position.x = userPosition.x; + user.position.y = userPosition.y; if (typeof user.group === 'undefined') { // If the user is not part of a group: diff --git a/back/tests/WorldTest.ts b/back/tests/WorldTest.ts index 148e7383..47ca7a5c 100644 --- a/back/tests/WorldTest.ts +++ b/back/tests/WorldTest.ts @@ -17,39 +17,19 @@ describe("World", () => { let world = new World(connect, disconnect, 160, 160, () => {}, () => {}); - world.join({ id: "foo" }, new MessageUserPosition({ - userId: "foofoo", - roomId: 1, - position: new Point(100, 100) - })); + world.join({ id: "foo" }, new Point(100, 100)); - world.join({ id: "bar" }, new MessageUserPosition({ - userId: "barbar", - roomId: 1, - position: new Point(500, 100) - })); + world.join({ id: "bar" }, new Point(500, 100)); - world.updatePosition({ id: "bar" }, new MessageUserPosition({ - userId: "barbar", - roomId: 1, - position: new Point(261, 100) - })); + world.updatePosition({ id: "bar" }, new Point(261, 100)); expect(connectCalledNumber).toBe(0); - world.updatePosition({ id: "bar" }, new MessageUserPosition({ - userId: "barbar", - roomId: 1, - position: new Point(101, 100) - })); + world.updatePosition({ id: "bar" }, new Point(101, 100)); expect(connectCalledNumber).toBe(2); - world.updatePosition({ id: "bar" }, new MessageUserPosition({ - userId: "barbar", - roomId: 1, - position: new Point(102, 100) - })); + world.updatePosition({ id: "bar" }, new Point(102, 100)); expect(connectCalledNumber).toBe(2); }); @@ -64,35 +44,19 @@ describe("World", () => { let world = new World(connect, disconnect, 160, 160, () => {}, () => {}); - world.join({ id: "foo" }, new MessageUserPosition({ - userId: "foofoo", - roomId: 1, - position: new Point(100, 100) - })); + world.join({ id: "foo" }, new Point(100, 100)); - world.join({ id: "bar" }, new MessageUserPosition({ - userId: "barbar", - roomId: 1, - position: new Point(200, 100) - })); + world.join({ id: "bar" }, new Point(200, 100)); expect(connectCalled).toBe(true); connectCalled = false; // baz joins at the outer limit of the group - world.join({ id: "baz" }, new MessageUserPosition({ - userId: "bazbaz", - roomId: 1, - position: new Point(311, 100) - })); + world.join({ id: "baz" }, new Point(311, 100)); expect(connectCalled).toBe(false); - world.updatePosition({ id: "baz" }, new MessageUserPosition({ - userId: "bazbaz", - roomId: 1, - position: new Point(309, 100) - })); + world.updatePosition({ id: "baz" }, new Point(309, 100)); expect(connectCalled).toBe(true); }); @@ -109,34 +73,18 @@ describe("World", () => { let world = new World(connect, disconnect, 160, 160, () => {}, () => {}); - world.join({ id: "foo" }, new MessageUserPosition({ - userId: "foofoo", - roomId: 1, - position: new Point(100, 100) - })); + world.join({ id: "foo" }, new Point(100, 100)); - world.join({ id: "bar" }, new MessageUserPosition({ - userId: "barbar", - roomId: 1, - position: new Point(259, 100) - })); + world.join({ id: "bar" }, new Point(259, 100)); expect(connectCalled).toBe(true); expect(disconnectCallNumber).toBe(0); - world.updatePosition({ id: "bar" }, new MessageUserPosition({ - userId: "barbar", - roomId: 1, - position: new Point(100+160+160+1, 100) - })); + world.updatePosition({ id: "bar" }, new Point(100+160+160+1, 100)); expect(disconnectCallNumber).toBe(2); - world.updatePosition({ id: "bar" }, new MessageUserPosition({ - userId: "barbar", - roomId: 1, - position: new Point(262, 100) - })); + world.updatePosition({ id: "bar" }, new Point(262, 100)); expect(disconnectCallNumber).toBe(2); }); diff --git a/front/src/Connexion.ts b/front/src/Connexion.ts index 6b6049d2..52971752 100644 --- a/front/src/Connexion.ts +++ b/front/src/Connexion.ts @@ -150,6 +150,7 @@ export class Connexion implements ConnexionInterface { GameManager: GameManager; lastPositionShared: MessageUserPosition = null; + lastRoom: string|null = null; constructor(GameManager: GameManager) { this.GameManager = GameManager; @@ -185,12 +186,14 @@ export class Connexion implements ConnexionInterface { */ connectSocketServer(): Promise{ //if try to reconnect with last position - if(this.lastPositionShared) { + if(this.lastRoom) { //join the room this.joinARoom( - this.lastPositionShared.roomId, - this.lastPositionShared.character + this.lastRoom ); + } + + if(this.lastPositionShared) { //share your first position this.sharePosition( @@ -236,15 +239,9 @@ export class Connexion implements ConnexionInterface { * @param roomId * @param character */ - joinARoom(roomId: string, character: string): void { - let messageUserPosition = new MessageUserPosition( - this.userId, - roomId, - new Point(0, 0), - this.name, - character - ); - this.socket.emit(EventMessage.JOIN_ROOM, messageUserPosition); + joinARoom(roomId: string): void { + this.socket.emit(EventMessage.JOIN_ROOM, roomId); + this.lastRoom = roomId; } /** From 4d1c3517eca0bbc7d0ed921b5b6ca545c972c133 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Fri, 15 May 2020 23:40:05 +0200 Subject: [PATCH 07/13] When sharing user position, only position is sent now! --- back/src/Controller/IoSocketController.ts | 27 +++++------ front/src/Connexion.ts | 55 ++++++++++------------- front/src/Phaser/Game/GameManager.ts | 7 ++- front/src/Phaser/Game/GameScene.ts | 2 +- front/src/Phaser/Player/Player.ts | 4 +- 5 files changed, 40 insertions(+), 55 deletions(-) diff --git a/back/src/Controller/IoSocketController.ts b/back/src/Controller/IoSocketController.ts index 459fd5f2..2c83a8b5 100644 --- a/back/src/Controller/IoSocketController.ts +++ b/back/src/Controller/IoSocketController.ts @@ -11,7 +11,6 @@ import {World} from "../Model/World"; import {Group} from "_Model/Group"; import {UserInterface} from "_Model/UserInterface"; import {SetPlayerDetailsMessage} from "_Model/Websocket/SetPlayerDetailsMessage"; -import {MessageUserPositionInterface} from "../../../front/src/Connexion"; enum SockerIoEvent { CONNECTION = "connection", @@ -133,15 +132,15 @@ export class IoSocketController { socket.on(SockerIoEvent.USER_POSITION, (message: any) => { try { - let messageUserPosition = this.hydrateMessageReceive(message); - if (messageUserPosition instanceof Error) { - return socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: messageUserPosition.message}); + let position = this.hydratePositionReceive(message); + if (position instanceof Error) { + return socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: position.message}); } let Client = (socket as ExSocketInterface); // sending to all clients in room except sender - this.saveUserInformation(Client, messageUserPosition); + Client.position = position; //refresh position of all user in all rooms in real time this.refreshUserPosition(Client); @@ -345,15 +344,6 @@ export class IoSocketController { }); } - //permit to save user position in socket - saveUserInformation(socket: ExSocketInterface, message: MessageUserPosition) { - socket.position = message.position; - socket.roomId = message.roomId; - //socket.userId = message.userId; - socket.name = message.name; - socket.character = message.character; - } - refreshUserPosition(Client : ExSocketInterface) { //refresh position of all user in all rooms in real time let rooms = (this.Io.sockets.adapter.rooms as ExtRoomsInterface); @@ -369,7 +359,7 @@ export class IoSocketController { position: Client.position, name: Client.name, character: Client.character, - } as MessageUserPositionInterface; + }; let messageUserPosition = new MessageUserPosition(data); let world = this.Worlds.get(messageUserPosition.roomId); if (!world) { @@ -380,9 +370,12 @@ export class IoSocketController { } //Hydrate and manage error - hydrateMessageReceive(message: string): MessageUserPosition | Error { + hydratePositionReceive(message: any): Point | Error { try { - return new MessageUserPosition(message); + if (!message.x || !message.y || !message.direction) { + return new Error("invalid point message sent"); + } + return new Point(message.x, message.y, message.direction); } catch (err) { //TODO log error return new Error(err); diff --git a/front/src/Connexion.ts b/front/src/Connexion.ts index 52971752..da666b8b 100644 --- a/front/src/Connexion.ts +++ b/front/src/Connexion.ts @@ -149,7 +149,7 @@ export class Connexion implements ConnexionInterface { GameManager: GameManager; - lastPositionShared: MessageUserPosition = null; + lastPositionShared: PointInterface = null; lastRoom: string|null = null; constructor(GameManager: GameManager) { @@ -185,26 +185,6 @@ export class Connexion implements ConnexionInterface { * @param character */ connectSocketServer(): Promise{ - //if try to reconnect with last position - if(this.lastRoom) { - //join the room - this.joinARoom( - this.lastRoom - ); - } - - if(this.lastPositionShared) { - - //share your first position - this.sharePosition( - this.lastPositionShared ? this.lastPositionShared.position.x : 0, - this.lastPositionShared ? this.lastPositionShared.position.y : 0, - this.lastPositionShared.character, - this.lastPositionShared.roomId, - this.lastPositionShared.position.direction - ); - } - //listen event this.positionOfAllUser(); this.disconnectServer(); @@ -219,6 +199,25 @@ export class Connexion implements ConnexionInterface { } as SetPlayerDetailsMessage, (id: string) => { this.userId = id; }); + + //if try to reconnect with last position + if(this.lastRoom) { + //join the room + this.joinARoom( + this.lastRoom + ); + } + + if(this.lastPositionShared) { + + //share your first position + this.sharePosition( + this.lastPositionShared ? this.lastPositionShared.x : 0, + this.lastPositionShared ? this.lastPositionShared.y : 0, + this.lastPositionShared.direction + ); + } + resolve(this); }); } @@ -252,19 +251,13 @@ export class Connexion implements ConnexionInterface { * @param roomId * @param direction */ - sharePosition(x : number, y : number, character : string, roomId : string, direction : string = "none") : void{ + sharePosition(x : number, y : number, direction : string = "none") : void{ if(!this.socket){ return; } - let messageUserPosition = new MessageUserPosition( - this.userId, - roomId, - new Point(x, y, direction), - this.name, - character - ); - this.lastPositionShared = messageUserPosition; - this.socket.emit(EventMessage.USER_POSITION, messageUserPosition); + let point = new Point(x, y, direction); + this.lastPositionShared = point; + this.socket.emit(EventMessage.USER_POSITION, point); } /** diff --git a/front/src/Phaser/Game/GameManager.ts b/front/src/Phaser/Game/GameManager.ts index 1728d0d9..a84653cd 100644 --- a/front/src/Phaser/Game/GameManager.ts +++ b/front/src/Phaser/Game/GameManager.ts @@ -17,7 +17,6 @@ export interface HasMovedEvent { direction: string; x: number; y: number; - character: string; } export interface MapObject { @@ -71,8 +70,8 @@ export class GameManager { this.status = StatusGameManagerEnum.CURRENT_USER_CREATED; } - joinRoom(sceneKey : string, character: string){ - this.ConnexionInstance.joinARoom(sceneKey, character); + joinRoom(sceneKey : string){ + this.ConnexionInstance.joinARoom(sceneKey); } /** @@ -128,7 +127,7 @@ export class GameManager { } pushPlayerPosition(event: HasMovedEvent) { - this.ConnexionInstance.sharePosition(event.x, event.y, event.character, this.currentGameScene.scene.key, event.direction); + this.ConnexionInstance.sharePosition(event.x, event.y, event.direction); } loadMap(mapUrl: string, scene: ScenePlugin): string { diff --git a/front/src/Phaser/Game/GameScene.ts b/front/src/Phaser/Game/GameScene.ts index 1e4d1e6e..56c775ed 100644 --- a/front/src/Phaser/Game/GameScene.ts +++ b/front/src/Phaser/Game/GameScene.ts @@ -284,7 +284,7 @@ export class GameScene extends Phaser.Scene implements GameSceneInterface, Creat this.createCollisionObject(); //join room - this.GameManager.joinRoom(this.scene.key, this.CurrentPlayer.PlayerTexture); + this.GameManager.joinRoom(this.scene.key); //listen event to share position of user this.CurrentPlayer.on(hasMovedEventName, this.pushPlayerPosition.bind(this)) diff --git a/front/src/Phaser/Player/Player.ts b/front/src/Phaser/Player/Player.ts index dd33bd3c..73aad77e 100644 --- a/front/src/Phaser/Player/Player.ts +++ b/front/src/Phaser/Player/Player.ts @@ -81,12 +81,12 @@ export class Player extends PlayableCaracter implements CurrentGamerInterface, G } if (x !== 0 || y !== 0) { this.move(x, y); - this.emit(hasMovedEventName, {direction, x: this.x, y: this.y, character: this.PlayerTexture}); + this.emit(hasMovedEventName, {direction, x: this.x, y: this.y}); } else { if (this.previousMove !== PlayerAnimationNames.None) { direction = PlayerAnimationNames.None; this.stop(); - this.emit(hasMovedEventName, {direction, x: this.x, y: this.y, character: this.PlayerTexture}); + this.emit(hasMovedEventName, {direction, x: this.x, y: this.y}); } } From 3b6ace03fa3d7cbd2a31921193c26e0cc5900a0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Sat, 16 May 2020 00:19:27 +0200 Subject: [PATCH 08/13] Getting rid of roomId in Message class (this is not needed since all messages sent are for the room we are currently in) --- back/src/Controller/IoSocketController.ts | 4 ++-- back/src/Model/Websocket/ExtRooms.ts | 7 +++---- back/src/Model/Websocket/Message.ts | 6 ++---- back/tests/MessageTest.ts | 21 +++------------------ front/src/Connexion.ts | 10 +++------- 5 files changed, 13 insertions(+), 35 deletions(-) diff --git a/back/src/Controller/IoSocketController.ts b/back/src/Controller/IoSocketController.ts index 2c83a8b5..93dd8010 100644 --- a/back/src/Controller/IoSocketController.ts +++ b/back/src/Controller/IoSocketController.ts @@ -361,12 +361,12 @@ export class IoSocketController { character: Client.character, }; let messageUserPosition = new MessageUserPosition(data); - let world = this.Worlds.get(messageUserPosition.roomId); + let world = this.Worlds.get(Client.roomId); if (!world) { return; } world.updatePosition(Client, messageUserPosition.position); - this.Worlds.set(messageUserPosition.roomId, world); + this.Worlds.set(Client.roomId, world); } //Hydrate and manage error diff --git a/back/src/Model/Websocket/ExtRooms.ts b/back/src/Model/Websocket/ExtRooms.ts index 43395a28..b5493fdb 100644 --- a/back/src/Model/Websocket/ExtRooms.ts +++ b/back/src/Model/Websocket/ExtRooms.ts @@ -23,19 +23,18 @@ let RefreshUserPositionFunction = function(rooms : ExtRooms, Io: socketIO.Server } let data = { userId: socket.id, - roomId: socket.roomId, position: socket.position, name: socket.name, character: socket.character, }; let dataArray = []; - if (mapPositionUserByRoom.get(data.roomId)) { - dataArray = mapPositionUserByRoom.get(data.roomId); + if (mapPositionUserByRoom.get(socket.roomId)) { + dataArray = mapPositionUserByRoom.get(socket.roomId); dataArray.push(data); } else { dataArray = [data]; } - mapPositionUserByRoom.set(data.roomId, dataArray); + mapPositionUserByRoom.set(socket.roomId, dataArray); } rooms.userPositionMapByRoom = Array.from(mapPositionUserByRoom); }; diff --git a/back/src/Model/Websocket/Message.ts b/back/src/Model/Websocket/Message.ts index 70775d2b..2e928159 100644 --- a/back/src/Model/Websocket/Message.ts +++ b/back/src/Model/Websocket/Message.ts @@ -1,16 +1,14 @@ export class Message { userId: string; - roomId: string; name: string; character: string; constructor(data: any) { - if (!data.userId || !data.roomId) { + if (!data.userId) { console.error("Got invalid message", data); - throw Error("userId or roomId cannot be null"); + throw Error("userId cannot be null"); } this.userId = data.userId; - this.roomId = data.roomId; this.name = data.name; this.character = data.character; } diff --git a/back/tests/MessageTest.ts b/back/tests/MessageTest.ts index ab7d6476..971734c7 100644 --- a/back/tests/MessageTest.ts +++ b/back/tests/MessageTest.ts @@ -3,32 +3,17 @@ import {Message} from "../src/Model/Websocket/Message"; describe("Message Model", () => { it("should find userId and roomId", () => { - let message = {userId: "test1", roomId: "test2", name: "foo", character: "user"}; + let message = {userId: "test1", name: "foo", character: "user"}; let messageObject = new Message(message); expect(messageObject.userId).toBe("test1"); - expect(messageObject.roomId).toBe("test2"); expect(messageObject.name).toBe("foo"); expect(messageObject.character).toBe("user"); }) it("should find throw error when no userId", () => { - let message = {roomId: "test2"}; + let message = {}; expect(() => { let messageObject = new Message(message); - }).toThrow(new Error("userId or roomId cannot be null")); - }); - - it("should find throw error when no roomId", () => { - let message = {userId: "test1"}; - expect(() => { - let messageObject = new Message(message); - }).toThrow(new Error("userId or roomId cannot be null")); - }); - - it("should find throw error when no roomId", () => { - let message = {name: "foo"}; - expect(() => { - let messageObject = new Message(message); - }).toThrow(new Error("userId or roomId cannot be null")); + }).toThrow(new Error("userId cannot be null")); }); }) diff --git a/front/src/Connexion.ts b/front/src/Connexion.ts index da666b8b..f3e4f4ce 100644 --- a/front/src/Connexion.ts +++ b/front/src/Connexion.ts @@ -26,13 +26,11 @@ enum EventMessage{ class Message { userId: string; - roomId: string; name: string; character: string; - constructor(userId : string, roomId : string, name: string, character: string) { + constructor(userId : string, name: string, character: string) { this.userId = userId; - this.roomId = roomId; this.name = name; this.character = character; } @@ -61,7 +59,6 @@ class Point implements PointInterface{ export interface MessageUserPositionInterface { userId: string; - roomId: string; name: string; character: string; position: PointInterface; @@ -70,8 +67,8 @@ export interface MessageUserPositionInterface { class MessageUserPosition extends Message implements MessageUserPositionInterface{ position: PointInterface; - constructor(userId : string, roomId : string, point : Point, name: string, character: string) { - super(userId, roomId, name, character); + constructor(userId : string, point : Point, name: string, character: string) { + super(userId, name, character); this.position = point; } } @@ -91,7 +88,6 @@ class ListMessageUserPosition { data.forEach((userPosition: any) => { this.listUsersPosition.push(new MessageUserPosition( userPosition.userId, - userPosition.roomId, new Point( userPosition.position.x, userPosition.position.y, From b20357c1ee31fdb0d7db50b00ba4697d56c1eacf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Sat, 16 May 2020 15:44:40 +0200 Subject: [PATCH 09/13] Removing the Message class and merging it with MessageUserPosition (since it is only ever used it in MessageUserPosition) Taking advantage of the TypeScript Constructor Assignment too to reduce the amount of code! --- back/src/Controller/IoSocketController.ts | 17 ++-------------- back/src/Model/Websocket/Message.ts | 15 -------------- .../Model/Websocket/MessageUserPosition.ts | 20 +++---------------- 3 files changed, 5 insertions(+), 47 deletions(-) delete mode 100644 back/src/Model/Websocket/Message.ts diff --git a/back/src/Controller/IoSocketController.ts b/back/src/Controller/IoSocketController.ts index 93dd8010..9ea88991 100644 --- a/back/src/Controller/IoSocketController.ts +++ b/back/src/Controller/IoSocketController.ts @@ -115,13 +115,7 @@ export class IoSocketController { //add function to refresh position user in real time. this.refreshUserPosition(Client); - let messageUserPosition = new MessageUserPosition({ - userId: Client.id, - roomId: Client.roomId, - name: Client.name, - character: Client.character, - position: new Point(0, 0, 'none') - }); + let messageUserPosition = new MessageUserPosition(Client.id, Client.name, Client.character,new Point(0, 0, 'none')); socket.to(roomId).emit(SockerIoEvent.JOIN_ROOM, messageUserPosition); } catch (e) { @@ -353,14 +347,7 @@ export class IoSocketController { rooms.refreshUserPosition(rooms, this.Io); // update position in the world - let data = { - userId: Client.id, - roomId: Client.roomId, - position: Client.position, - name: Client.name, - character: Client.character, - }; - let messageUserPosition = new MessageUserPosition(data); + let messageUserPosition = new MessageUserPosition(Client.id, Client.name, Client.character, Client.position); let world = this.Worlds.get(Client.roomId); if (!world) { return; diff --git a/back/src/Model/Websocket/Message.ts b/back/src/Model/Websocket/Message.ts deleted file mode 100644 index 2e928159..00000000 --- a/back/src/Model/Websocket/Message.ts +++ /dev/null @@ -1,15 +0,0 @@ -export class Message { - userId: string; - name: string; - character: string; - - constructor(data: any) { - if (!data.userId) { - console.error("Got invalid message", data); - throw Error("userId cannot be null"); - } - this.userId = data.userId; - this.name = data.name; - this.character = data.character; - } -} diff --git a/back/src/Model/Websocket/MessageUserPosition.ts b/back/src/Model/Websocket/MessageUserPosition.ts index 4f27c26a..8a0c1d51 100644 --- a/back/src/Model/Websocket/MessageUserPosition.ts +++ b/back/src/Model/Websocket/MessageUserPosition.ts @@ -2,25 +2,11 @@ import {Message} from "./Message"; import {PointInterface} from "./PointInterface"; export class Point implements PointInterface{ - x: number; - y: number; - direction: string; - - constructor(x : number, y : number, direction : string = "none") { - if(x === null || y === null){ - throw Error("position x and y cannot be null"); - } - this.x = x; - this.y = y; - this.direction = direction; + constructor(public x : number, public y : number, public direction : string = "none") { } } -export class MessageUserPosition extends Message{ - position: PointInterface; - - constructor(message: any) { - super(message); - this.position = new Point(message.position.x, message.position.y, message.position.direction); +export class MessageUserPosition { + constructor(public userId: string, public name: string, public character: string, public position: PointInterface) { } } From 87707bc8140d43eb3c7a01aafcabc5f73246ba4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Sat, 16 May 2020 15:51:00 +0200 Subject: [PATCH 10/13] Removing broken import --- back/src/Model/Websocket/MessageUserPosition.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/back/src/Model/Websocket/MessageUserPosition.ts b/back/src/Model/Websocket/MessageUserPosition.ts index 8a0c1d51..613e47e6 100644 --- a/back/src/Model/Websocket/MessageUserPosition.ts +++ b/back/src/Model/Websocket/MessageUserPosition.ts @@ -1,4 +1,3 @@ -import {Message} from "./Message"; import {PointInterface} from "./PointInterface"; export class Point implements PointInterface{ From 57adc6b21c42cc372cf51096f87c4c542aff2c6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Sat, 16 May 2020 15:58:20 +0200 Subject: [PATCH 11/13] Cleaning up tests --- back/tests/MessageTest.ts | 19 ------------------- back/tests/WorldTest.ts | 16 +++++++--------- 2 files changed, 7 insertions(+), 28 deletions(-) delete mode 100644 back/tests/MessageTest.ts diff --git a/back/tests/MessageTest.ts b/back/tests/MessageTest.ts deleted file mode 100644 index 971734c7..00000000 --- a/back/tests/MessageTest.ts +++ /dev/null @@ -1,19 +0,0 @@ -import "jasmine"; -import {Message} from "../src/Model/Websocket/Message"; - -describe("Message Model", () => { - it("should find userId and roomId", () => { - let message = {userId: "test1", name: "foo", character: "user"}; - let messageObject = new Message(message); - expect(messageObject.userId).toBe("test1"); - expect(messageObject.name).toBe("foo"); - expect(messageObject.character).toBe("user"); - }) - - it("should find throw error when no userId", () => { - let message = {}; - expect(() => { - let messageObject = new Message(message); - }).toThrow(new Error("userId cannot be null")); - }); -}) diff --git a/back/tests/WorldTest.ts b/back/tests/WorldTest.ts index 47ca7a5c..aed9b838 100644 --- a/back/tests/WorldTest.ts +++ b/back/tests/WorldTest.ts @@ -1,17 +1,15 @@ import "jasmine"; -import {Message} from "../src/Model/Websocket/Message"; import {World, ConnectCallback, DisconnectCallback } from "../src/Model/World"; -import {MessageUserPosition, Point} from "../src/Model/Websocket/MessageUserPosition"; +import {Point} from "../src/Model/Websocket/MessageUserPosition"; import { Group } from "../src/Model/Group"; -import {Distance} from "../src/Model//Distance"; describe("World", () => { it("should connect user1 and user2", () => { let connectCalledNumber: number = 0; - let connect = (user: string, group: Group): void => { + let connect: ConnectCallback = (user: string, group: Group): void => { connectCalledNumber++; } - let disconnect = (user: string, group: Group): void => { + let disconnect: DisconnectCallback = (user: string, group: Group): void => { } @@ -35,10 +33,10 @@ describe("World", () => { it("should connect 3 users", () => { let connectCalled: boolean = false; - let connect = (user: string, group: Group): void => { + let connect: ConnectCallback = (user: string, group: Group): void => { connectCalled = true; } - let disconnect = (user: string, group: Group): void => { + let disconnect: DisconnectCallback = (user: string, group: Group): void => { } @@ -64,10 +62,10 @@ describe("World", () => { it("should disconnect user1 and user2", () => { let connectCalled: boolean = false; let disconnectCallNumber: number = 0; - let connect = (user: string, group: Group): void => { + let connect: ConnectCallback = (user: string, group: Group): void => { connectCalled = true; } - let disconnect = (user: string, group: Group): void => { + let disconnect: DisconnectCallback = (user: string, group: Group): void => { disconnectCallNumber++; } From 1bbd0866cb247cf474355b63787ca0f8c7f58207 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Sat, 16 May 2020 16:07:38 +0200 Subject: [PATCH 12/13] Code cleaning --- back/src/Controller/IoSocketController.ts | 10 ++++++---- back/tsconfig.json | 2 +- front/src/WebRtc/SimplePeer.ts | 17 +++-------------- 3 files changed, 10 insertions(+), 19 deletions(-) diff --git a/back/src/Controller/IoSocketController.ts b/back/src/Controller/IoSocketController.ts index 9ea88991..2c798797 100644 --- a/back/src/Controller/IoSocketController.ts +++ b/back/src/Controller/IoSocketController.ts @@ -94,10 +94,11 @@ export class IoSocketController { x: user x position on map y: user y position on map */ - socket.on(SockerIoEvent.JOIN_ROOM, (roomId: any) => { + socket.on(SockerIoEvent.JOIN_ROOM, (roomId: any): void => { try { if (typeof(roomId) !== 'string') { - return socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: 'Expected roomId as a string.'}) + socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: 'Expected roomId as a string.'}); + return; } let Client = (socket as ExSocketInterface); @@ -124,11 +125,12 @@ export class IoSocketController { } }); - socket.on(SockerIoEvent.USER_POSITION, (message: any) => { + socket.on(SockerIoEvent.USER_POSITION, (message: any): void => { try { let position = this.hydratePositionReceive(message); if (position instanceof Error) { - return socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: position.message}); + socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: position.message}); + return; } let Client = (socket as ExSocketInterface); diff --git a/back/tsconfig.json b/back/tsconfig.json index 7686fb67..03f8c9d8 100644 --- a/back/tsconfig.json +++ b/back/tsconfig.json @@ -36,7 +36,7 @@ /* Additional Checks */ // "noUnusedLocals": true, /* Report errors on unused locals. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */ diff --git a/front/src/WebRtc/SimplePeer.ts b/front/src/WebRtc/SimplePeer.ts index 54b7e0ed..595e83b2 100644 --- a/front/src/WebRtc/SimplePeer.ts +++ b/front/src/WebRtc/SimplePeer.ts @@ -49,18 +49,12 @@ export class SimplePeer implements SimplePeerInterface{ }); //receive signal by gemer - this.Connexion.disconnectMessage((message: any) => { - let data = message; + this.Connexion.disconnectMessage((data: any) => { this.closeConnexion(data.userId); }); } - /** - * - * @param message - */ - private receiveWebrtcStart(message: any) { - let data = message; + private receiveWebrtcStart(data: any) { this.WebRtcRoomId = data.roomId; this.Users = data.clients; @@ -193,12 +187,7 @@ export class SimplePeer implements SimplePeerInterface{ } } - /** - * - * @param message - */ - private receiveWebrtcSignal(message: any) { - let data = message; + private receiveWebrtcSignal(data: any) { try { //if offer type, create peer connexion if(data.signal.type === "offer"){ From 2628373b56912ac186cdfe4861751fc9e9d290d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20N=C3=A9grier?= Date: Sat, 16 May 2020 16:11:58 +0200 Subject: [PATCH 13/13] Stricter compiler --- back/tsconfig.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/back/tsconfig.json b/back/tsconfig.json index 03f8c9d8..51858b84 100644 --- a/back/tsconfig.json +++ b/back/tsconfig.json @@ -36,8 +36,8 @@ /* Additional Checks */ // "noUnusedLocals": true, /* Report errors on unused locals. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */ - "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */ "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */