partey_workadventure/front/src/Connection.ts

373 lines
12 KiB
TypeScript
Raw Normal View History

import Axios from "axios";
import {API_URL} from "./Enum/EnvironmentVariable";
2020-05-13 20:22:42 +02:00
import {MessageUI} from "./Logger/MessageUI";
import {
BatchMessage,
PositionMessage,
SetPlayerDetailsMessage, UserMovedMessage,
UserMovesMessage,
ViewportMessage
} from "../../messages/generated/messages_pb"
const SocketIo = require('socket.io-client');
import Socket = SocketIOClient.Socket;
import {PlayerAnimationNames} from "./Phaser/Player/Animation";
import {UserSimplePeerInterface} from "./WebRtc/SimplePeer";
import {SignalData} from "simple-peer";
import Direction = PositionMessage.Direction;
2020-04-25 16:05:33 +02:00
enum EventMessage{
WEBRTC_SIGNAL = "webrtc-signal",
2020-06-11 23:18:06 +02:00
WEBRTC_SCREEN_SHARING_SIGNAL = "webrtc-screen-sharing-signal",
2020-04-25 16:05:33 +02:00
WEBRTC_START = "webrtc-start",
JOIN_ROOM = "join-room", // bi-directional
USER_POSITION = "user-position", // From client to server
USER_MOVED = "user-moved", // From server to client
USER_LEFT = "user-left", // From server to client
2020-05-02 20:46:02 +02:00
MESSAGE_ERROR = "message-error",
WEBRTC_DISCONNECT = "webrtc-disconect",
GROUP_CREATE_UPDATE = "group-create-update",
GROUP_DELETE = "group-delete",
SET_PLAYER_DETAILS = "set-player-details", // Send the name and character to the server (on connect), receive back the id.
2020-07-27 22:36:07 +02:00
ITEM_EVENT = 'item-event',
2020-05-13 20:22:42 +02:00
CONNECT_ERROR = "connect_error",
SET_SILENT = "set_silent", // Set or unset the silent mode for this user.
SET_VIEWPORT = "set-viewport",
BATCH = "batch",
}
export interface PointInterface {
x: number;
y: number;
direction : string;
moving: boolean;
}
export class Point implements PointInterface{
constructor(public x : number, public y : number, public direction : string = PlayerAnimationNames.WalkDown, public moving : boolean = false) {
if(x === null || y === null){
throw Error("position x and y cannot be null");
}
}
}
export interface MessageUserPositionInterface {
userId: number;
name: string;
characterLayers: string[];
position: PointInterface;
}
2020-04-25 16:05:33 +02:00
export interface MessageUserMovedInterface {
userId: number;
position: PointInterface;
}
export interface MessageUserJoined {
userId: number;
name: string;
characterLayers: string[];
position: PointInterface
}
export interface PositionInterface {
x: number,
y: number
}
export interface GroupCreatedUpdatedMessageInterface {
position: PositionInterface,
groupId: string
}
export interface WebRtcStartMessageInterface {
roomId: string,
clients: UserSimplePeerInterface[]
}
export interface WebRtcDisconnectMessageInterface {
userId: number
}
export interface WebRtcSignalSentMessageInterface {
receiverId: number,
signal: SignalData
}
export interface WebRtcSignalReceivedMessageInterface {
userId: number,
signal: SignalData
}
export interface StartMapInterface {
mapUrlStart: string,
startInstance: string
}
export interface ViewportInterface {
left: number,
top: number,
right: number,
bottom: number,
}
export interface BatchedMessageInterface {
event: string,
2020-09-15 10:10:35 +02:00
payload: unknown
}
2020-07-27 22:36:07 +02:00
export interface ItemEventMessageInterface {
itemId: number,
event: string,
state: unknown,
parameters: unknown
}
export interface RoomJoinedMessageInterface {
2020-09-16 16:06:43 +02:00
users: MessageUserPositionInterface[],
groups: GroupCreatedUpdatedMessageInterface[],
2020-07-27 22:36:07 +02:00
items: { [itemId: number] : unknown }
}
export class Connection implements Connection {
private readonly socket: Socket;
private userId: number|null = null;
private batchCallbacks: Map<string, Function[]> = new Map<string, Function[]>();
2020-04-07 20:41:35 +02:00
private constructor(token: string) {
this.socket = SocketIo(`${API_URL}`, {
query: {
token: token
},
reconnection: false // Reconnection is handled by the application itself
});
this.socket.on(EventMessage.MESSAGE_ERROR, (message: string) => {
console.error(EventMessage.MESSAGE_ERROR, message);
})
/**
* Messages inside batched messages are extracted and sent to listeners directly.
*/
this.socket.on(EventMessage.BATCH, (batchedMessagesBinary: ArrayBuffer) => {
const batchMessage = BatchMessage.deserializeBinary(new Uint8Array(batchedMessagesBinary as ArrayBuffer));
for (const message of batchMessage.getPayloadList()) {
let event: string;
let payload;
if (message.hasUsermovedmessage()) {
event = EventMessage.USER_MOVED;
payload = message.getUsermovedmessage();
} else {
throw new Error('Unexpected batch message type');
}
const listeners = this.batchCallbacks.get(event);
if (listeners === undefined) {
continue;
}
for (const listener of listeners) {
listener(payload);
}
}
})
}
public static createConnection(name: string, characterLayersSelected: string[]): Promise<Connection> {
return Axios.post(`${API_URL}/login`, {name: name})
.then((res) => {
2020-06-22 16:10:18 +02:00
return new Promise<Connection>((resolve, reject) => {
const connection = new Connection(res.data.token);
2020-06-22 16:10:18 +02:00
connection.onConnectError((error: object) => {
console.log('An error occurred while connecting to socket server. Retrying');
reject(error);
});
2020-09-17 17:14:47 +02:00
const message = new SetPlayerDetailsMessage();
message.setName(name);
message.setCharacterlayersList(characterLayersSelected);
connection.socket.emit(EventMessage.SET_PLAYER_DETAILS, message.serializeBinary().buffer, (id: number) => {
2020-06-22 16:10:18 +02:00
connection.userId = id;
});
resolve(connection);
});
})
.catch((err) => {
// Let's retry in 4-6 seconds
return new Promise<Connection>((resolve, reject) => {
setTimeout(() => {
Connection.createConnection(name, characterLayersSelected).then((connection) => resolve(connection))
2020-06-22 16:10:18 +02:00
.catch((error) => reject(error));
}, 4000 + Math.floor(Math.random() * 2000) );
});
});
}
public closeConnection(): void {
this.socket?.close();
2020-06-03 11:55:31 +02:00
}
2020-09-16 11:41:03 +02:00
public joinARoom(roomId: string, startX: number, startY: number, direction: string, moving: boolean, viewport: ViewportInterface): Promise<RoomJoinedMessageInterface> {
2020-07-27 22:36:07 +02:00
const promise = new Promise<RoomJoinedMessageInterface>((resolve, reject) => {
this.socket.emit(EventMessage.JOIN_ROOM, {
roomId,
position: {x: startX, y: startY, direction, moving },
viewport,
2020-09-16 11:41:03 +02:00
}, (roomJoinedMessage: RoomJoinedMessageInterface) => {
resolve(roomJoinedMessage);
});
})
return promise;
}
public sharePosition(x : number, y : number, direction : string, moving: boolean, viewport: ViewportInterface) : void{
2020-04-07 20:46:30 +02:00
if(!this.socket){
return;
}
2020-06-09 23:13:26 +02:00
const point = new Point(x, y, direction, moving);
const positionMessage = new PositionMessage();
positionMessage.setX(Math.floor(x));
positionMessage.setY(Math.floor(y));
let directionEnum: PositionMessage.DirectionMap[keyof PositionMessage.DirectionMap];
switch (direction) {
case 'up':
directionEnum = Direction.UP;
break;
case 'down':
directionEnum = Direction.DOWN;
break;
case 'left':
directionEnum = Direction.LEFT;
break;
case 'right':
directionEnum = Direction.RIGHT;
break;
default:
throw new Error("Unexpected direction");
}
positionMessage.setDirection(directionEnum);
positionMessage.setMoving(moving);
const viewportMessage = new ViewportMessage();
viewportMessage.setLeft(Math.floor(viewport.left));
viewportMessage.setRight(Math.floor(viewport.right));
viewportMessage.setTop(Math.floor(viewport.top));
viewportMessage.setBottom(Math.floor(viewport.bottom));
const userMovesMessage = new UserMovesMessage();
userMovesMessage.setPosition(positionMessage);
userMovesMessage.setViewport(viewportMessage);
this.socket.emit(EventMessage.USER_POSITION, userMovesMessage.serializeBinary().buffer);
}
public setSilent(silent: boolean): void {
this.socket.emit(EventMessage.SET_SILENT, silent);
}
public setViewport(viewport: ViewportInterface): void {
this.socket.emit(EventMessage.SET_VIEWPORT, viewport);
}
public onUserJoins(callback: (message: MessageUserJoined) => void): void {
this.socket.on(EventMessage.JOIN_ROOM, callback);
}
public onUserMoved(callback: (message: UserMovedMessage) => void): void {
this.onBatchMessage(EventMessage.USER_MOVED, callback);
//this.socket.on(EventMessage.USER_MOVED, callback);
}
/**
* Registers a listener on a message that is part of a batch
*/
private onBatchMessage(eventName: string, callback: Function): void {
let callbacks = this.batchCallbacks.get(eventName);
if (callbacks === undefined) {
callbacks = new Array<Function>();
this.batchCallbacks.set(eventName, callbacks);
}
callbacks.push(callback);
}
public onUserLeft(callback: (userId: number) => void): void {
this.socket.on(EventMessage.USER_LEFT, callback);
}
public onGroupUpdatedOrCreated(callback: (groupCreateUpdateMessage: GroupCreatedUpdatedMessageInterface) => void): void {
this.socket.on(EventMessage.GROUP_CREATE_UPDATE, callback);
}
public onGroupDeleted(callback: (groupId: string) => void): void {
this.socket.on(EventMessage.GROUP_DELETE, callback)
}
2020-06-22 16:10:18 +02:00
public onConnectError(callback: (error: object) => void): void {
this.socket.on(EventMessage.CONNECT_ERROR, callback)
}
public sendWebrtcSignal(signal: unknown, receiverId: number) {
return this.socket.emit(EventMessage.WEBRTC_SIGNAL, {
receiverId: receiverId,
2020-04-25 16:05:33 +02:00
signal: signal
} as WebRtcSignalSentMessageInterface);
2020-04-25 16:05:33 +02:00
}
public sendWebrtcScreenSharingSignal(signal: unknown, receiverId: number) {
return this.socket.emit(EventMessage.WEBRTC_SCREEN_SHARING_SIGNAL, {
receiverId: receiverId,
2020-06-11 23:18:06 +02:00
signal: signal
} as WebRtcSignalSentMessageInterface);
2020-04-25 16:05:33 +02:00
}
public receiveWebrtcStart(callback: (message: WebRtcStartMessageInterface) => void) {
this.socket.on(EventMessage.WEBRTC_START, callback);
2020-04-25 16:05:33 +02:00
}
public receiveWebrtcSignal(callback: (message: WebRtcSignalReceivedMessageInterface) => void) {
return this.socket.on(EventMessage.WEBRTC_SIGNAL, callback);
2020-04-25 16:05:33 +02:00
}
public receiveWebrtcScreenSharingSignal(callback: (message: WebRtcSignalReceivedMessageInterface) => void) {
return this.socket.on(EventMessage.WEBRTC_SCREEN_SHARING_SIGNAL, callback);
2020-04-25 16:05:33 +02:00
}
public onServerDisconnected(callback: (reason: string) => void): void {
this.socket.on('disconnect', (reason: string) => {
if (reason === 'io client disconnect') {
// The client asks for disconnect, let's not trigger any event.
return;
}
callback(reason);
2020-05-13 20:22:42 +02:00
});
}
public getUserId(): number|null {
return this.userId;
2020-05-13 20:22:42 +02:00
}
disconnectMessage(callback: (message: WebRtcDisconnectMessageInterface) => void): void {
this.socket.on(EventMessage.WEBRTC_DISCONNECT, callback);
2020-05-02 20:46:02 +02:00
}
2020-07-27 22:36:07 +02:00
emitActionableEvent(itemId: number, event: string, state: unknown, parameters: unknown) {
return this.socket.emit(EventMessage.ITEM_EVENT, {
itemId,
event,
state,
parameters
});
}
onActionableEvent(callback: (message: ItemEventMessageInterface) => void): void {
this.socket.on(EventMessage.ITEM_EVENT, callback);
}
}