Adding support for "readableBy" and "writableBy" in back

This means that we are now loading maps from server side.
This commit is contained in:
David Négrier 2021-07-19 10:16:43 +02:00
parent 3d76f76d3e
commit dbd5b80636
24 changed files with 768 additions and 132 deletions

View file

@ -40,6 +40,7 @@
},
"homepage": "https://github.com/thecodingmachine/workadventure#readme",
"dependencies": {
"@workadventure/tiled-map-type-guard": "^1.0.0",
"axios": "^0.21.1",
"busboy": "^0.3.1",
"circular-json": "^0.5.9",
@ -47,6 +48,7 @@
"generic-type-guard": "^3.2.0",
"google-protobuf": "^3.13.0",
"grpc": "^1.24.4",
"ipaddr.js": "^2.0.1",
"jsonwebtoken": "^8.5.1",
"mkdirp": "^1.0.4",
"prom-client": "^12.0.0",

View file

@ -11,39 +11,54 @@ import {
EmoteEventMessage,
JoinRoomMessage,
SubToPusherRoomMessage,
VariableMessage,
VariableMessage, VariableWithTagMessage,
} from "../Messages/generated/messages_pb";
import { ProtobufUtils } from "../Model/Websocket/ProtobufUtils";
import { RoomSocket, ZoneSocket } from "src/RoomManager";
import { Admin } from "../Model/Admin";
import {adminApi} from "../Services/AdminApi";
import {isMapDetailsData, MapDetailsData} from "../Services/AdminApi/MapDetailsData";
import {ITiledMap} from "@workadventure/tiled-map-type-guard/dist";
import {mapFetcher} from "../Services/MapFetcher";
import {VariablesManager} from "../Services/VariablesManager";
import {ADMIN_API_URL} from "../Enum/EnvironmentVariable";
import {LocalUrlError} from "../Services/LocalUrlError";
export type ConnectCallback = (user: User, group: Group) => void;
export type DisconnectCallback = (user: User, group: Group) => void;
export class GameRoom {
private readonly minDistance: number;
private readonly groupRadius: number;
// Users, sorted by ID
private readonly users: Map<number, User>;
private readonly usersByUuid: Map<string, User>;
private readonly groups: Set<Group>;
private readonly admins: Set<Admin>;
private readonly connectCallback: ConnectCallback;
private readonly disconnectCallback: DisconnectCallback;
private readonly users = new Map<number, User>();
private readonly usersByUuid = new Map<string, User>();
private readonly groups = new Set<Group>();
private readonly admins = new Set<Admin>();
private itemsState = new Map<number, unknown>();
public readonly variables = new Map<string, string>();
private readonly positionNotifier: PositionNotifier;
public readonly roomUrl: string;
private versionNumber: number = 1;
private nextUserId: number = 1;
private roomListeners: Set<RoomSocket> = new Set<RoomSocket>();
constructor(
private constructor(
public readonly roomUrl: string,
private mapUrl: string,
private readonly connectCallback: ConnectCallback,
private readonly disconnectCallback: DisconnectCallback,
private readonly minDistance: number,
private readonly groupRadius: number,
onEnters: EntersCallback,
onMoves: MovesCallback,
onLeaves: LeavesCallback,
onEmote: EmoteCallback
) {
// A zone is 10 sprites wide.
this.positionNotifier = new PositionNotifier(320, 320, onEnters, onMoves, onLeaves, onEmote);
}
public static async create(
roomUrl: string,
connectCallback: ConnectCallback,
disconnectCallback: DisconnectCallback,
@ -53,19 +68,12 @@ export class GameRoom {
onMoves: MovesCallback,
onLeaves: LeavesCallback,
onEmote: EmoteCallback
) {
this.roomUrl = roomUrl;
) : Promise<GameRoom> {
const mapDetails = await GameRoom.getMapDetails(roomUrl);
this.users = new Map<number, User>();
this.usersByUuid = new Map<string, User>();
this.admins = new Set<Admin>();
this.groups = new Set<Group>();
this.connectCallback = connectCallback;
this.disconnectCallback = disconnectCallback;
this.minDistance = minDistance;
this.groupRadius = groupRadius;
// A zone is 10 sprites wide.
this.positionNotifier = new PositionNotifier(320, 320, onEnters, onMoves, onLeaves, onEmote);
const gameRoom = new GameRoom(roomUrl, mapDetails.mapUrl, connectCallback, disconnectCallback, minDistance, groupRadius, onEnters, onMoves, onLeaves, onEmote);
return gameRoom;
}
public getGroups(): Group[] {
@ -299,13 +307,19 @@ export class GameRoom {
return this.itemsState;
}
public setVariable(name: string, value: string): void {
this.variables.set(name, value);
public async setVariable(name: string, value: string, user: User): Promise<void> {
// First, let's check if "user" is allowed to modify the variable.
const variableManager = await this.getVariableManager();
const readableBy = variableManager.setVariable(name, value, user);
// TODO: should we batch those every 100ms?
const variableMessage = new VariableMessage();
const variableMessage = new VariableWithTagMessage();
variableMessage.setName(name);
variableMessage.setValue(value);
if (readableBy) {
variableMessage.setReadableby(readableBy);
}
const subMessage = new SubToPusherRoomMessage();
subMessage.setVariablemessage(variableMessage);
@ -356,4 +370,82 @@ export class GameRoom {
public removeRoomListener(socket: RoomSocket) {
this.roomListeners.delete(socket);
}
/**
* Connects to the admin server to fetch map details.
* If there is no admin server, the map details are generated by analysing the map URL (that must be in the form: /_/instance/map_url)
*/
private static async getMapDetails(roomUrl: string): Promise<MapDetailsData> {
if (!ADMIN_API_URL) {
const roomUrlObj = new URL(roomUrl);
const match = /\/_\/[^/]+\/(.+)/.exec(roomUrlObj.pathname);
if (!match) {
console.error('Unexpected room URL', roomUrl);
throw new Error('Unexpected room URL "' + roomUrl + '"');
}
const mapUrl = roomUrlObj.protocol + "//" + match[1];
return {
mapUrl,
policy_type: 1,
textures: [],
tags: [],
}
}
const result = await adminApi.fetchMapDetails(roomUrl);
if (!isMapDetailsData(result)) {
console.error('Unexpected room details received from server', result);
throw new Error('Unexpected room details received from server');
}
return result;
}
private mapPromise: Promise<ITiledMap>|undefined;
/**
* Returns a promise to the map file.
* @throws LocalUrlError if the map we are trying to load is hosted on a local network
* @throws Error
*/
private getMap(): Promise<ITiledMap> {
if (!this.mapPromise) {
this.mapPromise = mapFetcher.fetchMap(this.mapUrl);
}
return this.mapPromise;
}
private variableManagerPromise: Promise<VariablesManager>|undefined;
private getVariableManager(): Promise<VariablesManager> {
if (!this.variableManagerPromise) {
this.variableManagerPromise = new Promise<VariablesManager>((resolve, reject) => {
this.getMap().then((map) => {
resolve(new VariablesManager(map));
}).catch(e => {
if (e instanceof LocalUrlError) {
// If we are trying to load a local URL, we are probably in test mode.
// In this case, let's bypass the server-side checks completely.
// FIXME: find a way to send a warning to the client side
// FIXME: find a way to send a warning to the client side
// FIXME: find a way to send a warning to the client side
// FIXME: find a way to send a warning to the client side
resolve(new VariablesManager(null));
} else {
reject(e);
}
})
});
}
return this.variableManagerPromise;
}
public async getVariablesForTags(tags: string[]): Promise<Map<string, string>> {
const variablesManager = await this.getVariableManager();
return variablesManager.getVariablesForTags(tags);
}
}

View file

@ -4,7 +4,7 @@ import {
AdminMessage,
AdminPusherToBackMessage,
AdminRoomMessage,
BanMessage, BatchToPusherRoomMessage,
BanMessage, BatchToPusherMessage, BatchToPusherRoomMessage,
EmotePromptMessage,
EmptyMessage,
ItemEventMessage,
@ -14,7 +14,6 @@ import {
QueryJitsiJwtMessage,
RefreshRoomPromptMessage, RoomMessage,
ServerToAdminClientMessage,
ServerToClientMessage,
SilentMessage,
UserMovesMessage, VariableMessage,
WebRtcSignalToServerMessage,
@ -23,7 +22,7 @@ import {
} from "./Messages/generated/messages_pb";
import { sendUnaryData, ServerDuplexStream, ServerUnaryCall, ServerWritableStream } from "grpc";
import { socketManager } from "./Services/SocketManager";
import { emitError } from "./Services/MessageHelpers";
import {emitError, emitErrorOnRoomSocket, emitErrorOnZoneSocket} from "./Services/MessageHelpers";
import { User, UserSocket } from "./Model/User";
import { GameRoom } from "./Model/GameRoom";
import Debug from "debug";
@ -32,7 +31,7 @@ import { Admin } from "./Model/Admin";
const debug = Debug("roommanager");
export type AdminSocket = ServerDuplexStream<AdminPusherToBackMessage, ServerToAdminClientMessage>;
export type ZoneSocket = ServerWritableStream<ZoneMessage, ServerToClientMessage>;
export type ZoneSocket = ServerWritableStream<ZoneMessage, BatchToPusherMessage>;
export type RoomSocket = ServerWritableStream<RoomMessage, BatchToPusherRoomMessage>;
const roomManager: IRoomManagerServer = {
@ -56,7 +55,7 @@ const roomManager: IRoomManagerServer = {
//Connexion may have been closed before the init was finished, so we have to manually disconnect the user.
socketManager.leaveRoom(gameRoom, myUser);
}
});
}).catch(e => emitError(call, e));
} else {
throw new Error("The first message sent MUST be of type JoinRoomMessage");
}
@ -139,20 +138,22 @@ const roomManager: IRoomManagerServer = {
debug("listenZone called");
const zoneMessage = call.request;
socketManager.addZoneListener(call, zoneMessage.getRoomid(), zoneMessage.getX(), zoneMessage.getY());
socketManager.addZoneListener(call, zoneMessage.getRoomid(), zoneMessage.getX(), zoneMessage.getY()).catch(e => {
emitErrorOnZoneSocket(call, e.toString());
});
call.on("cancelled", () => {
debug("listenZone cancelled");
socketManager.removeZoneListener(call, zoneMessage.getRoomid(), zoneMessage.getX(), zoneMessage.getY());
socketManager.removeZoneListener(call, zoneMessage.getRoomid(), zoneMessage.getX(), zoneMessage.getY()).catch(e => console.error(e));
call.end();
});
call.on("close", () => {
debug("listenZone connection closed");
socketManager.removeZoneListener(call, zoneMessage.getRoomid(), zoneMessage.getX(), zoneMessage.getY());
socketManager.removeZoneListener(call, zoneMessage.getRoomid(), zoneMessage.getX(), zoneMessage.getY()).catch(e => console.error(e));
}).on("error", (e) => {
console.error("An error occurred in listenZone stream:", e);
socketManager.removeZoneListener(call, zoneMessage.getRoomid(), zoneMessage.getX(), zoneMessage.getY());
socketManager.removeZoneListener(call, zoneMessage.getRoomid(), zoneMessage.getX(), zoneMessage.getY()).catch(e => console.error(e));
call.end();
});
},
@ -161,20 +162,22 @@ const roomManager: IRoomManagerServer = {
debug("listenRoom called");
const roomMessage = call.request;
socketManager.addRoomListener(call, roomMessage.getRoomid());
socketManager.addRoomListener(call, roomMessage.getRoomid()).catch(e => {
emitErrorOnRoomSocket(call, e.toString());
});
call.on("cancelled", () => {
debug("listenRoom cancelled");
socketManager.removeRoomListener(call, roomMessage.getRoomid());
socketManager.removeRoomListener(call, roomMessage.getRoomid()).catch(e => console.error(e));
call.end();
});
call.on("close", () => {
debug("listenRoom connection closed");
socketManager.removeRoomListener(call, roomMessage.getRoomid());
socketManager.removeRoomListener(call, roomMessage.getRoomid()).catch(e => console.error(e));
}).on("error", (e) => {
console.error("An error occurred in listenRoom stream:", e);
socketManager.removeRoomListener(call, roomMessage.getRoomid());
socketManager.removeRoomListener(call, roomMessage.getRoomid()).catch(e => console.error(e));
call.end();
});
@ -193,7 +196,7 @@ const roomManager: IRoomManagerServer = {
const roomId = message.getSubscribetoroom();
socketManager.handleJoinAdminRoom(admin, roomId).then((gameRoom: GameRoom) => {
room = gameRoom;
});
}).catch(e => console.error(e));
} else {
throw new Error("The first message sent MUST be of type JoinRoomMessage");
}
@ -222,7 +225,7 @@ const roomManager: IRoomManagerServer = {
call.request.getRoomid(),
call.request.getRecipientuuid(),
call.request.getMessage()
);
).catch(e => console.error(e));
callback(null, new EmptyMessage());
},
@ -233,26 +236,29 @@ const roomManager: IRoomManagerServer = {
},
ban(call: ServerUnaryCall<BanMessage>, callback: sendUnaryData<EmptyMessage>): void {
// FIXME Work in progress
socketManager.banUser(call.request.getRoomid(), call.request.getRecipientuuid(), call.request.getMessage());
socketManager.banUser(call.request.getRoomid(), call.request.getRecipientuuid(), call.request.getMessage()).catch(e => console.error(e));
callback(null, new EmptyMessage());
},
sendAdminMessageToRoom(call: ServerUnaryCall<AdminRoomMessage>, callback: sendUnaryData<EmptyMessage>): void {
socketManager.sendAdminRoomMessage(call.request.getRoomid(), call.request.getMessage());
// FIXME: we could improve return message by returning a Success|ErrorMessage message
socketManager.sendAdminRoomMessage(call.request.getRoomid(), call.request.getMessage()).catch(e => console.error(e));
callback(null, new EmptyMessage());
},
sendWorldFullWarningToRoom(
call: ServerUnaryCall<WorldFullWarningToRoomMessage>,
callback: sendUnaryData<EmptyMessage>
): void {
socketManager.dispatchWorlFullWarning(call.request.getRoomid());
// FIXME: we could improve return message by returning a Success|ErrorMessage message
socketManager.dispatchWorldFullWarning(call.request.getRoomid()).catch(e => console.error(e));
callback(null, new EmptyMessage());
},
sendRefreshRoomPrompt(
call: ServerUnaryCall<RefreshRoomPromptMessage>,
callback: sendUnaryData<EmptyMessage>
): void {
socketManager.dispatchRoomRefresh(call.request.getRoomid());
// FIXME: we could improve return message by returning a Success|ErrorMessage message
socketManager.dispatchRoomRefresh(call.request.getRoomid()).catch(e => console.error(e));
callback(null, new EmptyMessage());
}
};

View file

@ -0,0 +1,24 @@
import { ADMIN_API_TOKEN, ADMIN_API_URL } from "../Enum/EnvironmentVariable";
import Axios from "axios";
import { MapDetailsData } from "./AdminApi/MapDetailsData";
import { RoomRedirect } from "./AdminApi/RoomRedirect";
class AdminApi {
async fetchMapDetails(playUri: string): Promise<MapDetailsData | RoomRedirect> {
if (!ADMIN_API_URL) {
return Promise.reject(new Error("No admin backoffice set!"));
}
const params: { playUri: string } = {
playUri,
};
const res = await Axios.get(ADMIN_API_URL + "/api/map", {
headers: { Authorization: `${ADMIN_API_TOKEN}` },
params,
});
return res.data;
}
}
export const adminApi = new AdminApi();

View file

@ -0,0 +1,11 @@
import * as tg from "generic-type-guard";
export const isCharacterTexture = new tg.IsInterface()
.withProperties({
id: tg.isNumber,
level: tg.isNumber,
url: tg.isString,
rights: tg.isString,
})
.get();
export type CharacterTexture = tg.GuardedType<typeof isCharacterTexture>;

View file

@ -0,0 +1,21 @@
import * as tg from "generic-type-guard";
import { isCharacterTexture } from "./CharacterTexture";
import { isAny, isNumber } from "generic-type-guard";
/*const isNumericEnum =
<T extends { [n: number]: string }>(vs: T) =>
(v: any): v is T =>
typeof v === "number" && v in vs;*/
export const isMapDetailsData = new tg.IsInterface()
.withProperties({
mapUrl: tg.isString,
policy_type: isNumber, //isNumericEnum(GameRoomPolicyTypes),
tags: tg.isArray(tg.isString),
textures: tg.isArray(isCharacterTexture),
})
.withOptionalProperties({
roomSlug: tg.isUnion(tg.isString, tg.isNull), // deprecated
})
.get();
export type MapDetailsData = tg.GuardedType<typeof isMapDetailsData>;

View file

@ -0,0 +1,8 @@
import * as tg from "generic-type-guard";
export const isRoomRedirect = new tg.IsInterface()
.withProperties({
redirectUrl: tg.isString,
})
.get();
export type RoomRedirect = tg.GuardedType<typeof isRoomRedirect>;

View file

@ -0,0 +1,2 @@
export class LocalUrlError extends Error {
}

View file

@ -0,0 +1,64 @@
import Axios from "axios";
import ipaddr from 'ipaddr.js';
import { Resolver } from 'dns';
import { promisify } from 'util';
import {LocalUrlError} from "./LocalUrlError";
import {ITiledMap} from "@workadventure/tiled-map-type-guard";
import {isTiledMap} from "@workadventure/tiled-map-type-guard/dist";
class MapFetcher {
async fetchMap(mapUrl: string): Promise<ITiledMap> {
// Before trying to make the query, let's verify the map is actually on the open internet (and not a local test map)
if (await this.isLocalUrl(mapUrl)) {
throw new LocalUrlError('URL for map "'+mapUrl+'" targets a local map');
}
// Note: mapUrl is provided by the client. A possible attack vector would be to use a rogue DNS server that
// returns local URLs. Alas, Axios cannot pin a URL to a given IP. So "isLocalUrl" and Axios.get could potentially
// target to different servers (and one could trick Axios.get into loading resources on the internal network
// despite isLocalUrl checking that.
// We can deem this problem not that important because:
// - We make sure we are only passing "GET" requests
// - The result of the query is never displayed to the end user
const res = await Axios.get(mapUrl, {
maxContentLength: 50*1024*1024, // Max content length: 50MB. Maps should not be bigger
});
if (!isTiledMap(res.data)) {
throw new Error('Invalid map format for map '+mapUrl);
}
return res.data;
}
/**
* Returns true if the domain name is localhost of *.localhost
* Returns true if the domain name resolves to an IP address that is "private" (like 10.x.x.x or 192.168.x.x)
*/
private async isLocalUrl(url: string): Promise<boolean> {
const urlObj = new URL(url);
if (urlObj.hostname === 'localhost' || urlObj.hostname.endsWith('.localhost')) {
return true;
}
let addresses = [];
if (!ipaddr.isValid(urlObj.hostname)) {
const resolver = new Resolver();
addresses = await promisify(resolver.resolve)(urlObj.hostname);
} else {
addresses = [urlObj.hostname];
}
for (const address of addresses) {
const addr = ipaddr.parse(address);
if (addr.range() !== 'unicast') {
return true;
}
}
return false;
}
}
export const mapFetcher = new MapFetcher();

View file

@ -1,5 +1,11 @@
import { ErrorMessage, ServerToClientMessage } from "../Messages/generated/messages_pb";
import {
BatchMessage,
BatchToPusherMessage, BatchToPusherRoomMessage,
ErrorMessage,
ServerToClientMessage, SubToPusherMessage, SubToPusherRoomMessage
} from "../Messages/generated/messages_pb";
import { UserSocket } from "_Model/User";
import {RoomSocket, ZoneSocket} from "../RoomManager";
export function emitError(Client: UserSocket, message: string): void {
const errorMessage = new ErrorMessage();
@ -13,3 +19,39 @@ export function emitError(Client: UserSocket, message: string): void {
//}
console.warn(message);
}
export function emitErrorOnRoomSocket(Client: RoomSocket, message: string): void {
console.error(message);
const errorMessage = new ErrorMessage();
errorMessage.setMessage(message);
const subToPusherRoomMessage = new SubToPusherRoomMessage();
subToPusherRoomMessage.setErrormessage(errorMessage);
const batchToPusherMessage = new BatchToPusherRoomMessage();
batchToPusherMessage.addPayload(subToPusherRoomMessage);
//if (!Client.disconnecting) {
Client.write(batchToPusherMessage);
//}
console.warn(message);
}
export function emitErrorOnZoneSocket(Client: ZoneSocket, message: string): void {
console.error(message);
const errorMessage = new ErrorMessage();
errorMessage.setMessage(message);
const subToPusherMessage = new SubToPusherMessage();
subToPusherMessage.setErrormessage(errorMessage);
const batchToPusherMessage = new BatchToPusherMessage();
batchToPusherMessage.addPayload(subToPusherMessage);
//if (!Client.disconnecting) {
Client.write(batchToPusherMessage);
//}
console.warn(message);
}

View file

@ -68,7 +68,7 @@ function emitZoneMessage(subMessage: SubToPusherMessage, socket: ZoneSocket): vo
}
export class SocketManager {
private rooms = new Map<string, GameRoom>();
//private rooms = new Map<string, GameRoom>();
// List of rooms in process of loading.
private roomsPromises = new Map<string, PromiseLike<GameRoom>>();
@ -106,7 +106,9 @@ export class SocketManager {
roomJoinedMessage.addItem(itemStateMessage);
}
for (const [name, value] of room.variables.entries()) {
const variables = await room.getVariablesForTags(user.tags);
for (const [name, value] of variables.entries()) {
const variableMessage = new VariableMessage();
variableMessage.setName(name);
variableMessage.setValue(value);
@ -198,12 +200,14 @@ export class SocketManager {
}
handleVariableEvent(room: GameRoom, user: User, variableMessage: VariableMessage) {
try {
room.setVariable(variableMessage.getName(), variableMessage.getValue());
} catch (e) {
console.error('An error occurred on "handleVariableEvent"');
console.error(e);
}
(async () => {
try {
await room.setVariable(variableMessage.getName(), variableMessage.getValue(), user);
} catch (e) {
console.error('An error occurred on "handleVariableEvent"');
console.error(e);
}
})();
}
emitVideo(room: GameRoom, user: User, data: WebRtcSignalToServerMessage): void {
@ -272,7 +276,7 @@ export class SocketManager {
//user leave previous world
room.leave(user);
if (room.isEmpty()) {
this.rooms.delete(room.roomUrl);
this.roomsPromises.delete(room.roomUrl);
gaugeManager.decNbRoomGauge();
debug('Room is empty. Deleting room "%s"', room.roomUrl);
}
@ -284,38 +288,34 @@ export class SocketManager {
async getOrCreateRoom(roomId: string): Promise<GameRoom> {
//check and create new room
let room = this.rooms.get(roomId);
if (room === undefined) {
let roomPromise = this.roomsPromises.get(roomId);
if (roomPromise) {
return roomPromise;
}
// Note: for now, the promise is useless (because this is synchronous, but soon, we will need to
// load the map server side.
room = new GameRoom(
roomId,
(user: User, group: Group) => this.joinWebRtcRoom(user, group),
(user: User, group: Group) => this.disConnectedUser(user, group),
MINIMUM_DISTANCE,
GROUP_RADIUS,
(thing: Movable, fromZone: Zone | null, listener: ZoneSocket) =>
this.onZoneEnter(thing, fromZone, listener),
(thing: Movable, position: PositionInterface, listener: ZoneSocket) =>
this.onClientMove(thing, position, listener),
(thing: Movable, newZone: Zone | null, listener: ZoneSocket) =>
this.onClientLeave(thing, newZone, listener),
(emoteEventMessage: EmoteEventMessage, listener: ZoneSocket) =>
this.onEmote(emoteEventMessage, listener)
);
gaugeManager.incNbRoomGauge();
this.rooms.set(roomId, room);
// TODO: change this the to new Promise()... when the method becomes actually asynchronous
roomPromise = Promise.resolve(room);
let roomPromise = this.roomsPromises.get(roomId);
if (roomPromise === undefined) {
roomPromise = new Promise<GameRoom>((resolve, reject) => {
GameRoom.create(
roomId,
(user: User, group: Group) => this.joinWebRtcRoom(user, group),
(user: User, group: Group) => this.disConnectedUser(user, group),
MINIMUM_DISTANCE,
GROUP_RADIUS,
(thing: Movable, fromZone: Zone | null, listener: ZoneSocket) =>
this.onZoneEnter(thing, fromZone, listener),
(thing: Movable, position: PositionInterface, listener: ZoneSocket) =>
this.onClientMove(thing, position, listener),
(thing: Movable, newZone: Zone | null, listener: ZoneSocket) =>
this.onClientLeave(thing, newZone, listener),
(emoteEventMessage: EmoteEventMessage, listener: ZoneSocket) =>
this.onEmote(emoteEventMessage, listener)
).then((gameRoom) => {
gaugeManager.incNbRoomGauge();
resolve(gameRoom);
}).catch((e) => {
this.roomsPromises.delete(roomId);
reject(e);
});
});
this.roomsPromises.set(roomId, roomPromise);
}
return Promise.resolve(room);
return roomPromise;
}
private async joinRoom(
@ -554,8 +554,8 @@ export class SocketManager {
}
}
public getWorlds(): Map<string, GameRoom> {
return this.rooms;
public getWorlds(): Map<string, PromiseLike<GameRoom>> {
return this.roomsPromises;
}
public handleQueryJitsiJwtMessage(user: User, queryJitsiJwtMessage: QueryJitsiJwtMessage) {
@ -625,11 +625,10 @@ export class SocketManager {
}, 10000);
}
public addZoneListener(call: ZoneSocket, roomId: string, x: number, y: number): void {
const room = this.rooms.get(roomId);
public async addZoneListener(call: ZoneSocket, roomId: string, x: number, y: number): Promise<void> {
const room = await this.roomsPromises.get(roomId);
if (!room) {
console.error("In addZoneListener, could not find room with id '" + roomId + "'");
return;
throw new Error("In addZoneListener, could not find room with id '" + roomId + "'");
}
const things = room.addZoneListener(call, x, y);
@ -670,11 +669,10 @@ export class SocketManager {
call.write(batchMessage);
}
removeZoneListener(call: ZoneSocket, roomId: string, x: number, y: number) {
const room = this.rooms.get(roomId);
async removeZoneListener(call: ZoneSocket, roomId: string, x: number, y: number): Promise<void> {
const room = await this.roomsPromises.get(roomId);
if (!room) {
console.error("In removeZoneListener, could not find room with id '" + roomId + "'");
return;
throw new Error("In removeZoneListener, could not find room with id '" + roomId + "'");
}
room.removeZoneListener(call, x, y);
@ -683,8 +681,7 @@ export class SocketManager {
async addRoomListener(call: RoomSocket, roomId: string) {
const room = await this.getOrCreateRoom(roomId);
if (!room) {
console.error("In addRoomListener, could not find room with id '" + roomId + "'");
return;
throw new Error("In addRoomListener, could not find room with id '" + roomId + "'");
}
room.addRoomListener(call);
@ -692,7 +689,10 @@ export class SocketManager {
const batchMessage = new BatchToPusherRoomMessage();
for (const [name, value] of room.variables.entries()) {
// Finally, no need to store variables in the pusher, let's only make it act as a relay
/*const variables = await room.getVariables();
for (const [name, value] of variables.entries()) {
const variableMessage = new VariableMessage();
variableMessage.setName(name);
variableMessage.setValue(value);
@ -701,16 +701,15 @@ export class SocketManager {
subMessage.setVariablemessage(variableMessage);
batchMessage.addPayload(subMessage);
}
}*/
call.write(batchMessage);
}
removeRoomListener(call: RoomSocket, roomId: string) {
const room = this.rooms.get(roomId);
async removeRoomListener(call: RoomSocket, roomId: string) {
const room = await this.roomsPromises.get(roomId);
if (!room) {
console.error("In removeRoomListener, could not find room with id '" + roomId + "'");
return;
throw new Error("In removeRoomListener, could not find room with id '" + roomId + "'");
}
room.removeRoomListener(call);
@ -727,14 +726,14 @@ export class SocketManager {
public leaveAdminRoom(room: GameRoom, admin: Admin) {
room.adminLeave(admin);
if (room.isEmpty()) {
this.rooms.delete(room.roomUrl);
this.roomsPromises.delete(room.roomUrl);
gaugeManager.decNbRoomGauge();
debug('Room is empty. Deleting room "%s"', room.roomUrl);
}
}
public sendAdminMessage(roomId: string, recipientUuid: string, message: string): void {
const room = this.rooms.get(roomId);
public async sendAdminMessage(roomId: string, recipientUuid: string, message: string): Promise<void> {
const room = await this.roomsPromises.get(roomId);
if (!room) {
console.error(
"In sendAdminMessage, could not find room with id '" +
@ -764,8 +763,8 @@ export class SocketManager {
recipient.socket.write(serverToClientMessage);
}
public banUser(roomId: string, recipientUuid: string, message: string): void {
const room = this.rooms.get(roomId);
public async banUser(roomId: string, recipientUuid: string, message: string): Promise<void> {
const room = await this.roomsPromises.get(roomId);
if (!room) {
console.error(
"In banUser, could not find room with id '" +
@ -800,8 +799,8 @@ export class SocketManager {
recipient.socket.end();
}
sendAdminRoomMessage(roomId: string, message: string) {
const room = this.rooms.get(roomId);
async sendAdminRoomMessage(roomId: string, message: string) {
const room = await this.roomsPromises.get(roomId);
if (!room) {
//todo: this should cause the http call to return a 500
console.error(
@ -824,8 +823,8 @@ export class SocketManager {
});
}
dispatchWorlFullWarning(roomId: string): void {
const room = this.rooms.get(roomId);
async dispatchWorldFullWarning(roomId: string): Promise<void> {
const room = await this.roomsPromises.get(roomId);
if (!room) {
//todo: this should cause the http call to return a 500
console.error(
@ -846,8 +845,8 @@ export class SocketManager {
});
}
dispatchRoomRefresh(roomId: string): void {
const room = this.rooms.get(roomId);
async dispatchRoomRefresh(roomId: string): Promise<void> {
const room = await this.roomsPromises.get(roomId);
if (!room) {
return;
}

View file

@ -0,0 +1,139 @@
/**
* Handles variables shared between the scripting API and the server.
*/
import {ITiledMap, ITiledMapObject, ITiledMapObjectLayer} from "@workadventure/tiled-map-type-guard/dist";
import {User} from "_Model/User";
interface Variable {
defaultValue?: string,
persist?: boolean,
readableBy?: string,
writableBy?: string,
}
export class VariablesManager {
/**
* The actual values of the variables for the current room
*/
private _variables = new Map<string, string>();
/**
* The list of variables that are allowed
*/
private variableObjects: Map<string, Variable> | undefined;
/**
* @param map The map can be "null" if it is hosted on a private network. In this case, we assume this is a test setup and bypass any server-side checks.
*/
constructor(private map: ITiledMap | null) {
// We initialize the list of variable object at room start. The objects cannot be edited later
// (otherwise, this would cause a security issue if the scripting API can edit this list of objects)
if (map) {
this.variableObjects = VariablesManager.findVariablesInMap(map);
// Let's initialize default values
for (const [name, variableObject] of this.variableObjects.entries()) {
if (variableObject.defaultValue !== undefined) {
this._variables.set(name, variableObject.defaultValue);
}
}
}
}
private static findVariablesInMap(map: ITiledMap): Map<string, Variable> {
const objects = new Map<string, Variable>();
for (const layer of map.layers) {
if (layer.type === 'objectgroup') {
for (const object of (layer as ITiledMapObjectLayer).objects) {
if (object.type === 'variable') {
if (object.template) {
console.warn('Warning, a variable object is using a Tiled "template". WorkAdventure does not support objects generated from Tiled templates.')
continue;
}
// We store a copy of the object (to make it immutable)
objects.set(object.name, this.iTiledObjectToVariable(object));
}
}
}
}
return objects;
}
private static iTiledObjectToVariable(object: ITiledMapObject): Variable {
const variable: Variable = {};
if (object.properties) {
for (const property of object.properties) {
const value = property.value;
switch (property.name) {
case 'default':
variable.defaultValue = JSON.stringify(value);
break;
case 'persist':
if (typeof value !== 'boolean') {
throw new Error('The persist property of variable "' + object.name + '" must be a boolean');
}
variable.persist = value;
break;
case 'writableBy':
if (typeof value !== 'string') {
throw new Error('The writableBy property of variable "' + object.name + '" must be a string');
}
if (value) {
variable.writableBy = value;
}
break;
case 'readableBy':
if (typeof value !== 'string') {
throw new Error('The readableBy property of variable "' + object.name + '" must be a string');
}
if (value) {
variable.readableBy = value;
}
break;
}
}
}
return variable;
}
setVariable(name: string, value: string, user: User): string | undefined {
let readableBy: string | undefined;
if (this.variableObjects) {
const variableObject = this.variableObjects.get(name);
if (variableObject === undefined) {
throw new Error('Trying to set a variable "' + name + '" that is not defined as an object in the map.');
}
if (variableObject.writableBy && user.tags.indexOf(variableObject.writableBy) === -1) {
throw new Error('Trying to set a variable "' + name + '". User "' + user.name + '" does not have sufficient permission. Required tag: "' + variableObject.writableBy + '". User tags: ' + user.tags.join(', ') + ".");
}
readableBy = variableObject.readableBy;
}
this._variables.set(name, value);
return readableBy;
}
public getVariablesForTags(tags: string[]): Map<string, string> {
if (this.variableObjects === undefined) {
return this._variables;
}
const readableVariables = new Map<string, string>();
for (const [key, value] of this._variables.entries()) {
const variableObject = this.variableObjects.get(key);
if (variableObject === undefined) {
throw new Error('Unexpected variable "'+key+'" found has no associated variableObject.');
}
if (!variableObject.readableBy || tags.indexOf(variableObject.readableBy) !== -1) {
readableVariables.set(key, value);
}
}
return readableVariables;
}
}

View file

@ -3,7 +3,7 @@
"experimentalDecorators": true,
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"target": "ES2019", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"downlevelIteration": true,
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */

View file

@ -187,6 +187,13 @@
semver "^7.3.2"
tsutils "^3.17.1"
"@workadventure/tiled-map-type-guard@^1.0.0":
version "1.0.0"
resolved "https://registry.yarnpkg.com/@workadventure/tiled-map-type-guard/-/tiled-map-type-guard-1.0.0.tgz#02524602ee8b2688429a1f56df1d04da3fc171ba"
integrity sha512-Mc0SE128otQnYlScQWVaQVyu1+CkailU/FTBh09UTrVnBAhyMO+jIn9vT9+Dv244xq+uzgQDpXmiVdjgrYFQ+A==
dependencies:
generic-type-guard "^3.4.1"
abbrev@1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8"
@ -1181,6 +1188,11 @@ generic-type-guard@^3.2.0:
resolved "https://registry.yarnpkg.com/generic-type-guard/-/generic-type-guard-3.3.3.tgz#954b846fecff91047cadb0dcc28930811fcb9dc1"
integrity sha512-SXraZvNW/uTfHVgB48iEwWaD1XFJ1nvZ8QP6qy9pSgaScEyQqFHYN5E6d6rCsJgrvlWKygPrNum7QeJHegzNuQ==
generic-type-guard@^3.4.1:
version "3.4.1"
resolved "https://registry.yarnpkg.com/generic-type-guard/-/generic-type-guard-3.4.1.tgz#0896dc018de915c890562a34763858076e4676da"
integrity sha512-sXce0Lz3Wfy2rR1W8O8kUemgEriTeG1x8shqSJeWGb0FwJu2qBEkB1M2qXbdSLmpgDnHcIXo0Dj/1VLNJkK/QA==
get-own-enumerable-property-symbols@^3.0.0:
version "3.0.2"
resolved "https://registry.yarnpkg.com/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz#b5fde77f22cbe35f390b4e089922c50bce6ef664"
@ -1417,6 +1429,11 @@ invert-kv@^1.0.0:
resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-1.0.0.tgz#104a8e4aaca6d3d8cd157a8ef8bfab2d7a3ffdb6"
integrity sha1-EEqOSqym09jNFXqO+L+rLXo//bY=
ipaddr.js@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-2.0.1.tgz#eca256a7a877e917aeb368b0a7497ddf42ef81c0"
integrity sha512-1qTgH9NG+IIJ4yfKs2e6Pp1bZg8wbDbKHT21HrLIeYBTRLgMYKnMTPAuI3Lcs61nfx5h1xlXnbJtH1kX5/d/ng==
is-accessor-descriptor@^0.1.6:
version "0.1.6"
resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz#a9e12cb3ae8d876727eeef3843f8a0897b5c98d6"