Refactoring Room.ts to fetch map url automatically from ID

This commit is contained in:
David Négrier 2020-10-13 16:46:46 +02:00
parent 0580c692d1
commit aee06da7f9
7 changed files with 94 additions and 56 deletions

View file

@ -23,33 +23,33 @@ class ConnectionManager {
const data = await Axios.post(`${API_URL}/register`, {organizationMemberToken}).then(res => res.data);
this.localUser = new LocalUser(data.userUuid, data.authToken);
localUserStore.saveUser(this.localUser);
const organizationSlug = data.organizationSlug;
const worldSlug = data.worldSlug;
const roomSlug = data.roomSlug;
urlManager.editUrlForRoom(roomSlug, organizationSlug, worldSlug);
const room = new Room(window.location.pathname, data.mapUrlStart)
const room = new Room(window.location.pathname);
return Promise.resolve(room);
} else if (connexionType === GameConnexionTypes.anonymous) {
const localUser = localUserStore.getLocalUser();
if (localUser) {
if (localUser && localUser.jwtToken && localUser.uuid) {
this.localUser = localUser
} else {
const data = await Axios.post(`${API_URL}/anonymLogin`).then(res => res.data);
this.localUser = new LocalUser(data.userUuid, data.authToken);
localUserStore.saveUser(this.localUser);
}
const room = new Room(window.location.pathname, urlManager.getAnonymousMapUrlStart())
const room = new Room(window.location.pathname);
return Promise.resolve(room);
} else if (connexionType == GameConnexionTypes.organization) {
const localUser = localUserStore.getLocalUser();
if (localUser) {
this.localUser = localUser
//todo: ask the node api for the correct starting map Url from its slug
return Promise.reject('Case not handled: need to get the map\'s url from its slug');
const room = new Room(window.location.pathname);
return Promise.resolve(room);
} else {
//todo: find some kind of fallback?
return Promise.reject('Could not find a user in localstorage');

View file

@ -1,10 +1,67 @@
import Axios from "axios";
import {API_URL} from "../Enum/EnvironmentVariable";
export class Room {
public ID: string;
public url: string
constructor(ID: string, url: string) {
this.ID = ID;
this.url = url;
public readonly id: string;
public readonly isPublic: boolean;
private mapUrl: string|undefined;
//public url: string
constructor(id: string/*, url: string*/) {
if (id.startsWith('/')) {
id = id.substr(1);
}
this.id = id;
if (id.startsWith('_/')) {
this.isPublic = true;
} else if (id.startsWith('@/')) {
this.isPublic = false;
} else {
throw new Error('Invalid room ID');
}
}
}
public async getMapUrl(): Promise<string> {
return new Promise<string>(async (resolve, reject) => {
if (this.mapUrl !== undefined) {
resolve(this.mapUrl);
return;
}
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(this.mapUrl);
return;
} else {
// We have a private ID, we need to query the map URL from the server.
const urlParts = this.parsePrivateUrl(this.id);
const data:any = await Axios.get(`${API_URL}/map`, {
params: urlParts
});
console.log('Map ', this.id, ' resolves to URL ', data.data.mapUrl);
resolve(data.data.mapUrl);
return;
}
});
}
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);
}
let results: { organizationSlug: string, worldSlug: string, roomSlug?: string } = {
organizationSlug: match[1],
worldSlug: match[2],
}
if (match[3] !== undefined) {
results.roomSlug = match[3];
}
return results;
}
}

View file

@ -11,7 +11,6 @@ import {
RoomJoinedMessage,
ServerToClientMessage,
SetPlayerDetailsMessage,
SetUserIdMessage,
SilentMessage, StopGlobalMessage,
UserJoinedMessage,
UserLeftMessage,
@ -58,7 +57,7 @@ export class RoomConnection implements RoomConnection {
let url = API_URL.replace('http://', 'ws://').replace('https://', 'wss://');
url += '/room';
url += '?roomId='+(roomId ?encodeURIComponent(roomId):'');
url += '?token='+(token ?encodeURIComponent(token):'');
url += '&token='+(token ?encodeURIComponent(token):'');
url += '&name='+encodeURIComponent(name);
for (const layer of characterLayers) {
url += '&characterLayers='+encodeURIComponent(layer);
@ -124,13 +123,13 @@ export class RoomConnection implements RoomConnection {
items[item.getItemid()] = JSON.parse(item.getStatejson());
}
this.userId = roomJoinedMessage.getCurrentuserid();
this.dispatch(EventMessage.START_ROOM, {
users,
groups,
items
});
} else if (message.hasSetuseridmessage()) {
this.userId = (message.getSetuseridmessage() as SetUserIdMessage).getUserid();
} else if (message.hasErrormessage()) {
console.error(EventMessage.MESSAGE_ERROR, message.getErrormessage()?.getMessage());
} else if (message.hasWebrtcsignaltoclientmessage()) {

View file

@ -17,7 +17,8 @@ export class GameManager {
public async init(scenePlugin: Phaser.Scenes.ScenePlugin) {
this.startRoom = await connectionManager.initGameConnexion();
this.loadMap(this.startRoom.url, this.startRoom.ID, scenePlugin);
const url = await this.startRoom.getMapUrl();
this.loadMap(url, this.startRoom.id, scenePlugin);
}
public setPlayerName(name: string): void {
@ -58,9 +59,10 @@ export class GameManager {
return mapUrlStart.substring(startPos, endPos);
}
public goToStartingMap(scenePlugin: Phaser.Scenes.ScenePlugin) {
console.log('Starting scene '+this.startRoom.url);
scenePlugin.start(this.startRoom.url, {startLayerName: 'global'});
public async goToStartingMap(scenePlugin: Phaser.Scenes.ScenePlugin) {
const url = await this.startRoom.getMapUrl();
console.log('Starting scene '+url);
scenePlugin.start(url, {startLayerName: 'global'});
}
}

View file

@ -23,13 +23,6 @@ class UrlManager {
}
}
public getAnonymousMapUrlStart():string {
const match = /\/_\/global\/(.+)/.exec(window.location.pathname.toString())
if (!match) throw new Error('Could not extract startmap url from'+window.location.pathname);
return window.location.protocol+'//'+match[1];
}
public getOrganizationToken(): string|null {
const match = /\/register\/(.+)/.exec(window.location.pathname.toString());
return match ? match [1] : null;