Merge branch 'develop' of github.com:thecodingmachine/workadventure into codeAPI

This commit is contained in:
CEC
2022-04-12 17:17:48 +02:00
176 changed files with 1518 additions and 1248 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
// lib/app.ts
import { IoSocketController } from "./Controller/IoSocketController"; //TODO fix import by "_Controller/..."
import { AuthenticateController } from "./Controller/AuthenticateController"; //TODO fix import by "_Controller/..."
import { IoSocketController } from "./Controller/IoSocketController";
import { AuthenticateController } from "./Controller/AuthenticateController";
import { MapController } from "./Controller/MapController";
import { PrometheusController } from "./Controller/PrometheusController";
import { DebugController } from "./Controller/DebugController";
+1 -1
View File
@@ -28,7 +28,7 @@ export class DebugController extends BaseHttpController {
return obj;
} else if (value instanceof Set) {
const obj: Array<unknown> = [];
for (const [setKey, setValue] of value.entries()) {
for (const setValue of value.values()) {
obj.push(setValue);
}
return obj;
+19 -14
View File
@@ -1,4 +1,4 @@
import { ExSocketInterface } from "../Model/Websocket/ExSocketInterface"; //TODO fix import by "_Model/.."
import { ExSocketInterface } from "../Model/Websocket/ExSocketInterface";
import { GameRoomPolicyTypes } from "../Model/PusherRoom";
import { PointInterface } from "../Model/Websocket/PointInterface";
import {
@@ -27,18 +27,19 @@ import { UserMovesMessage } from "../Messages/generated/messages_pb";
import { parse } from "query-string";
import { AdminSocketTokenData, jwtTokenManager, tokenInvalidException } from "../Services/JWTTokenManager";
import { adminApi, FetchMemberDataByUuidResponse } from "../Services/AdminApi";
import { SocketManager, socketManager } from "../Services/SocketManager";
import { socketManager } from "../Services/SocketManager";
import { emitInBatch } from "../Services/IoSocketHelpers";
import { ADMIN_API_URL, ADMIN_SOCKETS_TOKEN, DISABLE_ANONYMOUS, SOCKET_IDLE_TIMER } from "../Enum/EnvironmentVariable";
import { Zone } from "_Model/Zone";
import { ExAdminSocketInterface } from "_Model/Websocket/ExAdminSocketInterface";
import { isAdminMessageInterface } from "../Model/Websocket/Admin/AdminMessages";
import { Zone } from "../Model/Zone";
import { ExAdminSocketInterface } from "../Model/Websocket/ExAdminSocketInterface";
import { AdminMessageInterface, isAdminMessageInterface } from "../Model/Websocket/Admin/AdminMessages";
import Axios from "axios";
import { InvalidTokenError } from "../Controller/InvalidTokenError";
import HyperExpress from "hyper-express";
import { localWokaService } from "../Services/LocalWokaService";
import { WebSocket } from "uWebSockets.js";
import { WokaDetail } from "../Messages/JsonMessages/PlayerTextures";
import { z } from "zod";
/**
* The object passed between the "open" and the "upgrade" methods when opening a websocket
@@ -96,11 +97,18 @@ export class IoSocketController {
console.log("Admin socket connect to client on " + Buffer.from(ws.getRemoteAddressAsText()).toString());
ws.disconnecting = false;
},
message: (ws, arrayBuffer, isBinary): void => {
message: (ws, arrayBuffer): void => {
try {
const message = JSON.parse(new TextDecoder("utf-8").decode(new Uint8Array(arrayBuffer)));
const message: AdminMessageInterface = JSON.parse(
new TextDecoder("utf-8").decode(new Uint8Array(arrayBuffer))
);
if (!isAdminMessageInterface(message)) {
try {
isAdminMessageInterface.parse(message);
} catch (err) {
if (err instanceof z.ZodError) {
console.error(err.issues);
}
console.error("Invalid message received.", message);
ws.send(
JSON.stringify({
@@ -186,14 +194,12 @@ export class IoSocketController {
.catch((error) => console.error(error));
}
}
} else {
const tmp: never = message.event;
}
} catch (err) {
console.error(err);
}
},
close: (ws, code, message) => {
close: (ws) => {
const Client = ws as ExAdminSocketInterface;
try {
Client.disconnecting = true;
@@ -224,7 +230,6 @@ export class IoSocketController {
upgradeAborted.aborted = true;
});
const url = req.getUrl();
const query = parse(req.getQuery());
const websocketKey = req.getHeader("sec-websocket-key");
const websocketProtocol = req.getHeader("sec-websocket-protocol");
@@ -522,7 +527,7 @@ export class IoSocketController {
});
}
},
message: (ws, arrayBuffer, isBinary): void => {
message: (ws, arrayBuffer): void => {
const client = ws as ExSocketInterface;
const message = ClientToServerMessage.deserializeBinary(new Uint8Array(arrayBuffer));
@@ -590,7 +595,7 @@ export class IoSocketController {
drain: (ws) => {
console.log("WebSocket backpressure: " + ws.getBufferedAmount());
},
close: (ws, code, message) => {
close: (ws) => {
const Client = ws as ExSocketInterface;
try {
Client.disconnecting = true;
+5 -3
View File
@@ -160,10 +160,12 @@ export class MapController extends BaseHttpController {
}
}
}
const mapDetails = await adminApi.fetchMapDetails(query.playUri as string, userId);
const mapDetails = isMapDetailsData.safeParse(
await adminApi.fetchMapDetails(query.playUri as string, userId)
);
if (isMapDetailsData(mapDetails) && DISABLE_ANONYMOUS) {
mapDetails.authenticationMandatory = true;
if (mapDetails.success && DISABLE_ANONYMOUS) {
mapDetails.data.authenticationMandatory = true;
}
res.json(mapDetails);
-48
View File
@@ -1,48 +0,0 @@
import * as tg from "generic-type-guard";
import { z } from "zod";
//The list of all the player textures, both the default models and the partial textures used for customization
const wokaTexture = z.object({
id: z.string(),
name: z.string(),
url: z.string(),
tags: z.array(z.string()).optional(),
tintable: z.boolean().optional(),
});
export type WokaTexture = z.infer<typeof wokaTexture>;
const wokaTextureCollection = z.object({
name: z.string(),
textures: z.array(wokaTexture),
});
export type WokaTextureCollection = z.infer<typeof wokaTextureCollection>;
const wokaPartType = z.object({
collections: z.array(wokaTextureCollection),
required: z.boolean().optional(),
});
export type WokaPartType = z.infer<typeof wokaPartType>;
export const wokaList = z.record(wokaPartType);
export type WokaList = z.infer<typeof wokaList>;
export const wokaPartNames = ["woka", "body", "eyes", "hair", "clothes", "hat", "accessory"];
export const isWokaDetail = new tg.IsInterface()
.withProperties({
id: tg.isString,
})
.withOptionalProperties({
url: tg.isString,
layer: tg.isString,
})
.get();
export type WokaDetail = tg.GuardedType<typeof isWokaDetail>;
export type WokaDetailsResult = WokaDetail[];
+1 -1
View File
@@ -1,4 +1,4 @@
import { PositionInterface } from "_Model/PositionInterface";
import { PositionInterface } from "../Model/PositionInterface";
/**
* A physical object that can be placed into a Zone
+2 -2
View File
@@ -9,8 +9,8 @@
* number of players around the current player.
*/
import { Zone, ZoneEventListener } from "./Zone";
import { ViewportInterface } from "_Model/Websocket/ViewportMessage";
import { ExSocketInterface } from "_Model/Websocket/ExSocketInterface";
import { ViewportInterface } from "../Model/Websocket/ViewportMessage";
import { ExSocketInterface } from "../Model/Websocket/ExSocketInterface";
//import Debug from "debug";
//const debug = Debug('positiondispatcher');
+5 -14
View File
@@ -1,28 +1,18 @@
import { ExSocketInterface } from "_Model/Websocket/ExSocketInterface";
import { ExSocketInterface } from "../Model/Websocket/ExSocketInterface";
import { PositionDispatcher } from "./PositionDispatcher";
import { ViewportInterface } from "_Model/Websocket/ViewportMessage";
import { ViewportInterface } from "../Model/Websocket/ViewportMessage";
import { arrayIntersect } from "../Services/ArrayHelper";
import { GroupDescriptor, UserDescriptor, ZoneEventListener } from "_Model/Zone";
import { ZoneEventListener } from "../Model/Zone";
import { apiClientRepository } from "../Services/ApiClientRepository";
import {
BatchToPusherMessage,
BatchToPusherRoomMessage,
EmoteEventMessage,
ErrorMessage,
GroupLeftZoneMessage,
GroupUpdateZoneMessage,
RoomMessage,
SubMessage,
UserJoinedZoneMessage,
UserLeftZoneMessage,
UserMovedMessage,
VariableMessage,
VariableWithTagMessage,
ZoneMessage,
} from "../Messages/generated/messages_pb";
import Debug from "debug";
import { ClientReadableStream } from "grpc";
import { ExAdminSocketInterface } from "_Model/Websocket/ExAdminSocketInterface";
const debug = Debug("room");
@@ -121,7 +111,7 @@ export class PusherRoom {
}
});
this.backConnection.on("error", (e) => {
this.backConnection.on("error", (err) => {
if (!this.isClosing) {
debug("Error on back connection");
this.close();
@@ -129,6 +119,7 @@ export class PusherRoom {
for (const listener of this.listeners) {
listener.disconnecting = true;
listener.end(1011, "Connection error between pusher and back server");
console.error("Connection error between pusher and back server", err);
}
}
});
@@ -1,30 +1,24 @@
import * as tg from "generic-type-guard";
import { z } from "zod";
export const isBanBannedAdminMessageInterface = new tg.IsInterface()
.withProperties({
type: tg.isSingletonStringUnion("ban", "banned"),
message: tg.isString,
userUuid: tg.isString,
})
.get();
export const isBanBannedAdminMessageInterface = z.object({
type: z.enum(["ban", "banned"]),
message: z.string(),
userUuid: z.string(),
});
export const isUserMessageAdminMessageInterface = new tg.IsInterface()
.withProperties({
event: tg.isSingletonString("user-message"),
message: isBanBannedAdminMessageInterface,
world: tg.isString,
jwt: tg.isString,
})
.get();
export const isUserMessageAdminMessageInterface = z.object({
event: z.enum(["user-message"]),
message: isBanBannedAdminMessageInterface,
world: z.string(),
jwt: z.string(),
});
export const isListenRoomsMessageInterface = new tg.IsInterface()
.withProperties({
event: tg.isSingletonString("listen"),
roomIds: tg.isArray(tg.isString),
jwt: tg.isString,
})
.get();
export const isListenRoomsMessageInterface = z.object({
event: z.enum(["listen"]),
roomIds: z.array(z.string()),
jwt: z.string(),
});
export const isAdminMessageInterface = tg.isUnion(isUserMessageAdminMessageInterface, isListenRoomsMessageInterface);
export const isAdminMessageInterface = z.union([isUserMessageAdminMessageInterface, isListenRoomsMessageInterface]);
export type AdminMessageInterface = tg.GuardedType<typeof isAdminMessageInterface>;
export type AdminMessageInterface = z.infer<typeof isAdminMessageInterface>;
@@ -1,17 +1,6 @@
import { PointInterface } from "./PointInterface";
import { Identificable } from "./Identificable";
import { ViewportInterface } from "_Model/Websocket/ViewportMessage";
import {
AdminPusherToBackMessage,
BatchMessage,
PusherToBackMessage,
ServerToAdminClientMessage,
ServerToClientMessage,
SubMessage,
} from "../../Messages/generated/messages_pb";
import { AdminPusherToBackMessage, ServerToAdminClientMessage } from "../../Messages/generated/messages_pb";
import { compressors } from "hyper-express";
import { ClientDuplexStream } from "grpc";
import { Zone } from "_Model/Zone";
export type AdminConnection = ClientDuplexStream<AdminPusherToBackMessage, ServerToAdminClientMessage>;
@@ -1,6 +1,6 @@
import { PointInterface } from "./PointInterface";
import { Identificable } from "./Identificable";
import { ViewportInterface } from "_Model/Websocket/ViewportMessage";
import { ViewportInterface } from "../../Model/Websocket/ViewportMessage";
import {
BatchMessage,
CompanionMessage,
@@ -9,7 +9,7 @@ import {
SubMessage,
} from "../../Messages/generated/messages_pb";
import { ClientDuplexStream } from "grpc";
import { Zone } from "_Model/Zone";
import { Zone } from "../../Model/Zone";
import { compressors } from "hyper-express";
import { WokaDetail } from "../../Messages/JsonMessages/PlayerTextures";
+9 -10
View File
@@ -1,11 +1,10 @@
import * as tg from "generic-type-guard";
import { z } from "zod";
export const isItemEventMessageInterface = new tg.IsInterface()
.withProperties({
itemId: tg.isNumber,
event: tg.isString,
state: tg.isUnknown,
parameters: tg.isUnknown,
})
.get();
export type ItemEventMessageInterface = tg.GuardedType<typeof isItemEventMessageInterface>;
export const isItemEventMessageInterface = z.object({
itemId: z.number(),
event: z.string(),
state: z.unknown(),
parameters: z.unknown(),
});
export type ItemEventMessageInterface = z.infer<typeof isItemEventMessageInterface>;
+8 -16
View File
@@ -1,18 +1,10 @@
import * as tg from "generic-type-guard";
import { z } from "zod";
/*export interface PointInterface {
readonly x: number;
readonly y: number;
readonly direction: string;
readonly moving: boolean;
}*/
export const isPointInterface = z.object({
x: z.number(),
y: z.number(),
direction: z.string(),
moving: z.boolean(),
});
export const isPointInterface = new tg.IsInterface()
.withProperties({
x: tg.isNumber,
y: tg.isNumber,
direction: tg.isString,
moving: tg.isBoolean,
})
.get();
export type PointInterface = tg.GuardedType<typeof isPointInterface>;
export type PointInterface = z.infer<typeof isPointInterface>;
+2 -3
View File
@@ -5,10 +5,9 @@ import {
PointMessage,
PositionMessage,
} from "../../Messages/generated/messages_pb";
import { ExSocketInterface } from "_Model/Websocket/ExSocketInterface";
import Direction = PositionMessage.Direction;
import { ItemEventMessageInterface } from "_Model/Websocket/ItemEventMessage";
import { PositionInterface } from "_Model/PositionInterface";
import { ItemEventMessageInterface } from "../../Model/Websocket/ItemEventMessage";
import { PositionInterface } from "../../Model/PositionInterface";
import { WokaDetail } from "../../Messages/JsonMessages/PlayerTextures";
export class ProtobufUtils {
+9 -10
View File
@@ -1,11 +1,10 @@
import * as tg from "generic-type-guard";
import { z } from "zod";
export const isViewport = new tg.IsInterface()
.withProperties({
left: tg.isNumber,
top: tg.isNumber,
right: tg.isNumber,
bottom: tg.isNumber,
})
.get();
export type ViewportInterface = tg.GuardedType<typeof isViewport>;
export const isViewport = z.object({
left: z.number(),
top: z.number(),
right: z.number(),
bottom: z.number(),
});
export type ViewportInterface = z.infer<typeof isViewport>;
+4 -4
View File
@@ -20,7 +20,7 @@ import {
SetPlayerDetailsMessage,
} from "../Messages/generated/messages_pb";
import { ClientReadableStream } from "grpc";
import { PositionDispatcher } from "_Model/PositionDispatcher";
import { PositionDispatcher } from "../Model/PositionDispatcher";
import Debug from "debug";
import { BoolValue, UInt32Value } from "google-protobuf/google/protobuf/wrappers_pb";
@@ -427,7 +427,7 @@ export class Zone {
}
}
for (const [groupId, group] of this.groups.entries()) {
for (const group of this.groups.values()) {
this.socketListener.onGroupEnters(group, listener);
}
@@ -436,13 +436,13 @@ export class Zone {
}
public stopListening(listener: ExSocketInterface): void {
for (const [userId, user] of this.users.entries()) {
for (const userId of this.users.keys()) {
if (userId !== listener.userId) {
this.socketListener.onUserLeaves(userId, listener);
}
}
for (const [groupId, group] of this.groups.entries()) {
for (const groupId of this.groups.keys()) {
this.socketListener.onGroupLeaves(groupId, listener);
}
+49 -34
View File
@@ -1,10 +1,9 @@
import { ADMIN_API_TOKEN, ADMIN_API_URL, ADMIN_URL, OPID_PROFILE_SCREEN_PROVIDER } from "../Enum/EnvironmentVariable";
import { ADMIN_API_TOKEN, ADMIN_API_URL, OPID_PROFILE_SCREEN_PROVIDER } from "../Enum/EnvironmentVariable";
import Axios, { AxiosResponse } from "axios";
import { isMapDetailsData, MapDetailsData } from "../Messages/JsonMessages/MapDetailsData";
import { isRoomRedirect, RoomRedirect } from "../Messages/JsonMessages/RoomRedirect";
import { AdminApiData, isAdminApiData } from "../Messages/JsonMessages/AdminApiData";
import * as tg from "generic-type-guard";
import { isNumber } from "generic-type-guard";
import { z } from "zod";
import { isWokaDetail } from "../Messages/JsonMessages/PlayerTextures";
import qs from "qs";
@@ -13,22 +12,18 @@ export interface AdminBannedData {
message: string;
}
const isFetchMemberDataByUuidResponse = new tg.IsInterface()
.withProperties({
email: tg.isString,
userUuid: tg.isString,
tags: tg.isArray(tg.isString),
visitCardUrl: tg.isNullable(tg.isString),
textures: tg.isArray(isWokaDetail),
messages: tg.isArray(tg.isUnknown),
})
.withOptionalProperties({
anonymous: tg.isBoolean,
userRoomToken: tg.isString,
})
.get();
export const isFetchMemberDataByUuidResponse = z.object({
email: z.string(),
userUuid: z.string(),
tags: z.array(z.string()),
visitCardUrl: z.nullable(z.string()),
textures: z.array(isWokaDetail),
messages: z.array(z.unknown()),
anonymous: z.optional(z.boolean()),
userRoomToken: z.optional(z.string()),
});
export type FetchMemberDataByUuidResponse = tg.GuardedType<typeof isFetchMemberDataByUuidResponse>;
export type FetchMemberDataByUuidResponse = z.infer<typeof isFetchMemberDataByUuidResponse>;
class AdminApi {
private locale: string = "en";
@@ -55,13 +50,23 @@ class AdminApi {
headers: { Authorization: `${ADMIN_API_TOKEN}`, "Accept-Language": this.locale },
params,
});
if (!isMapDetailsData(res.data) && !isRoomRedirect(res.data)) {
throw new Error(
"Invalid answer received from the admin for the /api/map endpoint. Received: " +
JSON.stringify(res.data)
);
const mapDetailData = isMapDetailsData.safeParse(res.data);
const roomRedirect = isRoomRedirect.safeParse(res.data);
if (mapDetailData.success) {
return mapDetailData.data;
}
return res.data;
if (roomRedirect.success) {
return roomRedirect.data;
}
console.error(mapDetailData.error.issues);
console.error(roomRedirect.error.issues);
throw new Error(
"Invalid answer received from the admin for the /api/map endpoint. Received: " + JSON.stringify(res.data)
);
}
async fetchMemberDataByUuid(
@@ -85,13 +90,18 @@ class AdminApi {
return qs.stringify(p, { arrayFormat: "brackets" });
},
});
if (!isFetchMemberDataByUuidResponse(res.data)) {
throw new Error(
"Invalid answer received from the admin for the /api/room/access endpoint. Received: " +
JSON.stringify(res.data)
);
const fetchMemberDataByUuidResponse = isFetchMemberDataByUuidResponse.safeParse(res.data);
if (fetchMemberDataByUuidResponse.success) {
return fetchMemberDataByUuidResponse.data;
}
return res.data;
console.error(fetchMemberDataByUuidResponse.error.issues);
throw new Error(
"Invalid answer received from the admin for the /api/room/access endpoint. Received: " +
JSON.stringify(res.data)
);
}
async fetchMemberDataByToken(organizationMemberToken: string, playUri: string | null): Promise<AdminApiData> {
@@ -103,11 +113,16 @@ class AdminApi {
params: { playUri },
headers: { Authorization: `${ADMIN_API_TOKEN}`, "Accept-Language": this.locale },
});
if (!isAdminApiData(res.data)) {
console.error("Message received from /api/login-url is not in the expected format. Message: ", res.data);
throw new Error("Message received from /api/login-url is not in the expected format.");
const adminApiData = isAdminApiData.safeParse(res.data);
if (adminApiData.success) {
return adminApiData.data;
}
return res.data;
console.error(adminApiData.error.issues);
console.error("Message received from /api/login-url is not in the expected format. Message: ", res.data);
throw new Error("Message received from /api/login-url is not in the expected format.");
}
reportPlayer(
+1 -1
View File
@@ -1,4 +1,4 @@
import { ExSocketInterface } from "_Model/Websocket/ExSocketInterface";
import { ExSocketInterface } from "../Model/Websocket/ExSocketInterface";
import { BatchMessage, ErrorMessage, ServerToClientMessage, SubMessage } from "../Messages/generated/messages_pb";
import { WebSocket } from "uWebSockets.js";
+3 -2
View File
@@ -1,10 +1,11 @@
import { WokaDetail, WokaDetailsResult, WokaList, wokaPartNames } from "../Messages/JsonMessages/PlayerTextures";
import { WokaDetail, WokaList, wokaPartNames } from "../Messages/JsonMessages/PlayerTextures";
import { WokaServiceInterface } from "./WokaServiceInterface";
class LocalWokaService implements WokaServiceInterface {
/**
* Returns the list of all available Wokas & Woka Parts for the current user.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async getWokaList(roomId: string, token: string): Promise<WokaList | undefined> {
const wokaData: WokaList = await require("../../data/woka.json");
if (!wokaData) {
@@ -21,7 +22,7 @@ class LocalWokaService implements WokaServiceInterface {
*
* If one of the textures cannot be found, undefined is returned (and the user should be redirected to Woka choice page!)
*/
async fetchWokaDetails(textureIds: string[]): Promise<WokaDetailsResult | undefined> {
async fetchWokaDetails(textureIds: string[]): Promise<WokaDetail[] | undefined> {
const wokaData: WokaList = await require("../../data/woka.json");
const textures = new Map<
string,
+9 -10
View File
@@ -50,13 +50,11 @@ import Jwt from "jsonwebtoken";
import { clientEventsEmitter } from "./ClientEventsEmitter";
import { gaugeManager } from "./GaugeManager";
import { apiClientRepository } from "./ApiClientRepository";
import { GroupDescriptor, UserDescriptor, ZoneEventListener } from "_Model/Zone";
import { GroupDescriptor, UserDescriptor, ZoneEventListener } from "../Model/Zone";
import Debug from "debug";
import { ExAdminSocketInterface } from "_Model/Websocket/ExAdminSocketInterface";
import { WebSocket } from "uWebSockets.js";
import { isRoomRedirect } from "../Messages/JsonMessages/RoomRedirect";
//import { CharacterTexture } from "../Messages/JsonMessages/CharacterTexture";
import { ExAdminSocketInterface } from "../Model/Websocket/ExAdminSocketInterface";
import { compressors } from "hyper-express";
import { isMapDetailsData } from "../Messages/JsonMessages/MapDetailsData";
const debug = Debug("socket");
@@ -447,13 +445,14 @@ export class SocketManager implements ZoneEventListener {
public async updateRoomWithAdminData(room: PusherRoom): Promise<void> {
const data = await adminApi.fetchMapDetails(room.roomUrl);
const mapDetailsData = isMapDetailsData.safeParse(data);
if (isRoomRedirect(data)) {
if (mapDetailsData.success) {
room.tags = mapDetailsData.data.tags;
room.policyType = Number(mapDetailsData.data.policy_type);
} else {
// TODO: if the updated room data is actually a redirect, we need to take everybody on the map
// and redirect everybody to the new location (so we need to close the connection for everybody)
} else {
room.tags = data.tags;
room.policyType = Number(data.policy_type);
}
}
@@ -715,7 +714,7 @@ export class SocketManager implements ZoneEventListener {
for (const roomUrl of tabUrlRooms) {
const apiRoom = await apiClientRepository.getClient(roomUrl);
roomMessage.setRoomid(roomUrl);
apiRoom.sendAdminMessageToRoom(roomMessage, (response) => {
apiRoom.sendAdminMessageToRoom(roomMessage, () => {
return;
});
}