Merge branch 'develop' of github.com:thecodingmachine/workadventure into scripting_api_room_metadata
This commit is contained in:
commit
5c7ea7b258
66 changed files with 1296 additions and 967 deletions
|
@ -1,92 +1,107 @@
|
|||
import Axios from "axios";
|
||||
import {PUSHER_URL, START_ROOM_URL} from "../Enum/EnvironmentVariable";
|
||||
import {RoomConnection} from "./RoomConnection";
|
||||
import type {OnConnectInterface, PositionInterface, ViewportInterface} from "./ConnexionModels";
|
||||
import {GameConnexionTypes, urlManager} from "../Url/UrlManager";
|
||||
import {localUserStore} from "./LocalUserStore";
|
||||
import {CharacterTexture, LocalUser} from "./LocalUser";
|
||||
import {Room} from "./Room";
|
||||
|
||||
import { PUSHER_URL, START_ROOM_URL } from "../Enum/EnvironmentVariable";
|
||||
import { RoomConnection } from "./RoomConnection";
|
||||
import type { OnConnectInterface, PositionInterface, ViewportInterface } from "./ConnexionModels";
|
||||
import { GameConnexionTypes, urlManager } from "../Url/UrlManager";
|
||||
import { localUserStore } from "./LocalUserStore";
|
||||
import { CharacterTexture, LocalUser } from "./LocalUser";
|
||||
import { Room } from "./Room";
|
||||
|
||||
class ConnectionManager {
|
||||
private localUser!:LocalUser;
|
||||
private localUser!: LocalUser;
|
||||
|
||||
private connexionType?: GameConnexionTypes
|
||||
private reconnectingTimeout: NodeJS.Timeout|null = null;
|
||||
private _unloading:boolean = false;
|
||||
private connexionType?: GameConnexionTypes;
|
||||
private reconnectingTimeout: NodeJS.Timeout | null = null;
|
||||
private _unloading: boolean = false;
|
||||
|
||||
get unloading () {
|
||||
get unloading() {
|
||||
return this._unloading;
|
||||
}
|
||||
|
||||
constructor() {
|
||||
window.addEventListener('beforeunload', () => {
|
||||
window.addEventListener("beforeunload", () => {
|
||||
this._unloading = true;
|
||||
if (this.reconnectingTimeout) clearTimeout(this.reconnectingTimeout)
|
||||
})
|
||||
if (this.reconnectingTimeout) clearTimeout(this.reconnectingTimeout);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Tries to login to the node server and return the starting map url to be loaded
|
||||
*/
|
||||
public async initGameConnexion(): Promise<Room> {
|
||||
|
||||
const connexionType = urlManager.getGameConnexionType();
|
||||
this.connexionType = connexionType;
|
||||
if(connexionType === GameConnexionTypes.register) {
|
||||
const organizationMemberToken = urlManager.getOrganizationToken();
|
||||
const data = await Axios.post(`${PUSHER_URL}/register`, {organizationMemberToken}).then(res => res.data);
|
||||
if (connexionType === GameConnexionTypes.register) {
|
||||
const organizationMemberToken = urlManager.getOrganizationToken();
|
||||
const data = await Axios.post(`${PUSHER_URL}/register`, { organizationMemberToken }).then(
|
||||
(res) => res.data
|
||||
);
|
||||
this.localUser = new LocalUser(data.userUuid, data.authToken, data.textures);
|
||||
localUserStore.saveUser(this.localUser);
|
||||
|
||||
const organizationSlug = data.organizationSlug;
|
||||
const worldSlug = data.worldSlug;
|
||||
const roomSlug = data.roomSlug;
|
||||
const roomUrl = data.roomUrl;
|
||||
|
||||
const room = new Room('/@/'+organizationSlug+'/'+worldSlug+'/'+roomSlug + window.location.search + window.location.hash);
|
||||
const room = await Room.createRoom(
|
||||
new URL(
|
||||
window.location.protocol +
|
||||
"//" +
|
||||
window.location.host +
|
||||
roomUrl +
|
||||
window.location.search +
|
||||
window.location.hash
|
||||
)
|
||||
);
|
||||
urlManager.pushRoomIdToUrl(room);
|
||||
return Promise.resolve(room);
|
||||
} else if (connexionType === GameConnexionTypes.organization || connexionType === GameConnexionTypes.anonymous || connexionType === GameConnexionTypes.empty) {
|
||||
|
||||
} else if (
|
||||
connexionType === GameConnexionTypes.organization ||
|
||||
connexionType === GameConnexionTypes.anonymous ||
|
||||
connexionType === GameConnexionTypes.empty
|
||||
) {
|
||||
let localUser = localUserStore.getLocalUser();
|
||||
if (localUser && localUser.jwtToken && localUser.uuid && localUser.textures) {
|
||||
this.localUser = localUser;
|
||||
try {
|
||||
await this.verifyToken(localUser.jwtToken);
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
// If the token is invalid, let's generate an anonymous one.
|
||||
console.error('JWT token invalid. Did it expire? Login anonymously instead.');
|
||||
console.error("JWT token invalid. Did it expire? Login anonymously instead.");
|
||||
await this.anonymousLogin();
|
||||
}
|
||||
}else{
|
||||
} else {
|
||||
await this.anonymousLogin();
|
||||
}
|
||||
|
||||
localUser = localUserStore.getLocalUser();
|
||||
if(!localUser){
|
||||
if (!localUser) {
|
||||
throw "Error to store local user data";
|
||||
}
|
||||
|
||||
let roomId: string;
|
||||
let roomPath: string;
|
||||
if (connexionType === GameConnexionTypes.empty) {
|
||||
roomId = START_ROOM_URL;
|
||||
roomPath = window.location.protocol + "//" + window.location.host + START_ROOM_URL;
|
||||
} else {
|
||||
roomId = window.location.pathname + window.location.search + window.location.hash;
|
||||
roomPath =
|
||||
window.location.protocol +
|
||||
"//" +
|
||||
window.location.host +
|
||||
window.location.pathname +
|
||||
window.location.search +
|
||||
window.location.hash;
|
||||
}
|
||||
|
||||
//get detail map for anonymous login and set texture in local storage
|
||||
const room = new Room(roomId);
|
||||
const mapDetail = await room.getMapDetail();
|
||||
if(mapDetail.textures != undefined && mapDetail.textures.length > 0) {
|
||||
const room = await Room.createRoom(new URL(roomPath));
|
||||
if (room.textures != undefined && room.textures.length > 0) {
|
||||
//check if texture was changed
|
||||
if(localUser.textures.length === 0){
|
||||
localUser.textures = mapDetail.textures;
|
||||
}else{
|
||||
mapDetail.textures.forEach((newTexture) => {
|
||||
if (localUser.textures.length === 0) {
|
||||
localUser.textures = room.textures;
|
||||
} else {
|
||||
room.textures.forEach((newTexture) => {
|
||||
const alreadyExistTexture = localUser?.textures.find((c) => newTexture.id === c.id);
|
||||
if(localUser?.textures.findIndex((c) => newTexture.id === c.id) !== -1){
|
||||
if (localUser?.textures.findIndex((c) => newTexture.id === c.id) !== -1) {
|
||||
return;
|
||||
}
|
||||
localUser?.textures.push(newTexture)
|
||||
localUser?.textures.push(newTexture);
|
||||
});
|
||||
}
|
||||
this.localUser = localUser;
|
||||
|
@ -95,55 +110,79 @@ class ConnectionManager {
|
|||
return Promise.resolve(room);
|
||||
}
|
||||
|
||||
return Promise.reject(new Error('Invalid URL'));
|
||||
return Promise.reject(new Error("Invalid URL"));
|
||||
}
|
||||
|
||||
private async verifyToken(token: string): Promise<void> {
|
||||
await Axios.get(`${PUSHER_URL}/verify`, {params: {token}});
|
||||
await Axios.get(`${PUSHER_URL}/verify`, { params: { token } });
|
||||
}
|
||||
|
||||
public async anonymousLogin(isBenchmark: boolean = false): Promise<void> {
|
||||
const data = await Axios.post(`${PUSHER_URL}/anonymLogin`).then(res => res.data);
|
||||
const data = await Axios.post(`${PUSHER_URL}/anonymLogin`).then((res) => res.data);
|
||||
this.localUser = new LocalUser(data.userUuid, data.authToken, []);
|
||||
if (!isBenchmark) { // In benchmark, we don't have a local storage.
|
||||
if (!isBenchmark) {
|
||||
// In benchmark, we don't have a local storage.
|
||||
localUserStore.saveUser(this.localUser);
|
||||
}
|
||||
}
|
||||
|
||||
public initBenchmark(): void {
|
||||
this.localUser = new LocalUser('', 'test', []);
|
||||
this.localUser = new LocalUser("", "test", []);
|
||||
}
|
||||
|
||||
public connectToRoomSocket(roomId: string, name: string, characterLayers: string[], position: PositionInterface, viewport: ViewportInterface, companion: string|null): Promise<OnConnectInterface> {
|
||||
public connectToRoomSocket(
|
||||
roomUrl: string,
|
||||
name: string,
|
||||
characterLayers: string[],
|
||||
position: PositionInterface,
|
||||
viewport: ViewportInterface,
|
||||
companion: string | null
|
||||
): Promise<OnConnectInterface> {
|
||||
return new Promise<OnConnectInterface>((resolve, reject) => {
|
||||
const connection = new RoomConnection(this.localUser.jwtToken, roomId, name, characterLayers, position, viewport, companion);
|
||||
const connection = new RoomConnection(
|
||||
this.localUser.jwtToken,
|
||||
roomUrl,
|
||||
name,
|
||||
characterLayers,
|
||||
position,
|
||||
viewport,
|
||||
companion
|
||||
);
|
||||
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);
|
||||
});
|
||||
|
||||
connection.onConnectingError((event: CloseEvent) => {
|
||||
console.log('An error occurred while connecting to socket server. Retrying');
|
||||
reject(new Error('An error occurred while connecting to socket server. Retrying. Code: '+event.code+', Reason: '+event.reason));
|
||||
console.log("An error occurred while connecting to socket server. Retrying");
|
||||
reject(
|
||||
new Error(
|
||||
"An error occurred while connecting to socket server. Retrying. Code: " +
|
||||
event.code +
|
||||
", Reason: " +
|
||||
event.reason
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
connection.onConnect((connect: OnConnectInterface) => {
|
||||
resolve(connect);
|
||||
});
|
||||
|
||||
}).catch((err) => {
|
||||
// Let's retry in 4-6 seconds
|
||||
return new Promise<OnConnectInterface>((resolve, reject) => {
|
||||
this.reconnectingTimeout = setTimeout(() => {
|
||||
//todo: allow a way to break recursion?
|
||||
//todo: find a way to avoid recursive function. Otherwise, the call stack will grow indefinitely.
|
||||
this.connectToRoomSocket(roomId, name, characterLayers, position, viewport, companion).then((connection) => resolve(connection));
|
||||
}, 4000 + Math.floor(Math.random() * 2000) );
|
||||
this.connectToRoomSocket(roomUrl, name, characterLayers, position, viewport, companion).then(
|
||||
(connection) => resolve(connection)
|
||||
);
|
||||
}, 4000 + Math.floor(Math.random() * 2000));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
get getConnexionType(){
|
||||
get getConnexionType() {
|
||||
return this.connexionType;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,91 +3,103 @@ import { PUSHER_URL } from "../Enum/EnvironmentVariable";
|
|||
import type { CharacterTexture } from "./LocalUser";
|
||||
|
||||
export class MapDetail {
|
||||
constructor(public readonly mapUrl: string, public readonly textures: CharacterTexture[] | undefined) {
|
||||
}
|
||||
constructor(public readonly mapUrl: string, public readonly textures: CharacterTexture[] | undefined) {}
|
||||
}
|
||||
|
||||
export interface RoomRedirect {
|
||||
redirectUrl: string;
|
||||
}
|
||||
|
||||
export class Room {
|
||||
public readonly id: string;
|
||||
public readonly isPublic: boolean;
|
||||
private mapUrl: string | undefined;
|
||||
private textures: CharacterTexture[] | undefined;
|
||||
private _mapUrl: string | undefined;
|
||||
private _textures: CharacterTexture[] | undefined;
|
||||
private instance: string | undefined;
|
||||
private _search: URLSearchParams;
|
||||
private readonly _search: URLSearchParams;
|
||||
|
||||
constructor(id: string) {
|
||||
const url = new URL(id, 'https://example.com');
|
||||
private constructor(private roomUrl: URL) {
|
||||
this.id = roomUrl.pathname;
|
||||
|
||||
this.id = url.pathname;
|
||||
|
||||
if (this.id.startsWith('/')) {
|
||||
if (this.id.startsWith("/")) {
|
||||
this.id = this.id.substr(1);
|
||||
}
|
||||
if (this.id.startsWith('_/')) {
|
||||
if (this.id.startsWith("_/")) {
|
||||
this.isPublic = true;
|
||||
} else if (this.id.startsWith('@/')) {
|
||||
} else if (this.id.startsWith("@/")) {
|
||||
this.isPublic = false;
|
||||
} else {
|
||||
throw new Error('Invalid room ID');
|
||||
throw new Error("Invalid room ID");
|
||||
}
|
||||
|
||||
this._search = new URLSearchParams(url.search);
|
||||
this._search = new URLSearchParams(roomUrl.search);
|
||||
}
|
||||
|
||||
public static getIdFromIdentifier(identifier: string, baseUrl: string, currentInstance: string): { roomId: string, hash: string | null } {
|
||||
let roomId = '';
|
||||
let hash = null;
|
||||
if (!identifier.startsWith('/_/') && !identifier.startsWith('/@/')) { //relative file link
|
||||
//Relative identifier can be deep enough to rewrite the base domain, so we cannot use the variable 'baseUrl' as the actual base url for the URL objects.
|
||||
//We instead use 'workadventure' as a dummy base value.
|
||||
const baseUrlObject = new URL(baseUrl);
|
||||
const absoluteExitSceneUrl = new URL(identifier, 'http://workadventure/_/' + currentInstance + '/' + baseUrlObject.hostname + baseUrlObject.pathname);
|
||||
roomId = absoluteExitSceneUrl.pathname; //in case of a relative url, we need to create a public roomId
|
||||
roomId = roomId.substring(1); //remove the leading slash
|
||||
hash = absoluteExitSceneUrl.hash;
|
||||
hash = hash.substring(1); //remove the leading diese
|
||||
if (!hash.length) {
|
||||
hash = null
|
||||
}
|
||||
} else { //absolute room Id
|
||||
const parts = identifier.split('#');
|
||||
roomId = parts[0];
|
||||
roomId = roomId.substring(1); //remove the leading slash
|
||||
if (parts.length > 1) {
|
||||
hash = parts[1]
|
||||
/**
|
||||
* Creates a "Room" object representing the room.
|
||||
* This method will follow room redirects if necessary, so the instance returned is a "real" room.
|
||||
*/
|
||||
public static async createRoom(roomUrl: URL): Promise<Room> {
|
||||
let redirectCount = 0;
|
||||
while (redirectCount < 32) {
|
||||
const room = new Room(roomUrl);
|
||||
const result = await room.getMapDetail();
|
||||
if (result instanceof MapDetail) {
|
||||
return room;
|
||||
}
|
||||
redirectCount++;
|
||||
roomUrl = new URL(result.redirectUrl);
|
||||
}
|
||||
return { roomId, hash }
|
||||
throw new Error("Room resolving seems stuck in a redirect loop after 32 redirect attempts");
|
||||
}
|
||||
|
||||
public async getMapDetail(): Promise<MapDetail> {
|
||||
return new Promise<MapDetail>((resolve, reject) => {
|
||||
if (this.mapUrl !== undefined && this.textures != undefined) {
|
||||
resolve(new MapDetail(this.mapUrl, this.textures));
|
||||
return;
|
||||
}
|
||||
public static getRoomPathFromExitUrl(exitUrl: string, currentRoomUrl: string): URL {
|
||||
const url = new URL(exitUrl, currentRoomUrl);
|
||||
return url;
|
||||
}
|
||||
|
||||
if (this.isPublic) {
|
||||
const match = /_\/[^/]+\/(.+)/.exec(this.id);
|
||||
if (!match) throw new Error('Could not extract url from "' + this.id + '"');
|
||||
this.mapUrl = window.location.protocol + '//' + match[1];
|
||||
resolve(new MapDetail(this.mapUrl, this.textures));
|
||||
return;
|
||||
} else {
|
||||
// We have a private ID, we need to query the map URL from the server.
|
||||
const urlParts = this.parsePrivateUrl(this.id);
|
||||
/**
|
||||
* @deprecated USage of exitSceneUrl is deprecated and therefore, this method is deprecated too.
|
||||
*/
|
||||
public static getRoomPathFromExitSceneUrl(
|
||||
exitSceneUrl: string,
|
||||
currentRoomUrl: string,
|
||||
currentMapUrl: string
|
||||
): URL {
|
||||
const absoluteExitSceneUrl = new URL(exitSceneUrl, currentMapUrl);
|
||||
const baseUrl = new URL(currentRoomUrl);
|
||||
|
||||
Axios.get(`${PUSHER_URL}/map`, {
|
||||
params: urlParts
|
||||
}).then(({ data }) => {
|
||||
console.log('Map ', this.id, ' resolves to URL ', data.mapUrl);
|
||||
resolve(data);
|
||||
return;
|
||||
}).catch((reason) => {
|
||||
reject(reason);
|
||||
});
|
||||
}
|
||||
const currentRoom = new Room(baseUrl);
|
||||
let instance: string = "global";
|
||||
if (currentRoom.isPublic) {
|
||||
instance = currentRoom.instance as string;
|
||||
}
|
||||
|
||||
baseUrl.pathname = "/_/" + instance + "/" + absoluteExitSceneUrl.host + absoluteExitSceneUrl.pathname;
|
||||
if (absoluteExitSceneUrl.hash) {
|
||||
baseUrl.hash = absoluteExitSceneUrl.hash;
|
||||
}
|
||||
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
private async getMapDetail(): Promise<MapDetail | RoomRedirect> {
|
||||
const result = await Axios.get(`${PUSHER_URL}/map`, {
|
||||
params: {
|
||||
playUri: this.roomUrl.toString(),
|
||||
},
|
||||
});
|
||||
|
||||
const data = result.data;
|
||||
if (data.redirectUrl) {
|
||||
return {
|
||||
redirectUrl: data.redirectUrl as string,
|
||||
};
|
||||
}
|
||||
console.log("Map ", this.id, " resolves to URL ", data.mapUrl);
|
||||
this._mapUrl = data.mapUrl;
|
||||
this._textures = data.textures;
|
||||
return new MapDetail(data.mapUrl, data.textures);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -108,21 +120,24 @@ export class Room {
|
|||
} else {
|
||||
const match = /@\/([^/]+)\/([^/]+)\/.+/.exec(this.id);
|
||||
if (!match) throw new Error('Could not extract instance from "' + this.id + '"');
|
||||
this.instance = match[1] + '/' + match[2];
|
||||
this.instance = match[1] + "/" + match[2];
|
||||
return this.instance;
|
||||
}
|
||||
}
|
||||
|
||||
private parsePrivateUrl(url: string): { organizationSlug: string, worldSlug: string, roomSlug?: string } {
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
private parsePrivateUrl(url: string): { organizationSlug: string; worldSlug: string; roomSlug?: string } {
|
||||
const regex = /@\/([^/]+)\/([^/]+)(?:\/([^/]*))?/gm;
|
||||
const match = regex.exec(url);
|
||||
if (!match) {
|
||||
throw new Error('Invalid URL ' + url);
|
||||
throw new Error("Invalid URL " + url);
|
||||
}
|
||||
const results: { organizationSlug: string, worldSlug: string, roomSlug?: string } = {
|
||||
const results: { organizationSlug: string; worldSlug: string; roomSlug?: string } = {
|
||||
organizationSlug: match[1],
|
||||
worldSlug: match[2],
|
||||
}
|
||||
};
|
||||
if (match[3] !== undefined) {
|
||||
results.roomSlug = match[3];
|
||||
}
|
||||
|
@ -130,8 +145,8 @@ export class Room {
|
|||
}
|
||||
|
||||
public isDisconnected(): boolean {
|
||||
const alone = this._search.get('alone');
|
||||
if (alone && alone !== '0' && alone.toLowerCase() !== 'false') {
|
||||
const alone = this._search.get("alone");
|
||||
if (alone && alone !== "0" && alone.toLowerCase() !== "false") {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
|
@ -140,4 +155,32 @@ export class Room {
|
|||
public get search(): URLSearchParams {
|
||||
return this._search;
|
||||
}
|
||||
|
||||
/**
|
||||
* 2 rooms are equal if they share the same path (but not necessarily the same hash)
|
||||
* @param room
|
||||
*/
|
||||
public isEqual(room: Room): boolean {
|
||||
return room.key === this.key;
|
||||
}
|
||||
|
||||
/**
|
||||
* A key representing this room
|
||||
*/
|
||||
public get key(): string {
|
||||
const newUrl = new URL(this.roomUrl.toString());
|
||||
newUrl.hash = "";
|
||||
return newUrl.toString();
|
||||
}
|
||||
|
||||
get textures(): CharacterTexture[] | undefined {
|
||||
return this._textures;
|
||||
}
|
||||
|
||||
get mapUrl(): string {
|
||||
if (!this._mapUrl) {
|
||||
throw new Error("Map URL not fetched yet");
|
||||
}
|
||||
return this._mapUrl;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -76,11 +76,11 @@ export class RoomConnection implements RoomConnection {
|
|||
/**
|
||||
*
|
||||
* @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]"
|
||||
* @param roomUrl The URL of the room in the form "https://example.com/_/[instance]/[map_url]" or "https://example.com/@/[org]/[event]/[map]"
|
||||
*/
|
||||
public constructor(
|
||||
token: string | null,
|
||||
roomId: string,
|
||||
roomUrl: string,
|
||||
name: string,
|
||||
characterLayers: string[],
|
||||
position: PositionInterface,
|
||||
|
@ -93,7 +93,7 @@ export class RoomConnection implements RoomConnection {
|
|||
url += "/";
|
||||
}
|
||||
url += "room";
|
||||
url += "?roomId=" + (roomId ? encodeURIComponent(roomId) : "");
|
||||
url += "?roomId=" + encodeURIComponent(roomUrl);
|
||||
url += "&token=" + (token ? encodeURIComponent(token) : "");
|
||||
url += "&name=" + encodeURIComponent(name);
|
||||
for (const layer of characterLayers) {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue