Refactoring connection to pass room info on connect
This commit is contained in:
parent
0b78eb6277
commit
f542b117a8
@ -24,7 +24,6 @@ import {
|
|||||||
ItemEventMessage,
|
ItemEventMessage,
|
||||||
ViewportMessage,
|
ViewportMessage,
|
||||||
ClientToServerMessage,
|
ClientToServerMessage,
|
||||||
JoinRoomMessage,
|
|
||||||
ErrorMessage,
|
ErrorMessage,
|
||||||
RoomJoinedMessage,
|
RoomJoinedMessage,
|
||||||
ItemStateMessage,
|
ItemStateMessage,
|
||||||
@ -33,17 +32,17 @@ import {
|
|||||||
SilentMessage,
|
SilentMessage,
|
||||||
WebRtcSignalToClientMessage,
|
WebRtcSignalToClientMessage,
|
||||||
WebRtcSignalToServerMessage,
|
WebRtcSignalToServerMessage,
|
||||||
WebRtcStartMessage,
|
WebRtcStartMessage,
|
||||||
WebRtcDisconnectMessage,
|
WebRtcDisconnectMessage,
|
||||||
PlayGlobalMessage,
|
PlayGlobalMessage,
|
||||||
} from "../Messages/generated/messages_pb";
|
} from "../Messages/generated/messages_pb";
|
||||||
import {UserMovesMessage} from "../Messages/generated/messages_pb";
|
import {UserMovesMessage} from "../Messages/generated/messages_pb";
|
||||||
import Direction = PositionMessage.Direction;
|
import Direction = PositionMessage.Direction;
|
||||||
import {ProtobufUtils} from "../Model/Websocket/ProtobufUtils";
|
import {ProtobufUtils} from "../Model/Websocket/ProtobufUtils";
|
||||||
import {HttpRequest, TemplatedApp} from "uWebSockets.js"
|
import {TemplatedApp} from "uWebSockets.js"
|
||||||
import {parse} from "query-string";
|
import {parse} from "query-string";
|
||||||
import {cpuTracker} from "../Services/CpuTracker";
|
import {cpuTracker} from "../Services/CpuTracker";
|
||||||
import {adminApi} from "../Services/AdminApi";
|
import {ViewportInterface} from "../Model/Websocket/ViewportMessage";
|
||||||
|
|
||||||
function emitInBatch(socket: ExSocketInterface, payload: SubMessage): void {
|
function emitInBatch(socket: ExSocketInterface, payload: SubMessage): void {
|
||||||
socket.batchedMessages.addPayload(payload);
|
socket.batchedMessages.addPayload(payload);
|
||||||
@ -95,7 +94,7 @@ export class IoSocketController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async getUserUuidFromToken(token: unknown): Promise<string> {
|
private async getUserUuidFromToken(token: unknown): Promise<string> {
|
||||||
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
throw new Error('An authentication error happened, a user tried to connect without a token.');
|
throw new Error('An authentication error happened, a user tried to connect without a token.');
|
||||||
}
|
}
|
||||||
@ -137,8 +136,7 @@ export class IoSocketController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ioConnection() {
|
ioConnection() {
|
||||||
this.app.ws('/room', {
|
this.app.ws('/room/*', {
|
||||||
|
|
||||||
/* Options */
|
/* Options */
|
||||||
//compression: uWS.SHARED_COMPRESSOR,
|
//compression: uWS.SHARED_COMPRESSOR,
|
||||||
maxPayloadLength: 16 * 1024 * 1024,
|
maxPayloadLength: 16 * 1024 * 1024,
|
||||||
@ -147,7 +145,6 @@ export class IoSocketController {
|
|||||||
upgrade: (res, req, context) => {
|
upgrade: (res, req, context) => {
|
||||||
//console.log('An Http connection wants to become WebSocket, URL: ' + req.getUrl() + '!');
|
//console.log('An Http connection wants to become WebSocket, URL: ' + req.getUrl() + '!');
|
||||||
(async () => {
|
(async () => {
|
||||||
|
|
||||||
/* Keep track of abortions */
|
/* Keep track of abortions */
|
||||||
const upgradeAborted = {aborted: false};
|
const upgradeAborted = {aborted: false};
|
||||||
|
|
||||||
@ -159,19 +156,32 @@ export class IoSocketController {
|
|||||||
try {
|
try {
|
||||||
const query = parse(req.getQuery());
|
const query = parse(req.getQuery());
|
||||||
|
|
||||||
const moderated = query.moderated || false;
|
const roomId = req.getUrl().substr(6);
|
||||||
const roomId = query.roomId || null;
|
|
||||||
const token = query.token;
|
const token = query.token;
|
||||||
|
const x = Number(query.x);
|
||||||
|
const y = Number(query.y);
|
||||||
|
const top = Number(query.top);
|
||||||
|
const bottom = Number(query.bottom);
|
||||||
|
const left = Number(query.left);
|
||||||
|
const right = Number(query.right);
|
||||||
|
const name = query.name;
|
||||||
|
if (typeof name !== 'string') {
|
||||||
|
throw new Error('Expecting name');
|
||||||
|
}
|
||||||
|
if (name === '') {
|
||||||
|
throw new Error('No empty name');
|
||||||
|
}
|
||||||
|
let characterLayers = query.characterLayers;
|
||||||
|
if (characterLayers === null) {
|
||||||
|
throw new Error('Expecting skin');
|
||||||
|
}
|
||||||
|
if (typeof characterLayers === 'string') {
|
||||||
|
characterLayers = [ characterLayers ];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
const userUuid = await this.getUserUuidFromToken(token);
|
const userUuid = await this.getUserUuidFromToken(token);
|
||||||
|
|
||||||
this.handleJoinRoom(client, message.getJoinroommessage() as JoinRoomMessage);
|
|
||||||
|
|
||||||
const isGranted = await adminApi.memberIsGrantedAccessToRoom(client.userUuid, roomId);
|
|
||||||
if (!isGranted) {
|
|
||||||
throw Error('Client cannot acces this ressource.');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (upgradeAborted.aborted) {
|
if (upgradeAborted.aborted) {
|
||||||
console.log("Ouch! Client disconnected before we could upgrade it!");
|
console.log("Ouch! Client disconnected before we could upgrade it!");
|
||||||
@ -184,7 +194,22 @@ export class IoSocketController {
|
|||||||
// Data passed here is accessible on the "websocket" socket object.
|
// Data passed here is accessible on the "websocket" socket object.
|
||||||
url: req.getUrl(),
|
url: req.getUrl(),
|
||||||
token,
|
token,
|
||||||
userUuid
|
userUuid,
|
||||||
|
roomId,
|
||||||
|
name,
|
||||||
|
characterLayers,
|
||||||
|
position: {
|
||||||
|
x: x,
|
||||||
|
y: y,
|
||||||
|
direction: 'down',
|
||||||
|
moving: false
|
||||||
|
} as PointInterface,
|
||||||
|
viewport: {
|
||||||
|
top,
|
||||||
|
right,
|
||||||
|
bottom,
|
||||||
|
left
|
||||||
|
}
|
||||||
},
|
},
|
||||||
/* Spell these correctly */
|
/* Spell these correctly */
|
||||||
req.getHeader('sec-websocket-key'),
|
req.getHeader('sec-websocket-key'),
|
||||||
@ -217,12 +242,34 @@ export class IoSocketController {
|
|||||||
emitInBatch(client, payload);
|
emitInBatch(client, payload);
|
||||||
}
|
}
|
||||||
client.disconnecting = false;
|
client.disconnecting = false;
|
||||||
|
|
||||||
|
client.name = ws.name;
|
||||||
|
client.characterLayers = ws.characterLayers;
|
||||||
|
client.roomId = ws.roomId;
|
||||||
|
|
||||||
this.sockets.set(client.userId, client);
|
this.sockets.set(client.userId, client);
|
||||||
|
|
||||||
// Let's log server load when a user joins
|
// Let's log server load when a user joins
|
||||||
this.nbClientsGauge.inc();
|
this.nbClientsGauge.inc();
|
||||||
console.log(new Date().toISOString() + ' A user joined (', this.sockets.size, ' connected users)');
|
console.log(new Date().toISOString() + ' A user joined (', this.sockets.size, ' connected users)');
|
||||||
|
|
||||||
|
// Let's join the room
|
||||||
|
this.handleJoinRoom(client, client.roomId, client.position, client.viewport, client.name, client.characterLayers);
|
||||||
|
|
||||||
|
/*const isGranted = await adminApi.memberIsGrantedAccessToRoom(client.userUuid, roomId);
|
||||||
|
if (!isGranted) {
|
||||||
|
throw Error('Client cannot acces this ressource.');
|
||||||
|
}*/
|
||||||
|
|
||||||
|
const setUserIdMessage = new SetUserIdMessage();
|
||||||
|
setUserIdMessage.setUserid(client.userId);
|
||||||
|
|
||||||
|
const serverToClientMessage = new ServerToClientMessage();
|
||||||
|
serverToClientMessage.setSetuseridmessage(setUserIdMessage);
|
||||||
|
|
||||||
|
if (!client.disconnecting) {
|
||||||
|
client.send(serverToClientMessage.serializeBinary().buffer, true);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
message: (ws, arrayBuffer, isBinary): void => {
|
message: (ws, arrayBuffer, isBinary): void => {
|
||||||
const client = ws as ExSocketInterface;
|
const client = ws as ExSocketInterface;
|
||||||
@ -305,22 +352,12 @@ export class IoSocketController {
|
|||||||
console.warn(message);
|
console.warn(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async handleJoinRoom(client: ExSocketInterface, message: JoinRoomMessage): Promise<void> {
|
private async handleJoinRoom(client: ExSocketInterface, roomId: string, position: PointInterface, viewport: ViewportInterface, name: string, characterLayers: string[]): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const roomId = message.getRoomid();
|
|
||||||
|
|
||||||
if (client.roomId === roomId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
//leave previous room
|
|
||||||
//this.leaveRoom(Client); // Useless now, there is only one room per connection
|
|
||||||
|
|
||||||
//join new previous room
|
//join new previous room
|
||||||
const gameRoom = await this.joinRoom(client, roomId, ProtobufUtils.toPointInterface(message.getPosition() as PositionMessage));
|
const gameRoom = await this.joinRoom(client, roomId, position);
|
||||||
|
|
||||||
const things = gameRoom.setViewport(client, (message.getViewport() as ViewportMessage).toObject());
|
const things = gameRoom.setViewport(client, viewport);
|
||||||
|
|
||||||
const roomJoinedMessage = new RoomJoinedMessage();
|
const roomJoinedMessage = new RoomJoinedMessage();
|
||||||
|
|
||||||
@ -448,6 +485,7 @@ export class IoSocketController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Useless now, will be useful again if we allow editing details in game
|
||||||
private handleSetPlayerDetails(client: ExSocketInterface, playerDetailsMessage: SetPlayerDetailsMessage) {
|
private handleSetPlayerDetails(client: ExSocketInterface, playerDetailsMessage: SetPlayerDetailsMessage) {
|
||||||
const playerDetails = {
|
const playerDetails = {
|
||||||
name: playerDetailsMessage.getName(),
|
name: playerDetailsMessage.getName(),
|
||||||
@ -461,16 +499,6 @@ export class IoSocketController {
|
|||||||
client.name = playerDetails.name;
|
client.name = playerDetails.name;
|
||||||
client.characterLayers = playerDetails.characterLayers;
|
client.characterLayers = playerDetails.characterLayers;
|
||||||
|
|
||||||
|
|
||||||
const setUserIdMessage = new SetUserIdMessage();
|
|
||||||
setUserIdMessage.setUserid(client.userId);
|
|
||||||
|
|
||||||
const serverToClientMessage = new ServerToClientMessage();
|
|
||||||
serverToClientMessage.setSetuseridmessage(setUserIdMessage);
|
|
||||||
|
|
||||||
if (!client.disconnecting) {
|
|
||||||
client.send(serverToClientMessage.serializeBinary().buffer, true);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleSilentMessage(client: ExSocketInterface, silentMessage: SilentMessage) {
|
private handleSilentMessage(client: ExSocketInterface, silentMessage: SilentMessage) {
|
||||||
@ -585,7 +613,7 @@ export class IoSocketController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private joinRoom(client : ExSocketInterface, roomId: string, position: PointInterface): GameRoom {
|
private joinRoom(client : ExSocketInterface, roomId: string, position: PointInterface): GameRoom {
|
||||||
|
|
||||||
//join user in room
|
//join user in room
|
||||||
this.nbClientsPerRoomGauge.inc({ room: roomId });
|
this.nbClientsPerRoomGauge.inc({ room: roomId });
|
||||||
client.roomId = roomId;
|
client.roomId = roomId;
|
||||||
|
@ -27,7 +27,7 @@
|
|||||||
"google-protobuf": "^3.13.0",
|
"google-protobuf": "^3.13.0",
|
||||||
"phaser": "^3.22.0",
|
"phaser": "^3.22.0",
|
||||||
"queue-typescript": "^1.0.1",
|
"queue-typescript": "^1.0.1",
|
||||||
"quill": "1.3.6",
|
"quill": "^1.3.7",
|
||||||
"simple-peer": "^9.6.2",
|
"simple-peer": "^9.6.2",
|
||||||
"socket.io-client": "^2.3.0",
|
"socket.io-client": "^2.3.0",
|
||||||
"webpack-require-http": "^0.4.3"
|
"webpack-require-http": "^0.4.3"
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
import Axios from "axios";
|
import Axios from "axios";
|
||||||
import {API_URL} from "../Enum/EnvironmentVariable";
|
import {API_URL} from "../Enum/EnvironmentVariable";
|
||||||
import {RoomConnection} from "./RoomConnection";
|
import {RoomConnection} from "./RoomConnection";
|
||||||
|
import {PositionInterface, ViewportInterface} from "./ConnexionModels";
|
||||||
|
|
||||||
interface LoginApiData {
|
interface LoginApiData {
|
||||||
authToken: string
|
authToken: string
|
||||||
@ -35,9 +36,9 @@ class ConnectionManager {
|
|||||||
this.authToken = 'test';
|
this.authToken = 'test';
|
||||||
}
|
}
|
||||||
|
|
||||||
public connectToRoomSocket(): Promise<RoomConnection> {
|
public connectToRoomSocket(roomId: string, name: string, characterLayers: string[], position: PositionInterface, viewport: ViewportInterface): Promise<RoomConnection> {
|
||||||
return new Promise<RoomConnection>((resolve, reject) => {
|
return new Promise<RoomConnection>((resolve, reject) => {
|
||||||
const connection = new RoomConnection(this.authToken as string);
|
const connection = new RoomConnection(this.authToken as string, roomId, name, characterLayers, position, viewport);
|
||||||
connection.onConnectError((error: object) => {
|
connection.onConnectError((error: object) => {
|
||||||
console.log('An error occurred while connecting to socket server. Retrying');
|
console.log('An error occurred while connecting to socket server. Retrying');
|
||||||
reject(error);
|
reject(error);
|
||||||
@ -50,7 +51,7 @@ class ConnectionManager {
|
|||||||
return new Promise<RoomConnection>((resolve, reject) => {
|
return new Promise<RoomConnection>((resolve, reject) => {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
//todo: allow a way to break recurrsion?
|
//todo: allow a way to break recurrsion?
|
||||||
this.connectToRoomSocket().then((connection) => resolve(connection));
|
this.connectToRoomSocket(roomId, name, characterLayers, position, viewport).then((connection) => resolve(connection));
|
||||||
}, 4000 + Math.floor(Math.random() * 2000) );
|
}, 4000 + Math.floor(Math.random() * 2000) );
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -6,6 +6,7 @@ export enum EventMessage{
|
|||||||
WEBRTC_SIGNAL = "webrtc-signal",
|
WEBRTC_SIGNAL = "webrtc-signal",
|
||||||
WEBRTC_SCREEN_SHARING_SIGNAL = "webrtc-screen-sharing-signal",
|
WEBRTC_SCREEN_SHARING_SIGNAL = "webrtc-screen-sharing-signal",
|
||||||
WEBRTC_START = "webrtc-start",
|
WEBRTC_START = "webrtc-start",
|
||||||
|
START_ROOM = "start-room", // From server to client: list of all room users/groups/items
|
||||||
JOIN_ROOM = "join-room", // bi-directional
|
JOIN_ROOM = "join-room", // bi-directional
|
||||||
USER_POSITION = "user-position", // From client to server
|
USER_POSITION = "user-position", // From client to server
|
||||||
USER_MOVED = "user-moved", // From server to client
|
USER_MOVED = "user-moved", // From server to client
|
||||||
|
@ -6,7 +6,7 @@ import {
|
|||||||
GroupDeleteMessage,
|
GroupDeleteMessage,
|
||||||
GroupUpdateMessage,
|
GroupUpdateMessage,
|
||||||
ItemEventMessage,
|
ItemEventMessage,
|
||||||
JoinRoomMessage, PlayGlobalMessage,
|
PlayGlobalMessage,
|
||||||
PositionMessage,
|
PositionMessage,
|
||||||
RoomJoinedMessage,
|
RoomJoinedMessage,
|
||||||
ServerToClientMessage,
|
ServerToClientMessage,
|
||||||
@ -30,7 +30,7 @@ import {ProtobufClientUtils} from "../Network/ProtobufClientUtils";
|
|||||||
import {
|
import {
|
||||||
EventMessage,
|
EventMessage,
|
||||||
GroupCreatedUpdatedMessageInterface, ItemEventMessageInterface,
|
GroupCreatedUpdatedMessageInterface, ItemEventMessageInterface,
|
||||||
MessageUserJoined, PlayGlobalMessageInterface,
|
MessageUserJoined, PlayGlobalMessageInterface, PositionInterface,
|
||||||
RoomJoinedMessageInterface,
|
RoomJoinedMessageInterface,
|
||||||
ViewportInterface, WebRtcDisconnectMessageInterface,
|
ViewportInterface, WebRtcDisconnectMessageInterface,
|
||||||
WebRtcSignalReceivedMessageInterface,
|
WebRtcSignalReceivedMessageInterface,
|
||||||
@ -48,9 +48,25 @@ export class RoomConnection implements RoomConnection {
|
|||||||
RoomConnection.websocketFactory = websocketFactory;
|
RoomConnection.websocketFactory = websocketFactory;
|
||||||
}
|
}
|
||||||
|
|
||||||
public constructor(token: string) {
|
/**
|
||||||
|
*
|
||||||
|
* @param token A JWT token containing the UUID of the user
|
||||||
|
* @param roomId The ID of the room in the form "_/[instance]/[map_url]" or "@/[org]/[event]/[map]"
|
||||||
|
*/
|
||||||
|
public constructor(token: string, roomId: string, name: string, characterLayers: string[], position: PositionInterface, viewport: ViewportInterface) {
|
||||||
let url = API_URL.replace('http://', 'ws://').replace('https://', 'wss://');
|
let url = API_URL.replace('http://', 'ws://').replace('https://', 'wss://');
|
||||||
url += '?token='+token;
|
url += '/room/'+roomId
|
||||||
|
url += '?token='+encodeURIComponent(token);
|
||||||
|
url += '&name='+encodeURIComponent(name);
|
||||||
|
for (let layer of characterLayers) {
|
||||||
|
url += '&characterLayers='+encodeURIComponent(layer);
|
||||||
|
}
|
||||||
|
url += '&x='+Math.floor(position.x);
|
||||||
|
url += '&y='+Math.floor(position.y);
|
||||||
|
url += '&top='+Math.floor(viewport.top);
|
||||||
|
url += '&bottom='+Math.floor(viewport.bottom);
|
||||||
|
url += '&left='+Math.floor(viewport.left);
|
||||||
|
url += '&right='+Math.floor(viewport.right);
|
||||||
|
|
||||||
if (RoomConnection.websocketFactory) {
|
if (RoomConnection.websocketFactory) {
|
||||||
this.socket = RoomConnection.websocketFactory(url);
|
this.socket = RoomConnection.websocketFactory(url);
|
||||||
@ -106,11 +122,11 @@ export class RoomConnection implements RoomConnection {
|
|||||||
items[item.getItemid()] = JSON.parse(item.getStatejson());
|
items[item.getItemid()] = JSON.parse(item.getStatejson());
|
||||||
}
|
}
|
||||||
|
|
||||||
this.resolveJoinRoom({
|
this.dispatch(EventMessage.START_ROOM, {
|
||||||
users,
|
users,
|
||||||
groups,
|
groups,
|
||||||
items
|
items
|
||||||
})
|
});
|
||||||
} else if (message.hasSetuseridmessage()) {
|
} else if (message.hasSetuseridmessage()) {
|
||||||
this.userId = (message.getSetuseridmessage() as SetUserIdMessage).getUserid();
|
this.userId = (message.getSetuseridmessage() as SetUserIdMessage).getUserid();
|
||||||
} else if (message.hasErrormessage()) {
|
} else if (message.hasErrormessage()) {
|
||||||
@ -159,29 +175,6 @@ export class RoomConnection implements RoomConnection {
|
|||||||
this.socket?.close();
|
this.socket?.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveJoinRoom!: (value?: (RoomJoinedMessageInterface | PromiseLike<RoomJoinedMessageInterface> | undefined)) => void;
|
|
||||||
|
|
||||||
public joinARoom(roomId: string, startX: number, startY: number, direction: string, moving: boolean, viewport: ViewportInterface): Promise<RoomJoinedMessageInterface> {
|
|
||||||
const promise = new Promise<RoomJoinedMessageInterface>((resolve, reject) => {
|
|
||||||
this.resolveJoinRoom = resolve;
|
|
||||||
|
|
||||||
const positionMessage = this.toPositionMessage(startX, startY, direction, moving);
|
|
||||||
const viewportMessage = this.toViewportMessage(viewport);
|
|
||||||
|
|
||||||
const joinRoomMessage = new JoinRoomMessage();
|
|
||||||
joinRoomMessage.setRoomid(roomId);
|
|
||||||
joinRoomMessage.setPosition(positionMessage);
|
|
||||||
joinRoomMessage.setViewport(viewportMessage);
|
|
||||||
|
|
||||||
//console.log('Sending position ', positionMessage.getX(), positionMessage.getY());
|
|
||||||
const clientToServerMessage = new ClientToServerMessage();
|
|
||||||
clientToServerMessage.setJoinroommessage(joinRoomMessage);
|
|
||||||
|
|
||||||
this.socket.send(clientToServerMessage.serializeBinary().buffer);
|
|
||||||
})
|
|
||||||
return promise;
|
|
||||||
}
|
|
||||||
|
|
||||||
private toPositionMessage(x : number, y : number, direction : string, moving: boolean): PositionMessage {
|
private toPositionMessage(x : number, y : number, direction : string, moving: boolean): PositionMessage {
|
||||||
const positionMessage = new PositionMessage();
|
const positionMessage = new PositionMessage();
|
||||||
positionMessage.setX(Math.floor(x));
|
positionMessage.setX(Math.floor(x));
|
||||||
@ -337,6 +330,13 @@ export class RoomConnection implements RoomConnection {
|
|||||||
this.socket.addEventListener('open', callback)
|
this.socket.addEventListener('open', callback)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Triggered when we receive all the details of a room (users, groups, ...)
|
||||||
|
*/
|
||||||
|
public onStartRoom(callback: (event: RoomJoinedMessageInterface) => void): void {
|
||||||
|
this.onMessage(EventMessage.START_ROOM, callback);
|
||||||
|
}
|
||||||
|
|
||||||
public sendWebrtcSignal(signal: unknown, receiverId: number) {
|
public sendWebrtcSignal(signal: unknown, receiverId: number) {
|
||||||
const webRtcSignal = new WebRtcSignalToServerMessage();
|
const webRtcSignal = new WebRtcSignalToServerMessage();
|
||||||
webRtcSignal.setReceiverid(receiverId);
|
webRtcSignal.setReceiverid(receiverId);
|
||||||
|
@ -107,7 +107,6 @@ export class GameScene extends Phaser.Scene implements CenterListener {
|
|||||||
private simplePeer!: SimplePeer;
|
private simplePeer!: SimplePeer;
|
||||||
private GlobalMessageManager!: GlobalMessageManager;
|
private GlobalMessageManager!: GlobalMessageManager;
|
||||||
private ConsoleGlobalMessageManager!: ConsoleGlobalMessageManager;
|
private ConsoleGlobalMessageManager!: ConsoleGlobalMessageManager;
|
||||||
private connectionPromise!: Promise<RoomConnection>
|
|
||||||
private connectionAnswerPromise: Promise<RoomJoinedMessageInterface>;
|
private connectionAnswerPromise: Promise<RoomJoinedMessageInterface>;
|
||||||
private connectionAnswerPromiseResolve!: (value?: RoomJoinedMessageInterface | PromiseLike<RoomJoinedMessageInterface>) => void;
|
private connectionAnswerPromiseResolve!: (value?: RoomJoinedMessageInterface | PromiseLike<RoomJoinedMessageInterface>) => void;
|
||||||
// A promise that will resolve when the "create" method is called (signaling loading is ended)
|
// A promise that will resolve when the "create" method is called (signaling loading is ended)
|
||||||
@ -206,106 +205,6 @@ export class GameScene extends Phaser.Scene implements CenterListener {
|
|||||||
loadAllLayers(this.load);
|
loadAllLayers(this.load);
|
||||||
|
|
||||||
this.load.bitmapFont('main_font', 'resources/fonts/arcade.png', 'resources/fonts/arcade.xml');
|
this.load.bitmapFont('main_font', 'resources/fonts/arcade.png', 'resources/fonts/arcade.xml');
|
||||||
|
|
||||||
this.connectionPromise = connectionManager.connectToRoomSocket().then((connection : RoomConnection) => {
|
|
||||||
this.connection = connection;
|
|
||||||
|
|
||||||
this.connection.emitPlayerDetailsMessage(gameManager.getPlayerName(), gameManager.getCharacterSelected())
|
|
||||||
|
|
||||||
connection.onUserJoins((message: MessageUserJoined) => {
|
|
||||||
const userMessage: AddPlayerInterface = {
|
|
||||||
userId: message.userId,
|
|
||||||
characterLayers: message.characterLayers,
|
|
||||||
name: message.name,
|
|
||||||
position: message.position
|
|
||||||
}
|
|
||||||
this.addPlayer(userMessage);
|
|
||||||
});
|
|
||||||
|
|
||||||
connection.onUserMoved((message: UserMovedMessage) => {
|
|
||||||
const position = message.getPosition();
|
|
||||||
if (position === undefined) {
|
|
||||||
throw new Error('Position missing from UserMovedMessage');
|
|
||||||
}
|
|
||||||
//console.log('Received position ', position.getX(), position.getY(), "from user", message.getUserid());
|
|
||||||
|
|
||||||
const messageUserMoved: MessageUserMovedInterface = {
|
|
||||||
userId: message.getUserid(),
|
|
||||||
position: ProtobufClientUtils.toPointInterface(position)
|
|
||||||
}
|
|
||||||
|
|
||||||
this.updatePlayerPosition(messageUserMoved);
|
|
||||||
});
|
|
||||||
|
|
||||||
connection.onUserLeft((userId: number) => {
|
|
||||||
this.removePlayer(userId);
|
|
||||||
});
|
|
||||||
|
|
||||||
connection.onGroupUpdatedOrCreated((groupPositionMessage: GroupCreatedUpdatedMessageInterface) => {
|
|
||||||
this.shareGroupPosition(groupPositionMessage);
|
|
||||||
})
|
|
||||||
|
|
||||||
connection.onGroupDeleted((groupId: number) => {
|
|
||||||
try {
|
|
||||||
this.deleteGroup(groupId);
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
connection.onServerDisconnected(() => {
|
|
||||||
console.log('Player disconnected from server. Reloading scene.');
|
|
||||||
|
|
||||||
this.simplePeer.closeAllConnections();
|
|
||||||
this.simplePeer.unregister();
|
|
||||||
|
|
||||||
const key = 'somekey'+Math.round(Math.random()*10000);
|
|
||||||
const game : Phaser.Scene = GameScene.createFromUrl(this.MapUrlFile, this.instance, key);
|
|
||||||
this.scene.add(key, game, true,
|
|
||||||
{
|
|
||||||
initPosition: {
|
|
||||||
x: this.CurrentPlayer.x,
|
|
||||||
y: this.CurrentPlayer.y
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
this.scene.stop(this.scene.key);
|
|
||||||
this.scene.remove(this.scene.key);
|
|
||||||
window.removeEventListener('resize', this.onResizeCallback);
|
|
||||||
})
|
|
||||||
|
|
||||||
connection.onActionableEvent((message => {
|
|
||||||
const item = this.actionableItems.get(message.itemId);
|
|
||||||
if (item === undefined) {
|
|
||||||
console.warn('Received an event about object "'+message.itemId+'" but cannot find this item on the map.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
item.fire(message.event, message.state, message.parameters);
|
|
||||||
}));
|
|
||||||
|
|
||||||
// When connection is performed, let's connect SimplePeer
|
|
||||||
this.simplePeer = new SimplePeer(this.connection);
|
|
||||||
this.GlobalMessageManager = new GlobalMessageManager(this.connection);
|
|
||||||
|
|
||||||
const self = this;
|
|
||||||
this.simplePeer.registerPeerConnectionListener({
|
|
||||||
onConnect(user: UserSimplePeerInterface) {
|
|
||||||
self.presentationModeSprite.setVisible(true);
|
|
||||||
self.chatModeSprite.setVisible(true);
|
|
||||||
},
|
|
||||||
onDisconnect(userId: number) {
|
|
||||||
if (self.simplePeer.getNbConnections() === 0) {
|
|
||||||
self.presentationModeSprite.setVisible(false);
|
|
||||||
self.chatModeSprite.setVisible(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
this.scene.wake();
|
|
||||||
this.scene.sleep(ReconnectingSceneName);
|
|
||||||
|
|
||||||
return connection;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// FIXME: we need to put a "unknown" instead of a "any" and validate the structure of the JSON we are receiving.
|
// FIXME: we need to put a "unknown" instead of a "any" and validate the structure of the JSON we are receiving.
|
||||||
@ -617,6 +516,133 @@ export class GameScene extends Phaser.Scene implements CenterListener {
|
|||||||
this.connection.setSilent(true);
|
this.connection.setSilent(true);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const camera = this.cameras.main;
|
||||||
|
|
||||||
|
connectionManager.connectToRoomSocket(
|
||||||
|
this.RoomId,
|
||||||
|
gameManager.getPlayerName(),
|
||||||
|
gameManager.getCharacterSelected(),
|
||||||
|
{
|
||||||
|
x: this.startX,
|
||||||
|
y: this.startY
|
||||||
|
},
|
||||||
|
{
|
||||||
|
left: camera.scrollX,
|
||||||
|
top: camera.scrollY,
|
||||||
|
right: camera.scrollX + camera.width,
|
||||||
|
bottom: camera.scrollY + camera.height,
|
||||||
|
}).then((connection : RoomConnection) => {
|
||||||
|
this.connection = connection;
|
||||||
|
|
||||||
|
//this.connection.emitPlayerDetailsMessage(gameManager.getPlayerName(), gameManager.getCharacterSelected())
|
||||||
|
connection.onStartRoom((roomJoinedMessage: RoomJoinedMessageInterface) => {
|
||||||
|
this.initUsersPosition(roomJoinedMessage.users);
|
||||||
|
this.connectionAnswerPromiseResolve(roomJoinedMessage);
|
||||||
|
});
|
||||||
|
|
||||||
|
connection.onUserJoins((message: MessageUserJoined) => {
|
||||||
|
const userMessage: AddPlayerInterface = {
|
||||||
|
userId: message.userId,
|
||||||
|
characterLayers: message.characterLayers,
|
||||||
|
name: message.name,
|
||||||
|
position: message.position
|
||||||
|
}
|
||||||
|
this.addPlayer(userMessage);
|
||||||
|
});
|
||||||
|
|
||||||
|
connection.onUserMoved((message: UserMovedMessage) => {
|
||||||
|
const position = message.getPosition();
|
||||||
|
if (position === undefined) {
|
||||||
|
throw new Error('Position missing from UserMovedMessage');
|
||||||
|
}
|
||||||
|
//console.log('Received position ', position.getX(), position.getY(), "from user", message.getUserid());
|
||||||
|
|
||||||
|
const messageUserMoved: MessageUserMovedInterface = {
|
||||||
|
userId: message.getUserid(),
|
||||||
|
position: ProtobufClientUtils.toPointInterface(position)
|
||||||
|
}
|
||||||
|
|
||||||
|
this.updatePlayerPosition(messageUserMoved);
|
||||||
|
});
|
||||||
|
|
||||||
|
connection.onUserLeft((userId: number) => {
|
||||||
|
this.removePlayer(userId);
|
||||||
|
});
|
||||||
|
|
||||||
|
connection.onGroupUpdatedOrCreated((groupPositionMessage: GroupCreatedUpdatedMessageInterface) => {
|
||||||
|
this.shareGroupPosition(groupPositionMessage);
|
||||||
|
})
|
||||||
|
|
||||||
|
connection.onGroupDeleted((groupId: number) => {
|
||||||
|
try {
|
||||||
|
this.deleteGroup(groupId);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
connection.onServerDisconnected(() => {
|
||||||
|
console.log('Player disconnected from server. Reloading scene.');
|
||||||
|
|
||||||
|
this.simplePeer.closeAllConnections();
|
||||||
|
this.simplePeer.unregister();
|
||||||
|
|
||||||
|
const key = 'somekey'+Math.round(Math.random()*10000);
|
||||||
|
const game : Phaser.Scene = GameScene.createFromUrl(this.MapUrlFile, this.instance, key);
|
||||||
|
this.scene.add(key, game, true,
|
||||||
|
{
|
||||||
|
initPosition: {
|
||||||
|
x: this.CurrentPlayer.x,
|
||||||
|
y: this.CurrentPlayer.y
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.scene.stop(this.scene.key);
|
||||||
|
this.scene.remove(this.scene.key);
|
||||||
|
window.removeEventListener('resize', this.onResizeCallback);
|
||||||
|
})
|
||||||
|
|
||||||
|
connection.onActionableEvent((message => {
|
||||||
|
const item = this.actionableItems.get(message.itemId);
|
||||||
|
if (item === undefined) {
|
||||||
|
console.warn('Received an event about object "'+message.itemId+'" but cannot find this item on the map.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
item.fire(message.event, message.state, message.parameters);
|
||||||
|
}));
|
||||||
|
|
||||||
|
// When connection is performed, let's connect SimplePeer
|
||||||
|
this.simplePeer = new SimplePeer(this.connection);
|
||||||
|
this.GlobalMessageManager = new GlobalMessageManager(this.connection);
|
||||||
|
|
||||||
|
const self = this;
|
||||||
|
this.simplePeer.registerPeerConnectionListener({
|
||||||
|
onConnect(user: UserSimplePeerInterface) {
|
||||||
|
self.presentationModeSprite.setVisible(true);
|
||||||
|
self.chatModeSprite.setVisible(true);
|
||||||
|
},
|
||||||
|
onDisconnect(userId: number) {
|
||||||
|
if (self.simplePeer.getNbConnections() === 0) {
|
||||||
|
self.presentationModeSprite.setVisible(false);
|
||||||
|
self.chatModeSprite.setVisible(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
//listen event to share position of user
|
||||||
|
this.CurrentPlayer.on(hasMovedEventName, this.pushPlayerPosition.bind(this))
|
||||||
|
this.CurrentPlayer.on(hasMovedEventName, this.outlineItem.bind(this))
|
||||||
|
this.CurrentPlayer.on(hasMovedEventName, (event: HasMovedEvent) => {
|
||||||
|
this.gameMap.setPosition(event.x, event.y);
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
this.scene.wake();
|
||||||
|
this.scene.sleep(ReconnectingSceneName);
|
||||||
|
|
||||||
|
return connection;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private switchLayoutMode(): void {
|
private switchLayoutMode(): void {
|
||||||
@ -787,32 +813,6 @@ export class GameScene extends Phaser.Scene implements CenterListener {
|
|||||||
//create collision
|
//create collision
|
||||||
this.createCollisionWithPlayer();
|
this.createCollisionWithPlayer();
|
||||||
this.createCollisionObject();
|
this.createCollisionObject();
|
||||||
|
|
||||||
//join room
|
|
||||||
this.connectionPromise.then((connection: RoomConnection) => {
|
|
||||||
const camera = this.cameras.main;
|
|
||||||
connection.joinARoom(this.RoomId,
|
|
||||||
this.startX,
|
|
||||||
this.startY,
|
|
||||||
PlayerAnimationNames.WalkDown,
|
|
||||||
false, {
|
|
||||||
left: camera.scrollX,
|
|
||||||
top: camera.scrollY,
|
|
||||||
right: camera.scrollX + camera.width,
|
|
||||||
bottom: camera.scrollY + camera.height,
|
|
||||||
}).then((roomJoinedMessage: RoomJoinedMessageInterface) => {
|
|
||||||
this.initUsersPosition(roomJoinedMessage.users);
|
|
||||||
this.connectionAnswerPromiseResolve(roomJoinedMessage);
|
|
||||||
});
|
|
||||||
// FIXME: weirdly enough we don't use the result of joinARoom !!!!!!
|
|
||||||
|
|
||||||
//listen event to share position of user
|
|
||||||
this.CurrentPlayer.on(hasMovedEventName, this.pushPlayerPosition.bind(this))
|
|
||||||
this.CurrentPlayer.on(hasMovedEventName, this.outlineItem.bind(this))
|
|
||||||
this.CurrentPlayer.on(hasMovedEventName, (event: HasMovedEvent) => {
|
|
||||||
this.gameMap.setPosition(event.x, event.y);
|
|
||||||
})
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pushPlayerPosition(event: HasMovedEvent) {
|
pushPlayerPosition(event: HasMovedEvent) {
|
||||||
@ -983,7 +983,6 @@ export class GameScene extends Phaser.Scene implements CenterListener {
|
|||||||
type: "InitUserPositionEvent",
|
type: "InitUserPositionEvent",
|
||||||
event: usersPosition
|
event: usersPosition
|
||||||
});
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -1893,7 +1893,7 @@ extend-shallow@^3.0.0, extend-shallow@^3.0.2:
|
|||||||
assign-symbols "^1.0.0"
|
assign-symbols "^1.0.0"
|
||||||
is-extendable "^1.0.1"
|
is-extendable "^1.0.1"
|
||||||
|
|
||||||
extend@^3.0.1, extend@^3.0.2:
|
extend@^3.0.2:
|
||||||
version "3.0.2"
|
version "3.0.2"
|
||||||
resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa"
|
resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa"
|
||||||
integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==
|
integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==
|
||||||
@ -3871,15 +3871,15 @@ quill-delta@^3.6.2:
|
|||||||
extend "^3.0.2"
|
extend "^3.0.2"
|
||||||
fast-diff "1.1.2"
|
fast-diff "1.1.2"
|
||||||
|
|
||||||
quill@1.3.6:
|
quill@^1.3.7:
|
||||||
version "1.3.6"
|
version "1.3.7"
|
||||||
resolved "https://registry.yarnpkg.com/quill/-/quill-1.3.6.tgz#99f4de1fee85925a0d7d4163b6d8328f23317a4d"
|
resolved "https://registry.yarnpkg.com/quill/-/quill-1.3.7.tgz#da5b2f3a2c470e932340cdbf3668c9f21f9286e8"
|
||||||
integrity sha512-K0mvhimWZN6s+9OQ249CH2IEPZ9JmkFuCQeHAOQax3EZ2nDJ3wfGh59mnlQaZV2i7u8eFarx6wAtvQKgShojug==
|
integrity sha512-hG/DVzh/TiknWtE6QmWAF/pxoZKYxfe3J/d/+ShUWkDvvkZQVTPeVmUJVu1uE6DDooC4fWTiCLh84ul89oNz5g==
|
||||||
dependencies:
|
dependencies:
|
||||||
clone "^2.1.1"
|
clone "^2.1.1"
|
||||||
deep-equal "^1.0.1"
|
deep-equal "^1.0.1"
|
||||||
eventemitter3 "^2.0.3"
|
eventemitter3 "^2.0.3"
|
||||||
extend "^3.0.1"
|
extend "^3.0.2"
|
||||||
parchment "^1.1.4"
|
parchment "^1.1.4"
|
||||||
quill-delta "^3.6.2"
|
quill-delta "^3.6.2"
|
||||||
|
|
||||||
|
@ -38,12 +38,6 @@ message SetPlayerDetailsMessage {
|
|||||||
repeated string characterLayers = 2;
|
repeated string characterLayers = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
message JoinRoomMessage {
|
|
||||||
string roomId = 1;
|
|
||||||
PositionMessage position = 2;
|
|
||||||
ViewportMessage viewport = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
message UserMovesMessage {
|
message UserMovesMessage {
|
||||||
PositionMessage position = 1;
|
PositionMessage position = 1;
|
||||||
ViewportMessage viewport = 2;
|
ViewportMessage viewport = 2;
|
||||||
@ -56,7 +50,6 @@ message WebRtcSignalToServerMessage {
|
|||||||
|
|
||||||
message ClientToServerMessage {
|
message ClientToServerMessage {
|
||||||
oneof message {
|
oneof message {
|
||||||
JoinRoomMessage joinRoomMessage = 1;
|
|
||||||
UserMovesMessage userMovesMessage = 2;
|
UserMovesMessage userMovesMessage = 2;
|
||||||
SilentMessage silentMessage = 3;
|
SilentMessage silentMessage = 3;
|
||||||
ViewportMessage viewportMessage = 4;
|
ViewportMessage viewportMessage = 4;
|
||||||
|
Loading…
Reference in New Issue
Block a user