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
|
@ -5,7 +5,7 @@ export const isSetTilesEvent = tg.isArray(
|
|||
.withProperties({
|
||||
x: tg.isNumber,
|
||||
y: tg.isNumber,
|
||||
tile: tg.isUnion(tg.isNumber, tg.isString),
|
||||
tile: tg.isUnion(tg.isUnion(tg.isNumber, tg.isString), tg.isNull),
|
||||
layer: tg.isString,
|
||||
})
|
||||
.get()
|
||||
|
|
|
@ -2,27 +2,34 @@ import { IframeApiContribution, sendToWorkadventure } from "./IframeApiContribut
|
|||
import type { HasPlayerMovedEvent, HasPlayerMovedEventCallback } from "../Events/HasPlayerMovedEvent";
|
||||
import { Subject } from "rxjs";
|
||||
import { apiCallback } from "./registeredCallbacks";
|
||||
import { getGameState } from "./room";
|
||||
import { isHasPlayerMovedEvent } from "../Events/HasPlayerMovedEvent";
|
||||
|
||||
interface User {
|
||||
id: string | undefined;
|
||||
nickName: string | null;
|
||||
tags: string[];
|
||||
}
|
||||
|
||||
const moveStream = new Subject<HasPlayerMovedEvent>();
|
||||
|
||||
let playerName: string|undefined;
|
||||
let playerName: string | undefined;
|
||||
|
||||
export const setPlayerName = (name: string) => {
|
||||
playerName = name;
|
||||
}
|
||||
};
|
||||
|
||||
let tags: string[]|undefined;
|
||||
let tags: string[] | undefined;
|
||||
|
||||
export const setTags = (_tags: string[]) => {
|
||||
tags = _tags;
|
||||
}
|
||||
};
|
||||
|
||||
let uuid: string|undefined;
|
||||
let uuid: string | undefined;
|
||||
|
||||
export const setUuid = (_uuid: string|undefined) => {
|
||||
export const setUuid = (_uuid: string | undefined) => {
|
||||
uuid = _uuid;
|
||||
}
|
||||
};
|
||||
|
||||
export class WorkadventurePlayerCommands extends IframeApiContribution<WorkadventurePlayerCommands> {
|
||||
callbacks = [
|
||||
|
@ -43,25 +50,27 @@ export class WorkadventurePlayerCommands extends IframeApiContribution<Workadven
|
|||
});
|
||||
}
|
||||
|
||||
get name() : string {
|
||||
get name(): string {
|
||||
if (playerName === undefined) {
|
||||
throw new Error('Player name not initialized yet. You should call WA.player.name within a WA.onInit callback.');
|
||||
throw new Error(
|
||||
"Player name not initialized yet. You should call WA.player.name within a WA.onInit callback."
|
||||
);
|
||||
}
|
||||
return playerName;
|
||||
}
|
||||
|
||||
get tags() : string[] {
|
||||
get tags(): string[] {
|
||||
if (tags === undefined) {
|
||||
throw new Error('Tags not initialized yet. You should call WA.player.tags within a WA.onInit callback.');
|
||||
throw new Error("Tags not initialized yet. You should call WA.player.tags within a WA.onInit callback.");
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
get id() : string|undefined {
|
||||
get id(): string | undefined {
|
||||
// Note: this is not a type, we are checking if playerName is undefined because playerName cannot be undefined
|
||||
// while uuid could.
|
||||
if (playerName === undefined) {
|
||||
throw new Error('Player id not initialized yet. You should call WA.player.id within a WA.onInit callback.');
|
||||
throw new Error("Player id not initialized yet. You should call WA.player.id within a WA.onInit callback.");
|
||||
}
|
||||
return uuid;
|
||||
}
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
import {Observable, Subject} from "rxjs";
|
||||
import { Observable, Subject } from "rxjs";
|
||||
|
||||
import { EnterLeaveEvent, isEnterLeaveEvent } from "../Events/EnterLeaveEvent";
|
||||
|
||||
import {IframeApiContribution, queryWorkadventure, sendToWorkadventure} from "./IframeApiContribution";
|
||||
import { IframeApiContribution, queryWorkadventure, sendToWorkadventure } from "./IframeApiContribution";
|
||||
import { apiCallback } from "./registeredCallbacks";
|
||||
|
||||
import type { ITiledMap } from "../../Phaser/Map/ITiledMap";
|
||||
|
@ -13,21 +13,21 @@ const leaveStreams: Map<string, Subject<EnterLeaveEvent>> = new Map<string, Subj
|
|||
interface TileDescriptor {
|
||||
x: number;
|
||||
y: number;
|
||||
tile: number | string;
|
||||
tile: number | string | null;
|
||||
layer: string;
|
||||
}
|
||||
|
||||
let roomId: string|undefined;
|
||||
let roomId: string | undefined;
|
||||
|
||||
export const setRoomId = (id: string) => {
|
||||
roomId = id;
|
||||
}
|
||||
};
|
||||
|
||||
let mapURL: string|undefined;
|
||||
let mapURL: string | undefined;
|
||||
|
||||
export const setMapURL = (url: string) => {
|
||||
mapURL = url;
|
||||
}
|
||||
};
|
||||
|
||||
export class WorkadventureRoomCommands extends IframeApiContribution<WorkadventureRoomCommands> {
|
||||
callbacks = [
|
||||
|
@ -90,16 +90,18 @@ export class WorkadventureRoomCommands extends IframeApiContribution<Workadventu
|
|||
});
|
||||
}
|
||||
|
||||
get id() : string {
|
||||
get id(): string {
|
||||
if (roomId === undefined) {
|
||||
throw new Error('Room id not initialized yet. You should call WA.room.id within a WA.onInit callback.');
|
||||
throw new Error("Room id not initialized yet. You should call WA.room.id within a WA.onInit callback.");
|
||||
}
|
||||
return roomId;
|
||||
}
|
||||
|
||||
get mapURL() : string {
|
||||
get mapURL(): string {
|
||||
if (mapURL === undefined) {
|
||||
throw new Error('mapURL is not initialized yet. You should call WA.room.mapURL within a WA.onInit callback.');
|
||||
throw new Error(
|
||||
"mapURL is not initialized yet. You should call WA.room.mapURL within a WA.onInit callback."
|
||||
);
|
||||
}
|
||||
return mapURL;
|
||||
}
|
||||
|
|
|
@ -10,12 +10,14 @@
|
|||
import {errorStore} from "../Stores/ErrorStore";
|
||||
import CustomCharacterScene from "./CustomCharacterScene/CustomCharacterScene.svelte";
|
||||
import LoginScene from "./Login/LoginScene.svelte";
|
||||
import Chat from "./Chat/Chat.svelte";
|
||||
import {loginSceneVisibleStore} from "../Stores/LoginSceneStore";
|
||||
import EnableCameraScene from "./EnableCamera/EnableCameraScene.svelte";
|
||||
import VisitCard from "./VisitCard/VisitCard.svelte";
|
||||
import {requestVisitCardsStore} from "../Stores/GameStore";
|
||||
|
||||
import type {Game} from "../Phaser/Game/Game";
|
||||
import {chatVisibilityStore} from "../Stores/ChatStore";
|
||||
import {helpCameraSettingsVisibleStore} from "../Stores/HelpCameraSettingsStore";
|
||||
import HelpCameraSettingsPopup from "./HelpCameraSettings/HelpCameraSettingsPopup.svelte";
|
||||
import AudioPlaying from "./UI/AudioPlaying.svelte";
|
||||
|
@ -61,14 +63,6 @@
|
|||
<AudioPlaying url={$soundPlayingStore} />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!--
|
||||
{#if $menuIconVisible}
|
||||
<div>
|
||||
<MenuIcon />
|
||||
</div>
|
||||
{/if}
|
||||
-->
|
||||
{#if $gameOverlayVisibilityStore}
|
||||
<div>
|
||||
<VideoOverlay></VideoOverlay>
|
||||
|
@ -94,4 +88,7 @@
|
|||
<ErrorDialog></ErrorDialog>
|
||||
</div>
|
||||
{/if}
|
||||
{#if $chatVisibilityStore}
|
||||
<Chat></Chat>
|
||||
{/if}
|
||||
</div>
|
||||
|
|
104
front/src/Components/Chat/Chat.svelte
Normal file
104
front/src/Components/Chat/Chat.svelte
Normal file
|
@ -0,0 +1,104 @@
|
|||
<script lang="ts">
|
||||
import { fly } from 'svelte/transition';
|
||||
import { chatMessagesStore, chatVisibilityStore } from "../../Stores/ChatStore";
|
||||
import ChatMessageForm from './ChatMessageForm.svelte';
|
||||
import ChatElement from './ChatElement.svelte';
|
||||
import { afterUpdate, beforeUpdate } from "svelte";
|
||||
|
||||
let listDom: HTMLElement;
|
||||
let autoscroll: boolean;
|
||||
|
||||
beforeUpdate(() => {
|
||||
autoscroll = listDom && (listDom.offsetHeight + listDom.scrollTop) > (listDom.scrollHeight - 20);
|
||||
});
|
||||
|
||||
afterUpdate(() => {
|
||||
if (autoscroll) listDom.scrollTo(0, listDom.scrollHeight);
|
||||
});
|
||||
|
||||
function closeChat() {
|
||||
chatVisibilityStore.set(false);
|
||||
}
|
||||
function onKeyDown(e:KeyboardEvent) {
|
||||
if (e.key === 'Escape') {
|
||||
closeChat();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window on:keydown={onKeyDown}/>
|
||||
|
||||
|
||||
<aside class="chatWindow" transition:fly="{{ x: -1000, duration: 500 }}">
|
||||
<section class="chatWindowTitle">
|
||||
<h1>Your chat history <span class="float-right" on:click={closeChat}>×</span></h1>
|
||||
|
||||
</section>
|
||||
<section class="messagesList" bind:this={listDom}>
|
||||
<ul>
|
||||
{#each $chatMessagesStore as message, i}
|
||||
<li><ChatElement message={message} line={i}></ChatElement></li>
|
||||
{/each}
|
||||
</ul>
|
||||
</section>
|
||||
<section class="messageForm">
|
||||
<ChatMessageForm></ChatMessageForm>
|
||||
</section>
|
||||
</aside>
|
||||
|
||||
<style lang="scss">
|
||||
h1 {
|
||||
font-family: Lato;
|
||||
|
||||
span.float-right {
|
||||
font-size: 30px;
|
||||
line-height: 25px;
|
||||
font-weight: bold;
|
||||
float: right;
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
aside.chatWindow {
|
||||
z-index:100;
|
||||
pointer-events: auto;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
height: 100vh;
|
||||
width:30vw;
|
||||
min-width: 350px;
|
||||
background: rgb(5, 31, 51, 0.9);
|
||||
color: whitesmoke;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
padding: 10px;
|
||||
|
||||
border-bottom-right-radius: 16px;
|
||||
border-top-right-radius: 16px;
|
||||
|
||||
h1 {
|
||||
background-color: #5f5f5f;
|
||||
border-radius: 8px;
|
||||
padding: 2px;
|
||||
}
|
||||
|
||||
.chatWindowTitle {
|
||||
flex: 0 100px;
|
||||
}
|
||||
.messagesList {
|
||||
overflow-y: auto;
|
||||
flex: auto;
|
||||
|
||||
ul {
|
||||
list-style-type: none;
|
||||
padding-left: 0;
|
||||
}
|
||||
}
|
||||
.messageForm {
|
||||
flex: 0 70px;
|
||||
padding-top: 20px;
|
||||
}
|
||||
}
|
||||
</style>
|
83
front/src/Components/Chat/ChatElement.svelte
Normal file
83
front/src/Components/Chat/ChatElement.svelte
Normal file
|
@ -0,0 +1,83 @@
|
|||
<script lang="ts">
|
||||
import {ChatMessageTypes} from "../../Stores/ChatStore";
|
||||
import type {ChatMessage} from "../../Stores/ChatStore";
|
||||
import {HtmlUtils} from "../../WebRtc/HtmlUtils";
|
||||
import ChatPlayerName from './ChatPlayerName.svelte';
|
||||
import type {PlayerInterface} from "../../Phaser/Game/PlayerInterface";
|
||||
|
||||
export let message: ChatMessage;
|
||||
export let line: number;
|
||||
|
||||
$: author = message.author as PlayerInterface;
|
||||
$: targets = message.targets || [];
|
||||
$: texts = message.text || [];
|
||||
|
||||
function urlifyText(text: string): string {
|
||||
return HtmlUtils.urlify(text)
|
||||
}
|
||||
function renderDate(date: Date) {
|
||||
return date.toLocaleTimeString(navigator.language, {
|
||||
hour: '2-digit',
|
||||
minute:'2-digit'
|
||||
});
|
||||
}
|
||||
function isLastIteration(index: number) {
|
||||
return targets.length -1 === index;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="chatElement">
|
||||
<div class="messagePart">
|
||||
{#if message.type === ChatMessageTypes.userIncoming}
|
||||
>> {#each targets as target, index}<ChatPlayerName player={target} line={line}></ChatPlayerName>{#if !isLastIteration(index)}, {/if}{/each} entered <span class="date">({renderDate(message.date)})</span>
|
||||
{:else if message.type === ChatMessageTypes.userOutcoming}
|
||||
<< {#each targets as target, index}<ChatPlayerName player={target} line={line}></ChatPlayerName>{#if !isLastIteration(index)}, {/if}{/each} left <span class="date">({renderDate(message.date)})</span>
|
||||
{:else if message.type === ChatMessageTypes.me}
|
||||
<h4>Me: <span class="date">({renderDate(message.date)})</span></h4>
|
||||
{#each texts as text}
|
||||
<div><p class="my-text">{@html urlifyText(text)}</p></div>
|
||||
{/each}
|
||||
{:else}
|
||||
<h4><ChatPlayerName player={author} line={line}></ChatPlayerName>: <span class="date">({renderDate(message.date)})</span></h4>
|
||||
{#each texts as text}
|
||||
<div><p class="other-text">{@html urlifyText(text)}</p></div>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style lang="scss">
|
||||
h4, p {
|
||||
font-family: Lato;
|
||||
}
|
||||
div.chatElement {
|
||||
display: flex;
|
||||
margin-bottom: 20px;
|
||||
|
||||
.messagePart {
|
||||
flex-grow:1;
|
||||
max-width: 100%;
|
||||
|
||||
span.date {
|
||||
font-size: 80%;
|
||||
color: gray;
|
||||
}
|
||||
|
||||
div > p {
|
||||
border-radius: 8px;
|
||||
margin-bottom: 10px;
|
||||
padding:6px;
|
||||
overflow-wrap: break-word;
|
||||
max-width: 100%;
|
||||
display: inline-block;
|
||||
&.other-text {
|
||||
background: gray;
|
||||
}
|
||||
|
||||
&.my-text {
|
||||
background: #6489ff;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
56
front/src/Components/Chat/ChatMessageForm.svelte
Normal file
56
front/src/Components/Chat/ChatMessageForm.svelte
Normal file
|
@ -0,0 +1,56 @@
|
|||
<script lang="ts">
|
||||
import {chatMessagesStore, chatInputFocusStore} from "../../Stores/ChatStore";
|
||||
|
||||
let newMessageText = '';
|
||||
|
||||
function onFocus() {
|
||||
chatInputFocusStore.set(true);
|
||||
}
|
||||
function onBlur() {
|
||||
chatInputFocusStore.set(false);
|
||||
}
|
||||
|
||||
function saveMessage() {
|
||||
if (!newMessageText) return;
|
||||
chatMessagesStore.addPersonnalMessage(newMessageText);
|
||||
newMessageText = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
<form on:submit|preventDefault={saveMessage}>
|
||||
<input type="text" bind:value={newMessageText} placeholder="Enter your message..." on:focus={onFocus} on:blur={onBlur} >
|
||||
<button type="submit">
|
||||
<img src="/static/images/send.png" alt="Send" width="20">
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<style lang="scss">
|
||||
form {
|
||||
display: flex;
|
||||
padding-left: 4px;
|
||||
padding-right: 4px;
|
||||
|
||||
input {
|
||||
flex: auto;
|
||||
background-color: #42464d;
|
||||
color: white;
|
||||
border-bottom-left-radius: 4px;
|
||||
border-top-left-radius: 4px;
|
||||
border: none;
|
||||
font-size: 22px;
|
||||
font-family: Lato;
|
||||
padding-left: 6px;
|
||||
min-width: 0; //Needed so that the input doesn't overflow the container in firefox
|
||||
outline: none;
|
||||
}
|
||||
|
||||
button {
|
||||
background-color: #42464d;
|
||||
border-bottom-right-radius: 4px;
|
||||
border-top-right-radius: 4px;
|
||||
border: none;
|
||||
border-left: solid black 1px;
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
</style>
|
51
front/src/Components/Chat/ChatPlayerName.svelte
Normal file
51
front/src/Components/Chat/ChatPlayerName.svelte
Normal file
|
@ -0,0 +1,51 @@
|
|||
<script lang="ts">
|
||||
import type {PlayerInterface} from "../../Phaser/Game/PlayerInterface";
|
||||
import {chatSubMenuVisbilityStore} from "../../Stores/ChatStore";
|
||||
import {onDestroy, onMount} from "svelte";
|
||||
import type {Unsubscriber} from "svelte/store";
|
||||
import ChatSubMenu from "./ChatSubMenu.svelte";
|
||||
|
||||
export let player: PlayerInterface;
|
||||
export let line: number;
|
||||
|
||||
let isSubMenuOpen: boolean;
|
||||
let chatSubMenuVisivilytUnsubcribe: Unsubscriber;
|
||||
|
||||
function openSubMenu() {
|
||||
chatSubMenuVisbilityStore.openSubMenu(player.name, line);
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
chatSubMenuVisivilytUnsubcribe = chatSubMenuVisbilityStore.subscribe((newValue) => {
|
||||
isSubMenuOpen = (newValue === player.name + line);
|
||||
})
|
||||
})
|
||||
|
||||
onDestroy(() => {
|
||||
chatSubMenuVisivilytUnsubcribe();
|
||||
})
|
||||
|
||||
</script>
|
||||
|
||||
<span class="subMenu">
|
||||
<span class="chatPlayerName" style="color: {player.color || 'white'}" on:click={openSubMenu}>
|
||||
{player.name}
|
||||
</span>
|
||||
{#if isSubMenuOpen}
|
||||
<ChatSubMenu player={player}/>
|
||||
{/if}
|
||||
</span>
|
||||
|
||||
|
||||
<style lang="scss">
|
||||
span.subMenu {
|
||||
display: inline-block;
|
||||
}
|
||||
span.chatPlayerName {
|
||||
margin-left: 3px;
|
||||
}
|
||||
.chatPlayerName:hover {
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
</style>
|
33
front/src/Components/Chat/ChatSubMenu.svelte
Normal file
33
front/src/Components/Chat/ChatSubMenu.svelte
Normal file
|
@ -0,0 +1,33 @@
|
|||
<script lang="ts">
|
||||
import type {PlayerInterface} from "../../Phaser/Game/PlayerInterface";
|
||||
import {requestVisitCardsStore} from "../../Stores/GameStore";
|
||||
|
||||
export let player: PlayerInterface;
|
||||
|
||||
|
||||
function openVisitCard() {
|
||||
if (player.visitCardUrl) {
|
||||
requestVisitCardsStore.set(player.visitCardUrl);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<ul class="selectMenu" style="border-top: {player.color || 'whitesmoke'} 5px solid">
|
||||
<li><button class="text-btn" disabled={!player.visitCardUrl} on:click={openVisitCard}>Visit card</button></li>
|
||||
<li><button class="text-btn" disabled>Add friend</button></li>
|
||||
</ul>
|
||||
|
||||
|
||||
<style lang="scss">
|
||||
ul.selectMenu {
|
||||
background-color: whitesmoke;
|
||||
position: absolute;
|
||||
padding: 5px;
|
||||
border-radius: 4px;
|
||||
list-style-type: none;
|
||||
|
||||
li {
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
</style>
|
|
@ -37,9 +37,7 @@
|
|||
<img alt="Report this user" src={reportImg}>
|
||||
<span>Report/Block</span>
|
||||
</button>
|
||||
{#if $streamStore }
|
||||
<video use:srcObject={$streamStore} autoplay playsinline on:click={() => videoFocusStore.toggleFocus(peer)}></video>
|
||||
{/if}
|
||||
<img src={blockSignImg} class="block-logo" alt="Block" />
|
||||
{#if $constraintStore && $constraintStore.audio !== false}
|
||||
<SoundMeterWidget stream={$streamStore}></SoundMeterWidget>
|
||||
|
|
|
@ -1,3 +1,6 @@
|
|||
import type { UserSimplePeerInterface } from "../../WebRtc/SimplePeer";
|
||||
import { STUN_SERVER, TURN_PASSWORD, TURN_SERVER, TURN_USER } from "../../Enum/EnvironmentVariable";
|
||||
|
||||
export function getColorByString(str: string): string | null {
|
||||
let hash = 0;
|
||||
if (str.length === 0) {
|
||||
|
@ -15,7 +18,7 @@ export function getColorByString(str: string): string | null {
|
|||
return color;
|
||||
}
|
||||
|
||||
export function srcObject(node: HTMLVideoElement, stream: MediaStream) {
|
||||
export function srcObject(node: HTMLVideoElement, stream: MediaStream | null) {
|
||||
node.srcObject = stream;
|
||||
return {
|
||||
update(newStream: MediaStream) {
|
||||
|
@ -25,3 +28,19 @@ export function srcObject(node: HTMLVideoElement, stream: MediaStream) {
|
|||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function getIceServersConfig(user: UserSimplePeerInterface): RTCIceServer[] {
|
||||
const config: RTCIceServer[] = [
|
||||
{
|
||||
urls: STUN_SERVER.split(","),
|
||||
},
|
||||
];
|
||||
if (TURN_SERVER !== "") {
|
||||
config.push({
|
||||
urls: TURN_SERVER.split(","),
|
||||
username: user.webRtcUser || TURN_USER,
|
||||
credential: user.webRtcPassword || TURN_PASSWORD,
|
||||
});
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
|
|
@ -45,8 +45,9 @@
|
|||
|
||||
.visitCard {
|
||||
pointer-events: all;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
transform: translate(-50%, 0);
|
||||
margin-top: 200px;
|
||||
max-width: 80vw;
|
||||
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
import {discussionManager} from "../../WebRtc/DiscussionManager";
|
||||
import {DEPTH_INGAME_TEXT_INDEX} from "../Game/DepthIndexes";
|
||||
import { DEPTH_INGAME_TEXT_INDEX } from "../Game/DepthIndexes";
|
||||
import { chatVisibilityStore } from "../../Stores/ChatStore";
|
||||
|
||||
export const openChatIconName = 'openChatIcon';
|
||||
export const openChatIconName = "openChatIcon";
|
||||
export class OpenChatIcon extends Phaser.GameObjects.Image {
|
||||
constructor(scene: Phaser.Scene, x: number, y: number) {
|
||||
super(scene, x, y, openChatIconName, 3);
|
||||
|
@ -9,9 +9,9 @@ export class OpenChatIcon extends Phaser.GameObjects.Image {
|
|||
this.setScrollFactor(0, 0);
|
||||
this.setOrigin(0, 1);
|
||||
this.setInteractive();
|
||||
this.setVisible(false);
|
||||
//this.setVisible(false);
|
||||
this.setDepth(DEPTH_INGAME_TEXT_INDEX);
|
||||
|
||||
this.on("pointerup", () => discussionManager.showDiscussionPart());
|
||||
this.on("pointerup", () => chatVisibilityStore.set(true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -101,7 +101,6 @@ export const createLoadingPromise = (
|
|||
frameConfig: FrameConfig
|
||||
) => {
|
||||
return new Promise<BodyResourceDescriptionInterface>((res, rej) => {
|
||||
console.log("count", loadPlugin.listenerCount("loaderror"));
|
||||
if (loadPlugin.textureManager.exists(playerResourceDescriptor.name)) {
|
||||
return res(playerResourceDescriptor);
|
||||
}
|
||||
|
|
|
@ -28,7 +28,7 @@ export class GameManager {
|
|||
|
||||
public async init(scenePlugin: Phaser.Scenes.ScenePlugin): Promise<string> {
|
||||
this.startRoom = await connectionManager.initGameConnexion();
|
||||
await this.loadMap(this.startRoom, scenePlugin);
|
||||
this.loadMap(this.startRoom, scenePlugin);
|
||||
|
||||
if (!this.playerName) {
|
||||
return LoginSceneName;
|
||||
|
@ -68,20 +68,19 @@ export class GameManager {
|
|||
return this.companion;
|
||||
}
|
||||
|
||||
public async loadMap(room: Room, scenePlugin: Phaser.Scenes.ScenePlugin): Promise<void> {
|
||||
const roomID = room.id;
|
||||
const mapDetail = await room.getMapDetail();
|
||||
public loadMap(room: Room, scenePlugin: Phaser.Scenes.ScenePlugin) {
|
||||
const roomID = room.key;
|
||||
|
||||
const gameIndex = scenePlugin.getIndex(roomID);
|
||||
if (gameIndex === -1) {
|
||||
const game: Phaser.Scene = new GameScene(room, mapDetail.mapUrl);
|
||||
const game: Phaser.Scene = new GameScene(room, room.mapUrl);
|
||||
scenePlugin.add(roomID, game, false);
|
||||
}
|
||||
}
|
||||
|
||||
public goToStartingMap(scenePlugin: Phaser.Scenes.ScenePlugin): void {
|
||||
console.log("starting " + (this.currentGameSceneName || this.startRoom.id));
|
||||
scenePlugin.start(this.currentGameSceneName || this.startRoom.id);
|
||||
console.log("starting " + (this.currentGameSceneName || this.startRoom.key));
|
||||
scenePlugin.start(this.currentGameSceneName || this.startRoom.key);
|
||||
scenePlugin.launch(MenuSceneName);
|
||||
|
||||
if (
|
||||
|
|
|
@ -152,7 +152,10 @@ export class GameMap {
|
|||
}
|
||||
|
||||
private getTileProperty(index: number): Array<ITiledMapProperty> {
|
||||
return this.tileSetPropertyMap[index];
|
||||
if (this.tileSetPropertyMap[index]) {
|
||||
return this.tileSetPropertyMap[index];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
private trigger(
|
||||
|
@ -189,6 +192,10 @@ export class GameMap {
|
|||
return this.phaserLayers.find((layer) => layer.layer.name === layerName);
|
||||
}
|
||||
|
||||
public findPhaserLayers(groupName: string): TilemapLayer[] {
|
||||
return this.phaserLayers.filter((l) => l.layer.name.includes(groupName));
|
||||
}
|
||||
|
||||
public addTerrain(terrain: Phaser.Tilemaps.Tileset): void {
|
||||
for (const phaserLayer of this.phaserLayers) {
|
||||
phaserLayer.tileset.push(terrain);
|
||||
|
@ -198,37 +205,45 @@ export class GameMap {
|
|||
private putTileInFlatLayer(index: number, x: number, y: number, layer: string): void {
|
||||
const fLayer = this.findLayer(layer);
|
||||
if (fLayer == undefined) {
|
||||
console.error("The layer that you want to change doesn't exist.");
|
||||
console.error("The layer '" + layer + "' that you want to change doesn't exist.");
|
||||
return;
|
||||
}
|
||||
if (fLayer.type !== "tilelayer") {
|
||||
console.error("The layer that you want to change is not a tilelayer. Tile can only be put in tilelayer.");
|
||||
console.error(
|
||||
"The layer '" +
|
||||
layer +
|
||||
"' that you want to change is not a tilelayer. Tile can only be put in tilelayer."
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (typeof fLayer.data === "string") {
|
||||
console.error("Data of the layer that you want to change is only readable.");
|
||||
console.error("Data of the layer '" + layer + "' that you want to change is only readable.");
|
||||
return;
|
||||
}
|
||||
fLayer.data[x + y * fLayer.height] = index;
|
||||
fLayer.data[x + y * fLayer.width] = index;
|
||||
}
|
||||
|
||||
public putTile(tile: string | number, x: number, y: number, layer: string): void {
|
||||
public putTile(tile: string | number | null, x: number, y: number, layer: string): void {
|
||||
const phaserLayer = this.findPhaserLayer(layer);
|
||||
if (phaserLayer) {
|
||||
if (tile === null) {
|
||||
phaserLayer.putTileAt(-1, x, y);
|
||||
return;
|
||||
}
|
||||
const tileIndex = this.getIndexForTileType(tile);
|
||||
if (tileIndex !== undefined) {
|
||||
this.putTileInFlatLayer(tileIndex, x, y, layer);
|
||||
const phaserTile = phaserLayer.putTileAt(tileIndex, x, y);
|
||||
for (const property of this.getTileProperty(tileIndex)) {
|
||||
if (property.name === "collides" && property.value === "true") {
|
||||
if (property.name === "collides" && property.value) {
|
||||
phaserTile.setCollision(true);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error("The tile that you want to place doesn't exist.");
|
||||
console.error("The tile '" + tile + "' that you want to place doesn't exist.");
|
||||
}
|
||||
} else {
|
||||
console.error("The layer that you want to change is not a tilelayer. Tile can only be put in tilelayer.");
|
||||
console.error("The layer '" + layer + "' does not exist (or is not a tilelaye).");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -87,6 +87,7 @@ import { videoFocusStore } from "../../Stores/VideoFocusStore";
|
|||
import { biggestAvailableAreaStore } from "../../Stores/BiggestAvailableAreaStore";
|
||||
import { SharedVariablesManager } from "./SharedVariablesManager";
|
||||
import { playersStore } from "../../Stores/PlayersStore";
|
||||
import { chatVisibilityStore } from "../../Stores/ChatStore";
|
||||
|
||||
export interface GameSceneInitInterface {
|
||||
initPosition: PointInterface | null;
|
||||
|
@ -164,9 +165,10 @@ export class GameScene extends DirtyScene {
|
|||
private createPromiseResolve!: (value?: void | PromiseLike<void>) => void;
|
||||
private iframeSubscriptionList!: Array<Subscription>;
|
||||
private peerStoreUnsubscribe!: () => void;
|
||||
private chatVisibilityUnsubscribe!: () => void;
|
||||
private biggestAvailableAreaStoreUnsubscribe!: () => void;
|
||||
MapUrlFile: string;
|
||||
RoomId: string;
|
||||
roomUrl: string;
|
||||
instance: string;
|
||||
|
||||
currentTick!: number;
|
||||
|
@ -200,14 +202,14 @@ export class GameScene extends DirtyScene {
|
|||
|
||||
constructor(private room: Room, MapUrlFile: string, customKey?: string | undefined) {
|
||||
super({
|
||||
key: customKey ?? room.id,
|
||||
key: customKey ?? room.key,
|
||||
});
|
||||
this.Terrains = [];
|
||||
this.groups = new Map<number, Sprite>();
|
||||
this.instance = room.getInstance();
|
||||
|
||||
this.MapUrlFile = MapUrlFile;
|
||||
this.RoomId = room.id;
|
||||
this.roomUrl = room.key;
|
||||
|
||||
this.createPromise = new Promise<void>((resolve, reject): void => {
|
||||
this.createPromiseResolve = resolve;
|
||||
|
@ -459,11 +461,13 @@ export class GameScene extends DirtyScene {
|
|||
if (layer.type === "tilelayer") {
|
||||
const exitSceneUrl = this.getExitSceneUrl(layer);
|
||||
if (exitSceneUrl !== undefined) {
|
||||
this.loadNextGame(exitSceneUrl);
|
||||
this.loadNextGame(
|
||||
Room.getRoomPathFromExitSceneUrl(exitSceneUrl, window.location.toString(), this.MapUrlFile)
|
||||
);
|
||||
}
|
||||
const exitUrl = this.getExitUrl(layer);
|
||||
if (exitUrl !== undefined) {
|
||||
this.loadNextGame(exitUrl);
|
||||
this.loadNextGameFromExitUrl(exitUrl);
|
||||
}
|
||||
}
|
||||
if (layer.type === "objectgroup") {
|
||||
|
@ -476,7 +480,7 @@ export class GameScene extends DirtyScene {
|
|||
}
|
||||
|
||||
this.gameMap.exitUrls.forEach((exitUrl) => {
|
||||
this.loadNextGame(exitUrl);
|
||||
this.loadNextGameFromExitUrl(exitUrl);
|
||||
});
|
||||
|
||||
this.startPositionCalculator = new StartPositionCalculator(
|
||||
|
@ -567,6 +571,10 @@ export class GameScene extends DirtyScene {
|
|||
}
|
||||
oldPeerNumber = newPeerNumber;
|
||||
});
|
||||
|
||||
this.chatVisibilityUnsubscribe = chatVisibilityStore.subscribe((v) => {
|
||||
this.openChatIcon.setVisible(!v);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -577,7 +585,7 @@ export class GameScene extends DirtyScene {
|
|||
|
||||
connectionManager
|
||||
.connectToRoomSocket(
|
||||
this.RoomId,
|
||||
this.roomUrl,
|
||||
this.playerName,
|
||||
this.characterLayers,
|
||||
{
|
||||
|
@ -688,12 +696,12 @@ export class GameScene extends DirtyScene {
|
|||
const self = this;
|
||||
this.simplePeer.registerPeerConnectionListener({
|
||||
onConnect(peer) {
|
||||
self.openChatIcon.setVisible(true);
|
||||
//self.openChatIcon.setVisible(true);
|
||||
audioManager.decreaseVolume();
|
||||
},
|
||||
onDisconnect(userId: number) {
|
||||
if (self.simplePeer.getNbConnections() === 0) {
|
||||
self.openChatIcon.setVisible(false);
|
||||
//self.openChatIcon.setVisible(false);
|
||||
audioManager.restoreVolume();
|
||||
}
|
||||
},
|
||||
|
@ -707,7 +715,11 @@ export class GameScene extends DirtyScene {
|
|||
});
|
||||
|
||||
// Set up variables manager
|
||||
this.sharedVariablesManager = new SharedVariablesManager(this.connection, this.gameMap, onConnect.room.variables);
|
||||
this.sharedVariablesManager = new SharedVariablesManager(
|
||||
this.connection,
|
||||
this.gameMap,
|
||||
onConnect.room.variables
|
||||
);
|
||||
|
||||
//this.initUsersPosition(roomJoinedMessage.users);
|
||||
this.connectionAnswerPromiseResolve(onConnect.room);
|
||||
|
@ -768,10 +780,13 @@ export class GameScene extends DirtyScene {
|
|||
|
||||
private triggerOnMapLayerPropertyChange() {
|
||||
this.gameMap.onPropertyChange("exitSceneUrl", (newValue, oldValue) => {
|
||||
if (newValue) this.onMapExit(newValue as string);
|
||||
if (newValue)
|
||||
this.onMapExit(
|
||||
Room.getRoomPathFromExitSceneUrl(newValue as string, window.location.toString(), this.MapUrlFile)
|
||||
);
|
||||
});
|
||||
this.gameMap.onPropertyChange("exitUrl", (newValue, oldValue) => {
|
||||
if (newValue) this.onMapExit(newValue as string);
|
||||
if (newValue) this.onMapExit(Room.getRoomPathFromExitUrl(newValue as string, window.location.toString()));
|
||||
});
|
||||
this.gameMap.onPropertyChange("openWebsite", (newValue, oldValue, allProps) => {
|
||||
if (newValue === undefined) {
|
||||
|
@ -996,9 +1011,9 @@ ${escapedMessage}
|
|||
);
|
||||
this.iframeSubscriptionList.push(
|
||||
iframeListener.loadPageStream.subscribe((url: string) => {
|
||||
this.loadNextGame(url).then(() => {
|
||||
this.loadNextGameFromExitUrl(url).then(() => {
|
||||
this.events.once(EVENT_TYPE.POST_UPDATE, () => {
|
||||
this.onMapExit(url);
|
||||
this.onMapExit(Room.getRoomPathFromExitUrl(url, window.location.toString()));
|
||||
});
|
||||
});
|
||||
})
|
||||
|
@ -1056,7 +1071,7 @@ ${escapedMessage}
|
|||
startLayerName: this.startPositionCalculator.startLayerName,
|
||||
uuid: localUserStore.getLocalUser()?.uuid,
|
||||
nickname: this.playerName,
|
||||
roomId: this.RoomId,
|
||||
roomId: this.roomUrl,
|
||||
tags: this.connection ? this.connection.getAllTags() : [],
|
||||
variables: this.sharedVariablesManager.variables,
|
||||
};
|
||||
|
@ -1080,53 +1095,86 @@ ${escapedMessage}
|
|||
console.warn('Could not find layer "' + layerName + '" when calling setProperty');
|
||||
return;
|
||||
}
|
||||
if (propertyName === "exitUrl" && typeof propertyValue === "string") {
|
||||
this.loadNextGameFromExitUrl(propertyValue);
|
||||
}
|
||||
if (layer.properties === undefined) {
|
||||
layer.properties = [];
|
||||
}
|
||||
const property = layer.properties.find((property) => property.name === propertyName);
|
||||
if (property === undefined) {
|
||||
if (propertyValue === undefined) {
|
||||
return;
|
||||
}
|
||||
layer.properties.push({ name: propertyName, type: typeof propertyValue, value: propertyValue });
|
||||
return;
|
||||
}
|
||||
if (propertyValue === undefined) {
|
||||
const index = layer.properties.indexOf(property);
|
||||
layer.properties.splice(index, 1);
|
||||
}
|
||||
property.value = propertyValue;
|
||||
}
|
||||
|
||||
private setLayerVisibility(layerName: string, visible: boolean): void {
|
||||
const phaserLayer = this.gameMap.findPhaserLayer(layerName);
|
||||
if (phaserLayer === undefined) {
|
||||
console.warn('Could not find layer "' + layerName + '" when calling WA.hideLayer / WA.showLayer');
|
||||
return;
|
||||
if (phaserLayer != undefined) {
|
||||
phaserLayer.setVisible(visible);
|
||||
phaserLayer.setCollisionByProperty({ collides: true }, visible);
|
||||
} else {
|
||||
const phaserLayers = this.gameMap.findPhaserLayers(layerName + "/");
|
||||
if (phaserLayers === []) {
|
||||
console.warn(
|
||||
'Could not find layer with name that contains "' +
|
||||
layerName +
|
||||
'" when calling WA.hideLayer / WA.showLayer'
|
||||
);
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < phaserLayers.length; i++) {
|
||||
phaserLayers[i].setVisible(visible);
|
||||
phaserLayers[i].setCollisionByProperty({ collides: true }, visible);
|
||||
}
|
||||
}
|
||||
phaserLayer.setVisible(visible);
|
||||
this.dirty = true;
|
||||
this.markDirty();
|
||||
}
|
||||
|
||||
private getMapDirUrl(): string {
|
||||
return this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf("/"));
|
||||
}
|
||||
|
||||
private onMapExit(exitKey: string) {
|
||||
private async onMapExit(roomUrl: URL) {
|
||||
if (this.mapTransitioning) return;
|
||||
this.mapTransitioning = true;
|
||||
const { roomId, hash } = Room.getIdFromIdentifier(exitKey, this.MapUrlFile, this.instance);
|
||||
if (!roomId) throw new Error("Could not find the room from its exit key: " + exitKey);
|
||||
if (hash) {
|
||||
urlManager.pushStartLayerNameToUrl(hash);
|
||||
|
||||
let targetRoom: Room;
|
||||
try {
|
||||
targetRoom = await Room.createRoom(roomUrl);
|
||||
} catch (e: unknown) {
|
||||
console.error('Error while fetching new room "' + roomUrl.toString() + '"', e);
|
||||
this.mapTransitioning = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (roomUrl.hash) {
|
||||
urlManager.pushStartLayerNameToUrl(roomUrl.hash);
|
||||
}
|
||||
|
||||
const menuScene: MenuScene = this.scene.get(MenuSceneName) as MenuScene;
|
||||
menuScene.reset();
|
||||
if (roomId !== this.scene.key) {
|
||||
if (this.scene.get(roomId) === null) {
|
||||
console.error("next room not loaded", exitKey);
|
||||
|
||||
if (!targetRoom.isEqual(this.room)) {
|
||||
if (this.scene.get(targetRoom.key) === null) {
|
||||
console.error("next room not loaded", targetRoom.key);
|
||||
return;
|
||||
}
|
||||
this.cleanupClosingScene();
|
||||
this.scene.stop();
|
||||
this.scene.start(targetRoom.key);
|
||||
this.scene.remove(this.scene.key);
|
||||
this.scene.start(roomId);
|
||||
} else {
|
||||
//if the exit points to the current map, we simply teleport the user back to the startLayer
|
||||
this.startPositionCalculator.initPositionFromLayerName(hash, hash);
|
||||
this.startPositionCalculator.initPositionFromLayerName(roomUrl.hash, roomUrl.hash);
|
||||
this.CurrentPlayer.x = this.startPositionCalculator.startPosition.x;
|
||||
this.CurrentPlayer.y = this.startPositionCalculator.startPosition.y;
|
||||
setTimeout(() => (this.mapTransitioning = false), 500);
|
||||
|
@ -1153,6 +1201,7 @@ ${escapedMessage}
|
|||
this.pinchManager?.destroy();
|
||||
this.emoteManager.destroy();
|
||||
this.peerStoreUnsubscribe();
|
||||
this.chatVisibilityUnsubscribe();
|
||||
this.biggestAvailableAreaStoreUnsubscribe();
|
||||
iframeListener.unregisterAnswerer("getState");
|
||||
this.sharedVariablesManager?.close();
|
||||
|
@ -1218,11 +1267,18 @@ ${escapedMessage}
|
|||
.map((property) => property.value);
|
||||
}
|
||||
|
||||
private loadNextGameFromExitUrl(exitUrl: string): Promise<void> {
|
||||
return this.loadNextGame(Room.getRoomPathFromExitUrl(exitUrl, window.location.toString()));
|
||||
}
|
||||
|
||||
//todo: push that into the gameManager
|
||||
private loadNextGame(exitSceneIdentifier: string): Promise<void> {
|
||||
const { roomId, hash } = Room.getIdFromIdentifier(exitSceneIdentifier, this.MapUrlFile, this.instance);
|
||||
const room = new Room(roomId);
|
||||
return gameManager.loadMap(room, this.scene).catch(() => {});
|
||||
private async loadNextGame(exitRoomPath: URL): Promise<void> {
|
||||
try {
|
||||
const room = await Room.createRoom(exitRoomPath);
|
||||
return gameManager.loadMap(room, this.scene);
|
||||
} catch (e: unknown) {
|
||||
console.warn('Error while pre-loading exit room "' + exitRoomPath.toString() + '"', e);
|
||||
}
|
||||
}
|
||||
|
||||
//todo: in a dedicated class/function?
|
||||
|
|
|
@ -7,4 +7,5 @@ export interface PlayerInterface {
|
|||
visitCardUrl: string | null;
|
||||
companion: string | null;
|
||||
userUuid: string;
|
||||
color?: string;
|
||||
}
|
||||
|
|
|
@ -19,6 +19,7 @@ import { sendMenuClickedEvent } from "../../Api/iframe/Ui/MenuItem";
|
|||
import { consoleGlobalMessageManagerVisibleStore } from "../../Stores/ConsoleGlobalMessageManagerStore";
|
||||
import { get } from "svelte/store";
|
||||
import { playersStore } from "../../Stores/PlayersStore";
|
||||
import { mediaManager } from "../../WebRtc/MediaManager";
|
||||
|
||||
export const MenuSceneName = "MenuScene";
|
||||
const gameMenuKey = "gameMenu";
|
||||
|
@ -98,6 +99,10 @@ export class MenuScene extends Phaser.Scene {
|
|||
this.menuElement.setOrigin(0);
|
||||
MenuScene.revealMenusAfterInit(this.menuElement, "gameMenu");
|
||||
|
||||
if (mediaManager.hasNotification()) {
|
||||
HtmlUtils.getElementByIdOrFail("enableNotification").hidden = true;
|
||||
}
|
||||
|
||||
const middleX = window.innerWidth / 3 - 298;
|
||||
this.gameQualityMenuElement = this.add.dom(middleX, -400).createFromCache(gameSettingsMenuKey);
|
||||
MenuScene.revealMenusAfterInit(this.gameQualityMenuElement, "gameQuality");
|
||||
|
@ -357,6 +362,9 @@ export class MenuScene extends Phaser.Scene {
|
|||
case "toggleFullscreen":
|
||||
this.toggleFullscreen();
|
||||
break;
|
||||
case "enableNotification":
|
||||
this.enableNotification();
|
||||
break;
|
||||
case "adminConsoleButton":
|
||||
if (get(consoleGlobalMessageManagerVisibleStore)) {
|
||||
consoleGlobalMessageManagerVisibleStore.set(false);
|
||||
|
@ -419,4 +427,12 @@ export class MenuScene extends Phaser.Scene {
|
|||
public isDirty(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
private enableNotification() {
|
||||
mediaManager.requestNotification().then(() => {
|
||||
if (mediaManager.hasNotification()) {
|
||||
HtmlUtils.getElementByIdOrFail("enableNotification").hidden = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
118
front/src/Stores/ChatStore.ts
Normal file
118
front/src/Stores/ChatStore.ts
Normal file
|
@ -0,0 +1,118 @@
|
|||
import { writable } from "svelte/store";
|
||||
import { playersStore } from "./PlayersStore";
|
||||
import type { PlayerInterface } from "../Phaser/Game/PlayerInterface";
|
||||
|
||||
export const chatVisibilityStore = writable(false);
|
||||
export const chatInputFocusStore = writable(false);
|
||||
|
||||
export const newChatMessageStore = writable<string | null>(null);
|
||||
|
||||
export enum ChatMessageTypes {
|
||||
text = 1,
|
||||
me,
|
||||
userIncoming,
|
||||
userOutcoming,
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
type: ChatMessageTypes;
|
||||
date: Date;
|
||||
author?: PlayerInterface;
|
||||
targets?: PlayerInterface[];
|
||||
text?: string[];
|
||||
}
|
||||
|
||||
function getAuthor(authorId: number): PlayerInterface {
|
||||
const author = playersStore.getPlayerById(authorId);
|
||||
if (!author) {
|
||||
throw "Could not find data for author " + authorId;
|
||||
}
|
||||
return author;
|
||||
}
|
||||
|
||||
function createChatMessagesStore() {
|
||||
const { subscribe, update } = writable<ChatMessage[]>([]);
|
||||
|
||||
return {
|
||||
subscribe,
|
||||
addIncomingUser(authorId: number) {
|
||||
update((list) => {
|
||||
const lastMessage = list[list.length - 1];
|
||||
if (lastMessage && lastMessage.type === ChatMessageTypes.userIncoming && lastMessage.targets) {
|
||||
lastMessage.targets.push(getAuthor(authorId));
|
||||
} else {
|
||||
list.push({
|
||||
type: ChatMessageTypes.userIncoming,
|
||||
targets: [getAuthor(authorId)],
|
||||
date: new Date(),
|
||||
});
|
||||
}
|
||||
return list;
|
||||
});
|
||||
},
|
||||
addOutcomingUser(authorId: number) {
|
||||
update((list) => {
|
||||
const lastMessage = list[list.length - 1];
|
||||
if (lastMessage && lastMessage.type === ChatMessageTypes.userOutcoming && lastMessage.targets) {
|
||||
lastMessage.targets.push(getAuthor(authorId));
|
||||
} else {
|
||||
list.push({
|
||||
type: ChatMessageTypes.userOutcoming,
|
||||
targets: [getAuthor(authorId)],
|
||||
date: new Date(),
|
||||
});
|
||||
}
|
||||
return list;
|
||||
});
|
||||
},
|
||||
addPersonnalMessage(text: string) {
|
||||
newChatMessageStore.set(text);
|
||||
update((list) => {
|
||||
const lastMessage = list[list.length - 1];
|
||||
if (lastMessage && lastMessage.type === ChatMessageTypes.me && lastMessage.text) {
|
||||
lastMessage.text.push(text);
|
||||
} else {
|
||||
list.push({
|
||||
type: ChatMessageTypes.me,
|
||||
text: [text],
|
||||
date: new Date(),
|
||||
});
|
||||
}
|
||||
return list;
|
||||
});
|
||||
},
|
||||
addExternalMessage(authorId: number, text: string) {
|
||||
update((list) => {
|
||||
const lastMessage = list[list.length - 1];
|
||||
if (lastMessage && lastMessage.type === ChatMessageTypes.text && lastMessage.text) {
|
||||
lastMessage.text.push(text);
|
||||
} else {
|
||||
list.push({
|
||||
type: ChatMessageTypes.text,
|
||||
text: [text],
|
||||
author: getAuthor(authorId),
|
||||
date: new Date(),
|
||||
});
|
||||
}
|
||||
return list;
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
export const chatMessagesStore = createChatMessagesStore();
|
||||
|
||||
function createChatSubMenuVisibilityStore() {
|
||||
const { subscribe, update } = writable<string>("");
|
||||
|
||||
return {
|
||||
subscribe,
|
||||
openSubMenu(playerName: string, index: number) {
|
||||
const id = playerName + index;
|
||||
update((oldValue) => {
|
||||
return oldValue === id ? "" : id;
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const chatSubMenuVisbilityStore = createChatSubMenuVisibilityStore();
|
|
@ -1,6 +1,7 @@
|
|||
import { writable } from "svelte/store";
|
||||
import type { PlayerInterface } from "../Phaser/Game/PlayerInterface";
|
||||
import type { RoomConnection } from "../Connexion/RoomConnection";
|
||||
import { getRandomColor } from "../WebRtc/ColorGenerator";
|
||||
|
||||
/**
|
||||
* A store that contains the list of players currently known.
|
||||
|
@ -24,6 +25,7 @@ function createPlayersStore() {
|
|||
visitCardUrl: message.visitCardUrl,
|
||||
companion: message.companion,
|
||||
userUuid: message.userUuid,
|
||||
color: getRandomColor(),
|
||||
});
|
||||
return users;
|
||||
});
|
||||
|
|
|
@ -1,10 +1,11 @@
|
|||
import {derived} from "svelte/store";
|
||||
import {consoleGlobalMessageManagerFocusStore} from "./ConsoleGlobalMessageManagerStore";
|
||||
import { derived } from "svelte/store";
|
||||
import { consoleGlobalMessageManagerFocusStore } from "./ConsoleGlobalMessageManagerStore";
|
||||
import { chatInputFocusStore } from "./ChatStore";
|
||||
|
||||
//derived from the focus on Menu, ConsoleGlobal, Chat and ...
|
||||
export const enableUserInputsStore = derived(
|
||||
consoleGlobalMessageManagerFocusStore,
|
||||
($consoleGlobalMessageManagerFocusStore) => {
|
||||
return !$consoleGlobalMessageManagerFocusStore;
|
||||
[consoleGlobalMessageManagerFocusStore, chatInputFocusStore],
|
||||
([$consoleGlobalMessageManagerFocusStore, $chatInputFocusStore]) => {
|
||||
return !$consoleGlobalMessageManagerFocusStore && !$chatInputFocusStore;
|
||||
}
|
||||
);
|
||||
);
|
||||
|
|
52
front/src/WebRtc/ColorGenerator.ts
Normal file
52
front/src/WebRtc/ColorGenerator.ts
Normal file
|
@ -0,0 +1,52 @@
|
|||
export function getRandomColor(): string {
|
||||
const golden_ratio_conjugate = 0.618033988749895;
|
||||
let hue = Math.random();
|
||||
hue += golden_ratio_conjugate;
|
||||
hue %= 1;
|
||||
return hsv_to_rgb(hue, 0.5, 0.95);
|
||||
}
|
||||
|
||||
//todo: test this.
|
||||
function hsv_to_rgb(hue: number, saturation: number, brightness: number): string {
|
||||
const h_i = Math.floor(hue * 6);
|
||||
const f = hue * 6 - h_i;
|
||||
const p = brightness * (1 - saturation);
|
||||
const q = brightness * (1 - f * saturation);
|
||||
const t = brightness * (1 - (1 - f) * saturation);
|
||||
let r: number, g: number, b: number;
|
||||
switch (h_i) {
|
||||
case 0:
|
||||
r = brightness;
|
||||
g = t;
|
||||
b = p;
|
||||
break;
|
||||
case 1:
|
||||
r = q;
|
||||
g = brightness;
|
||||
b = p;
|
||||
break;
|
||||
case 2:
|
||||
r = p;
|
||||
g = brightness;
|
||||
b = t;
|
||||
break;
|
||||
case 3:
|
||||
r = p;
|
||||
g = q;
|
||||
b = brightness;
|
||||
break;
|
||||
case 4:
|
||||
r = t;
|
||||
g = p;
|
||||
b = brightness;
|
||||
break;
|
||||
case 5:
|
||||
r = brightness;
|
||||
g = p;
|
||||
b = q;
|
||||
break;
|
||||
default:
|
||||
throw "h_i cannot be " + h_i;
|
||||
}
|
||||
return "#" + Math.floor(r * 256).toString(16) + Math.floor(g * 256).toString(16) + Math.floor(b * 256).toString(16);
|
||||
}
|
|
@ -1,232 +1,12 @@
|
|||
import { HtmlUtils } from "./HtmlUtils";
|
||||
import type { UserInputManager } from "../Phaser/UserInput/UserInputManager";
|
||||
import { connectionManager } from "../Connexion/ConnectionManager";
|
||||
import { GameConnexionTypes } from "../Url/UrlManager";
|
||||
import { iframeListener } from "../Api/IframeListener";
|
||||
import { showReportScreenStore } from "../Stores/ShowReportScreenStore";
|
||||
|
||||
export type SendMessageCallback = (message: string) => void;
|
||||
import { chatMessagesStore, chatVisibilityStore } from "../Stores/ChatStore";
|
||||
|
||||
export class DiscussionManager {
|
||||
private mainContainer: HTMLDivElement;
|
||||
|
||||
private divDiscuss?: HTMLDivElement;
|
||||
private divParticipants?: HTMLDivElement;
|
||||
private nbpParticipants?: HTMLParagraphElement;
|
||||
private divMessages?: HTMLParagraphElement;
|
||||
|
||||
private participants: Map<number | string, HTMLDivElement> = new Map<number | string, HTMLDivElement>();
|
||||
|
||||
private activeDiscussion: boolean = false;
|
||||
|
||||
private sendMessageCallBack: Map<number | string, SendMessageCallback> = new Map<
|
||||
number | string,
|
||||
SendMessageCallback
|
||||
>();
|
||||
|
||||
private userInputManager?: UserInputManager;
|
||||
|
||||
constructor() {
|
||||
this.mainContainer = HtmlUtils.getElementByIdOrFail<HTMLDivElement>("main-container");
|
||||
this.createDiscussPart(""); //todo: why do we always use empty string?
|
||||
|
||||
iframeListener.chatStream.subscribe((chatEvent) => {
|
||||
this.addMessage(chatEvent.author, chatEvent.message, false);
|
||||
this.showDiscussion();
|
||||
chatMessagesStore.addExternalMessage(parseInt(chatEvent.author), chatEvent.message);
|
||||
chatVisibilityStore.set(true);
|
||||
});
|
||||
this.onSendMessageCallback("iframe_listener", (message) => {
|
||||
iframeListener.sendUserInputChat(message);
|
||||
});
|
||||
}
|
||||
|
||||
private createDiscussPart(name: string) {
|
||||
this.divDiscuss = document.createElement("div");
|
||||
this.divDiscuss.classList.add("discussion");
|
||||
|
||||
const buttonCloseDiscussion: HTMLButtonElement = document.createElement("button");
|
||||
buttonCloseDiscussion.classList.add("close-btn");
|
||||
buttonCloseDiscussion.innerHTML = `<img src="resources/logos/close.svg"/>`;
|
||||
buttonCloseDiscussion.addEventListener("click", () => {
|
||||
this.hideDiscussion();
|
||||
});
|
||||
this.divDiscuss.appendChild(buttonCloseDiscussion);
|
||||
|
||||
const myName: HTMLParagraphElement = document.createElement("p");
|
||||
myName.innerText = name.toUpperCase();
|
||||
this.nbpParticipants = document.createElement("p");
|
||||
this.nbpParticipants.innerText = "PARTICIPANTS (1)";
|
||||
|
||||
this.divParticipants = document.createElement("div");
|
||||
this.divParticipants.classList.add("participants");
|
||||
|
||||
this.divMessages = document.createElement("div");
|
||||
this.divMessages.classList.add("messages");
|
||||
this.divMessages.innerHTML = "<h2>Local messages</h2>";
|
||||
|
||||
this.divDiscuss.appendChild(myName);
|
||||
this.divDiscuss.appendChild(this.nbpParticipants);
|
||||
this.divDiscuss.appendChild(this.divParticipants);
|
||||
this.divDiscuss.appendChild(this.divMessages);
|
||||
|
||||
const sendDivMessage: HTMLDivElement = document.createElement("div");
|
||||
sendDivMessage.classList.add("send-message");
|
||||
const inputMessage: HTMLInputElement = document.createElement("input");
|
||||
inputMessage.onfocus = () => {
|
||||
if (this.userInputManager) {
|
||||
this.userInputManager.disableControls();
|
||||
}
|
||||
};
|
||||
inputMessage.onblur = () => {
|
||||
if (this.userInputManager) {
|
||||
this.userInputManager.restoreControls();
|
||||
}
|
||||
};
|
||||
inputMessage.type = "text";
|
||||
inputMessage.addEventListener("keyup", (event: KeyboardEvent) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
if (inputMessage.value === null || inputMessage.value === "" || inputMessage.value === undefined) {
|
||||
return;
|
||||
}
|
||||
this.addMessage(name, inputMessage.value, true);
|
||||
for (const callback of this.sendMessageCallBack.values()) {
|
||||
callback(inputMessage.value);
|
||||
}
|
||||
inputMessage.value = "";
|
||||
}
|
||||
});
|
||||
sendDivMessage.appendChild(inputMessage);
|
||||
this.divDiscuss.appendChild(sendDivMessage);
|
||||
|
||||
//append in main container
|
||||
this.mainContainer.appendChild(this.divDiscuss);
|
||||
|
||||
this.addParticipant("me", "Moi", undefined, true);
|
||||
}
|
||||
|
||||
public addParticipant(
|
||||
userId: number | "me",
|
||||
name: string | undefined,
|
||||
img?: string | undefined,
|
||||
isMe: boolean = false
|
||||
) {
|
||||
const divParticipant: HTMLDivElement = document.createElement("div");
|
||||
divParticipant.classList.add("participant");
|
||||
divParticipant.id = `participant-${userId}`;
|
||||
|
||||
const divImgParticipant: HTMLImageElement = document.createElement("img");
|
||||
divImgParticipant.src = "resources/logos/boy.svg";
|
||||
if (img !== undefined) {
|
||||
divImgParticipant.src = img;
|
||||
}
|
||||
const divPParticipant: HTMLParagraphElement = document.createElement("p");
|
||||
if (!name) {
|
||||
name = "Anonymous";
|
||||
}
|
||||
divPParticipant.innerText = name;
|
||||
|
||||
divParticipant.appendChild(divImgParticipant);
|
||||
divParticipant.appendChild(divPParticipant);
|
||||
|
||||
if (
|
||||
!isMe &&
|
||||
connectionManager.getConnexionType &&
|
||||
connectionManager.getConnexionType !== GameConnexionTypes.anonymous &&
|
||||
userId !== "me"
|
||||
) {
|
||||
const reportBanUserAction: HTMLButtonElement = document.createElement("button");
|
||||
reportBanUserAction.classList.add("report-btn");
|
||||
reportBanUserAction.innerText = "Report";
|
||||
reportBanUserAction.addEventListener("click", () => {
|
||||
showReportScreenStore.set({ userId: userId, userName: name ? name : "" });
|
||||
});
|
||||
divParticipant.appendChild(reportBanUserAction);
|
||||
}
|
||||
|
||||
this.divParticipants?.appendChild(divParticipant);
|
||||
|
||||
this.participants.set(userId, divParticipant);
|
||||
|
||||
this.updateParticipant(this.participants.size);
|
||||
}
|
||||
|
||||
public updateParticipant(nb: number) {
|
||||
if (!this.nbpParticipants) {
|
||||
return;
|
||||
}
|
||||
this.nbpParticipants.innerText = `PARTICIPANTS (${nb})`;
|
||||
}
|
||||
|
||||
public addMessage(name: string, message: string, isMe: boolean = false) {
|
||||
const divMessage: HTMLDivElement = document.createElement("div");
|
||||
divMessage.classList.add("message");
|
||||
if (isMe) {
|
||||
divMessage.classList.add("me");
|
||||
}
|
||||
|
||||
const pMessage: HTMLParagraphElement = document.createElement("p");
|
||||
const date = new Date();
|
||||
if (isMe) {
|
||||
name = "Me";
|
||||
} else {
|
||||
name = HtmlUtils.escapeHtml(name);
|
||||
}
|
||||
pMessage.innerHTML = `<span style="font-weight: bold">${name}</span>
|
||||
<span style="color:#bac2cc;display:inline-block;font-size:12px;">
|
||||
${date.getHours()}:${date.getMinutes()}
|
||||
</span>`;
|
||||
divMessage.appendChild(pMessage);
|
||||
|
||||
const userMessage: HTMLParagraphElement = document.createElement("p");
|
||||
userMessage.innerHTML = HtmlUtils.urlify(message);
|
||||
userMessage.classList.add("body");
|
||||
divMessage.appendChild(userMessage);
|
||||
this.divMessages?.appendChild(divMessage);
|
||||
|
||||
//automatic scroll when there are new message
|
||||
setTimeout(() => {
|
||||
this.divMessages?.scroll({
|
||||
top: this.divMessages?.scrollTop + divMessage.getBoundingClientRect().y,
|
||||
behavior: "smooth",
|
||||
});
|
||||
}, 200);
|
||||
}
|
||||
|
||||
public removeParticipant(userId: number | string) {
|
||||
const element = this.participants.get(userId);
|
||||
if (element) {
|
||||
element.remove();
|
||||
this.participants.delete(userId);
|
||||
}
|
||||
//if all participant leave, hide discussion button
|
||||
|
||||
this.sendMessageCallBack.delete(userId);
|
||||
}
|
||||
|
||||
public onSendMessageCallback(userId: string | number, callback: SendMessageCallback): void {
|
||||
this.sendMessageCallBack.set(userId, callback);
|
||||
}
|
||||
|
||||
get activatedDiscussion() {
|
||||
return this.activeDiscussion;
|
||||
}
|
||||
|
||||
private showDiscussion() {
|
||||
this.activeDiscussion = true;
|
||||
this.divDiscuss?.classList.add("active");
|
||||
}
|
||||
|
||||
private hideDiscussion() {
|
||||
this.activeDiscussion = false;
|
||||
this.divDiscuss?.classList.remove("active");
|
||||
}
|
||||
|
||||
public setUserInputManager(userInputManager: UserInputManager) {
|
||||
this.userInputManager = userInputManager;
|
||||
}
|
||||
|
||||
public showDiscussionPart() {
|
||||
this.showDiscussion();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -2,9 +2,9 @@ export class HtmlUtils {
|
|||
public static getElementByIdOrFail<T extends HTMLElement>(id: string): T {
|
||||
const elem = document.getElementById(id);
|
||||
if (HtmlUtils.isHtmlElement<T>(elem)) {
|
||||
return elem;
|
||||
return elem;
|
||||
}
|
||||
throw new Error("Cannot find HTML element with id '"+id+"'");
|
||||
throw new Error("Cannot find HTML element with id '" + id + "'");
|
||||
}
|
||||
|
||||
public static querySelectorOrFail<T extends HTMLElement>(selector: string): T {
|
||||
|
@ -12,7 +12,7 @@ export class HtmlUtils {
|
|||
if (HtmlUtils.isHtmlElement<T>(elem)) {
|
||||
return elem;
|
||||
}
|
||||
throw new Error("Cannot find HTML element with selector '"+selector+"'");
|
||||
throw new Error("Cannot find HTML element with selector '" + selector + "'");
|
||||
}
|
||||
|
||||
public static removeElementByIdOrFail<T extends HTMLElement>(id: string): T {
|
||||
|
@ -21,12 +21,12 @@ export class HtmlUtils {
|
|||
elem.remove();
|
||||
return elem;
|
||||
}
|
||||
throw new Error("Cannot find HTML element with id '"+id+"'");
|
||||
throw new Error("Cannot find HTML element with id '" + id + "'");
|
||||
}
|
||||
|
||||
public static escapeHtml(html: string): string {
|
||||
const text = document.createTextNode(html);
|
||||
const p = document.createElement('p');
|
||||
const text = document.createTextNode(html.replace(/(\r\n|\r|\n)/g, "<br/>"));
|
||||
const p = document.createElement("p");
|
||||
p.appendChild(text);
|
||||
return p.innerHTML;
|
||||
}
|
||||
|
@ -35,7 +35,7 @@ export class HtmlUtils {
|
|||
const urlRegex = /(https?:\/\/[^\s]+)/g;
|
||||
text = HtmlUtils.escapeHtml(text);
|
||||
return text.replace(urlRegex, (url: string) => {
|
||||
const link = document.createElement('a');
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.target = "_blank";
|
||||
const text = document.createTextNode(url);
|
||||
|
|
|
@ -1,16 +1,10 @@
|
|||
import { DivImportance, layoutManager } from "./LayoutManager";
|
||||
import { layoutManager } from "./LayoutManager";
|
||||
import { HtmlUtils } from "./HtmlUtils";
|
||||
import { discussionManager, SendMessageCallback } from "./DiscussionManager";
|
||||
import type { UserInputManager } from "../Phaser/UserInput/UserInputManager";
|
||||
import { localUserStore } from "../Connexion/LocalUserStore";
|
||||
import type { UserSimplePeerInterface } from "./SimplePeer";
|
||||
import { SoundMeter } from "../Phaser/Components/SoundMeter";
|
||||
import { DISABLE_NOTIFICATIONS } from "../Enum/EnvironmentVariable";
|
||||
import { localStreamStore } from "../Stores/MediaStore";
|
||||
import { screenSharingLocalStreamStore } from "../Stores/ScreenSharingStore";
|
||||
import { helpCameraSettingsVisibleStore } from "../Stores/HelpCameraSettingsStore";
|
||||
|
||||
export type UpdatedLocalStreamCallback = (media: MediaStream | null) => void;
|
||||
export type StartScreenSharingCallback = (media: MediaStream) => void;
|
||||
export type StopScreenSharingCallback = (media: MediaStream) => void;
|
||||
|
||||
|
@ -21,16 +15,11 @@ export class MediaManager {
|
|||
startScreenSharingCallBacks: Set<StartScreenSharingCallback> = new Set<StartScreenSharingCallback>();
|
||||
stopScreenSharingCallBacks: Set<StopScreenSharingCallback> = new Set<StopScreenSharingCallback>();
|
||||
|
||||
private focused: boolean = true;
|
||||
|
||||
private triggerCloseJistiFrame: Map<String, Function> = new Map<String, Function>();
|
||||
|
||||
private userInputManager?: UserInputManager;
|
||||
|
||||
constructor() {
|
||||
//Check of ask notification navigator permission
|
||||
this.getNotification();
|
||||
|
||||
localStreamStore.subscribe((result) => {
|
||||
if (result.type === "error") {
|
||||
console.error(result.error);
|
||||
|
@ -182,67 +171,35 @@ export class MediaManager {
|
|||
}
|
||||
}
|
||||
|
||||
public addNewMessage(name: string, message: string, isMe: boolean = false) {
|
||||
discussionManager.addMessage(name, message, isMe);
|
||||
|
||||
//when there are new message, show discussion
|
||||
if (!discussionManager.activatedDiscussion) {
|
||||
discussionManager.showDiscussionPart();
|
||||
}
|
||||
}
|
||||
|
||||
public addSendMessageCallback(userId: string | number, callback: SendMessageCallback) {
|
||||
discussionManager.onSendMessageCallback(userId, callback);
|
||||
}
|
||||
|
||||
public setUserInputManager(userInputManager: UserInputManager) {
|
||||
this.userInputManager = userInputManager;
|
||||
discussionManager.setUserInputManager(userInputManager);
|
||||
}
|
||||
|
||||
public getNotification() {
|
||||
//Get notification
|
||||
if (!DISABLE_NOTIFICATIONS && window.Notification && Notification.permission !== "granted") {
|
||||
if (this.checkNotificationPromise()) {
|
||||
Notification.requestPermission().catch((err) => {
|
||||
console.error(`Notification permission error`, err);
|
||||
});
|
||||
} else {
|
||||
Notification.requestPermission();
|
||||
}
|
||||
}
|
||||
public hasNotification(): boolean {
|
||||
return Notification.permission === "granted";
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the browser supports the modern version of the Notification API (which is Promise based) or false
|
||||
* if we are on Safari...
|
||||
*
|
||||
* See https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API
|
||||
*/
|
||||
private checkNotificationPromise(): boolean {
|
||||
try {
|
||||
Notification.requestPermission().then();
|
||||
} catch (e) {
|
||||
return false;
|
||||
public requestNotification() {
|
||||
if (window.Notification && Notification.permission !== "granted") {
|
||||
return Notification.requestPermission();
|
||||
} else {
|
||||
return Promise.reject();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public createNotification(userName: string) {
|
||||
if (this.focused) {
|
||||
if (document.hasFocus()) {
|
||||
return;
|
||||
}
|
||||
if (window.Notification && Notification.permission === "granted") {
|
||||
const title = "WorkAdventure";
|
||||
|
||||
if (this.hasNotification()) {
|
||||
const title = `${userName} wants to discuss with you`;
|
||||
const options = {
|
||||
body: `Hi! ${userName} wants to discuss with you, don't be afraid!`,
|
||||
icon: "/resources/logos/logo-WA-min.png",
|
||||
image: "/resources/logos/logo-WA-min.png",
|
||||
badge: "/resources/logos/logo-WA-min.png",
|
||||
};
|
||||
new Notification(title, options);
|
||||
//new Notification(`Hi! ${userName} wants to discuss with you, don't be afraid!`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,11 +1,10 @@
|
|||
import type * as SimplePeerNamespace from "simple-peer";
|
||||
import { mediaManager } from "./MediaManager";
|
||||
import { STUN_SERVER, TURN_PASSWORD, TURN_SERVER, TURN_USER } from "../Enum/EnvironmentVariable";
|
||||
import type { RoomConnection } from "../Connexion/RoomConnection";
|
||||
import { MESSAGE_TYPE_CONSTRAINT, PeerStatus } from "./VideoPeer";
|
||||
import type { UserSimplePeerInterface } from "./SimplePeer";
|
||||
import { Readable, readable, writable, Writable } from "svelte/store";
|
||||
import { Readable, readable } from "svelte/store";
|
||||
import { videoFocusStore } from "../Stores/VideoFocusStore";
|
||||
import { getIceServersConfig } from "../Components/Video/utils";
|
||||
|
||||
const Peer: SimplePeerNamespace.SimplePeer = require("simple-peer");
|
||||
|
||||
|
@ -32,21 +31,9 @@ export class ScreenSharingPeer extends Peer {
|
|||
stream: MediaStream | null
|
||||
) {
|
||||
super({
|
||||
initiator: initiator ? initiator : false,
|
||||
//reconnectTimer: 10000,
|
||||
initiator,
|
||||
config: {
|
||||
iceServers: [
|
||||
{
|
||||
urls: STUN_SERVER.split(","),
|
||||
},
|
||||
TURN_SERVER !== ""
|
||||
? {
|
||||
urls: TURN_SERVER.split(","),
|
||||
username: user.webRtcUser || TURN_USER,
|
||||
credential: user.webRtcPassword || TURN_PASSWORD,
|
||||
}
|
||||
: undefined,
|
||||
].filter((value) => value !== undefined),
|
||||
iceServers: getIceServersConfig(user),
|
||||
},
|
||||
});
|
||||
|
||||
|
|
|
@ -12,6 +12,7 @@ import { localStreamStore, LocalStreamStoreValue, obtainedMediaConstraintStore }
|
|||
import { screenSharingLocalStreamStore } from "../Stores/ScreenSharingStore";
|
||||
import { discussionManager } from "./DiscussionManager";
|
||||
import { playersStore } from "../Stores/PlayersStore";
|
||||
import { newChatMessageStore } from "../Stores/ChatStore";
|
||||
|
||||
export interface UserSimplePeerInterface {
|
||||
userId: number;
|
||||
|
@ -155,27 +156,11 @@ export class SimplePeer {
|
|||
|
||||
const name = this.getName(user.userId);
|
||||
|
||||
discussionManager.removeParticipant(user.userId);
|
||||
|
||||
this.lastWebrtcUserName = user.webRtcUser;
|
||||
this.lastWebrtcPassword = user.webRtcPassword;
|
||||
|
||||
const peer = new VideoPeer(user, user.initiator ? user.initiator : false, name, this.Connection, localStream);
|
||||
|
||||
//permit to send message
|
||||
mediaManager.addSendMessageCallback(user.userId, (message: string) => {
|
||||
peer.write(
|
||||
new Buffer(
|
||||
JSON.stringify({
|
||||
type: MESSAGE_TYPE_MESSAGE,
|
||||
name: this.myName.toUpperCase(),
|
||||
userId: this.userId,
|
||||
message: message,
|
||||
})
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
peer.toClose = false;
|
||||
// When a connection is established to a video stream, and if a screen sharing is taking place,
|
||||
// the user sharing screen should also initiate a connection to the remote user!
|
||||
|
|
|
@ -1,14 +1,14 @@
|
|||
import type * as SimplePeerNamespace from "simple-peer";
|
||||
import { mediaManager } from "./MediaManager";
|
||||
import { STUN_SERVER, TURN_PASSWORD, TURN_SERVER, TURN_USER } from "../Enum/EnvironmentVariable";
|
||||
import type { RoomConnection } from "../Connexion/RoomConnection";
|
||||
import { blackListManager } from "./BlackListManager";
|
||||
import type { Subscription } from "rxjs";
|
||||
import type { UserSimplePeerInterface } from "./SimplePeer";
|
||||
import { get, readable, Readable } from "svelte/store";
|
||||
import { get, readable, Readable, Unsubscriber } from "svelte/store";
|
||||
import { obtainedMediaConstraintStore } from "../Stores/MediaStore";
|
||||
import { discussionManager } from "./DiscussionManager";
|
||||
import { playersStore } from "../Stores/PlayersStore";
|
||||
import { chatMessagesStore, chatVisibilityStore, newChatMessageStore } from "../Stores/ChatStore";
|
||||
import { getIceServersConfig } from "../Components/Video/utils";
|
||||
|
||||
const Peer: SimplePeerNamespace.SimplePeer = require("simple-peer");
|
||||
|
||||
|
@ -34,6 +34,8 @@ export class VideoPeer extends Peer {
|
|||
public readonly streamStore: Readable<MediaStream | null>;
|
||||
public readonly statusStore: Readable<PeerStatus>;
|
||||
public readonly constraintsStore: Readable<MediaStreamConstraints | null>;
|
||||
private newMessageunsubscriber: Unsubscriber | null = null;
|
||||
private closing: Boolean = false; //this is used to prevent destroy() from being called twice
|
||||
|
||||
constructor(
|
||||
public user: UserSimplePeerInterface,
|
||||
|
@ -43,21 +45,9 @@ export class VideoPeer extends Peer {
|
|||
localStream: MediaStream | null
|
||||
) {
|
||||
super({
|
||||
initiator: initiator ? initiator : false,
|
||||
//reconnectTimer: 10000,
|
||||
initiator,
|
||||
config: {
|
||||
iceServers: [
|
||||
{
|
||||
urls: STUN_SERVER.split(","),
|
||||
},
|
||||
TURN_SERVER !== ""
|
||||
? {
|
||||
urls: TURN_SERVER.split(","),
|
||||
username: user.webRtcUser || TURN_USER,
|
||||
credential: user.webRtcPassword || TURN_PASSWORD,
|
||||
}
|
||||
: undefined,
|
||||
].filter((value) => value !== undefined),
|
||||
iceServers: getIceServersConfig(user),
|
||||
},
|
||||
});
|
||||
|
||||
|
@ -147,6 +137,20 @@ export class VideoPeer extends Peer {
|
|||
|
||||
this.on("connect", () => {
|
||||
this._connected = true;
|
||||
chatMessagesStore.addIncomingUser(this.userId);
|
||||
|
||||
this.newMessageunsubscriber = newChatMessageStore.subscribe((newMessage) => {
|
||||
if (!newMessage) return;
|
||||
this.write(
|
||||
new Buffer(
|
||||
JSON.stringify({
|
||||
type: MESSAGE_TYPE_MESSAGE,
|
||||
message: newMessage,
|
||||
})
|
||||
)
|
||||
); //send more data
|
||||
newChatMessageStore.set(null); //This is to prevent a newly created SimplePeer to send an old message a 2nd time. Is there a better way?
|
||||
});
|
||||
});
|
||||
|
||||
this.on("data", (chunk: Buffer) => {
|
||||
|
@ -164,8 +168,9 @@ export class VideoPeer extends Peer {
|
|||
mediaManager.disabledVideoByUserId(this.userId);
|
||||
}
|
||||
} else if (message.type === MESSAGE_TYPE_MESSAGE) {
|
||||
if (!blackListManager.isBlackListed(message.userId)) {
|
||||
mediaManager.addNewMessage(message.name, message.message);
|
||||
if (!blackListManager.isBlackListed(this.userUuid)) {
|
||||
chatMessagesStore.addExternalMessage(this.userId, message.message);
|
||||
chatVisibilityStore.set(true);
|
||||
}
|
||||
} else if (message.type === MESSAGE_TYPE_BLOCKED) {
|
||||
//FIXME when A blacklists B, the output stream from A is muted in B's js client. This is insecure since B can manipulate the code to unmute A stream.
|
||||
|
@ -245,18 +250,18 @@ export class VideoPeer extends Peer {
|
|||
/**
|
||||
* This is triggered twice. Once by the server, and once by a remote client disconnecting
|
||||
*/
|
||||
public destroy(error?: Error): void {
|
||||
public destroy(): void {
|
||||
try {
|
||||
this._connected = false;
|
||||
if (!this.toClose) {
|
||||
if (!this.toClose || this.closing) {
|
||||
return;
|
||||
}
|
||||
this.closing = true;
|
||||
this.onBlockSubscribe.unsubscribe();
|
||||
this.onUnBlockSubscribe.unsubscribe();
|
||||
discussionManager.removeParticipant(this.userId);
|
||||
// FIXME: I don't understand why "Closing connection with" message is displayed TWICE before "Nb users in peerConnectionArray"
|
||||
// I do understand the method closeConnection is called twice, but I don't understand how they manage to run in parallel.
|
||||
super.destroy(error);
|
||||
if (this.newMessageunsubscriber) this.newMessageunsubscriber();
|
||||
chatMessagesStore.addOutcomingUser(this.userId);
|
||||
super.destroy();
|
||||
} catch (err) {
|
||||
console.error("VideoPeer::destroy", err);
|
||||
}
|
||||
|
|
|
@ -1,35 +1,34 @@
|
|||
import 'phaser';
|
||||
import "phaser";
|
||||
import GameConfig = Phaser.Types.Core.GameConfig;
|
||||
import "../style/index.scss";
|
||||
|
||||
import {DEBUG_MODE, isMobile} from "./Enum/EnvironmentVariable";
|
||||
import {LoginScene} from "./Phaser/Login/LoginScene";
|
||||
import {ReconnectingScene} from "./Phaser/Reconnecting/ReconnectingScene";
|
||||
import {SelectCharacterScene} from "./Phaser/Login/SelectCharacterScene";
|
||||
import {SelectCompanionScene} from "./Phaser/Login/SelectCompanionScene";
|
||||
import {EnableCameraScene} from "./Phaser/Login/EnableCameraScene";
|
||||
import {CustomizeScene} from "./Phaser/Login/CustomizeScene";
|
||||
import WebFontLoaderPlugin from 'phaser3-rex-plugins/plugins/webfontloader-plugin.js';
|
||||
import OutlinePipelinePlugin from 'phaser3-rex-plugins/plugins/outlinepipeline-plugin.js';
|
||||
import {EntryScene} from "./Phaser/Login/EntryScene";
|
||||
import {coWebsiteManager} from "./WebRtc/CoWebsiteManager";
|
||||
import {MenuScene} from "./Phaser/Menu/MenuScene";
|
||||
import {localUserStore} from "./Connexion/LocalUserStore";
|
||||
import {ErrorScene} from "./Phaser/Reconnecting/ErrorScene";
|
||||
import {iframeListener} from "./Api/IframeListener";
|
||||
import { SelectCharacterMobileScene } from './Phaser/Login/SelectCharacterMobileScene';
|
||||
import {HdpiManager} from "./Phaser/Services/HdpiManager";
|
||||
import {waScaleManager} from "./Phaser/Services/WaScaleManager";
|
||||
import {Game} from "./Phaser/Game/Game";
|
||||
import App from './Components/App.svelte';
|
||||
import {HtmlUtils} from "./WebRtc/HtmlUtils";
|
||||
import { DEBUG_MODE, isMobile } from "./Enum/EnvironmentVariable";
|
||||
import { LoginScene } from "./Phaser/Login/LoginScene";
|
||||
import { ReconnectingScene } from "./Phaser/Reconnecting/ReconnectingScene";
|
||||
import { SelectCharacterScene } from "./Phaser/Login/SelectCharacterScene";
|
||||
import { SelectCompanionScene } from "./Phaser/Login/SelectCompanionScene";
|
||||
import { EnableCameraScene } from "./Phaser/Login/EnableCameraScene";
|
||||
import { CustomizeScene } from "./Phaser/Login/CustomizeScene";
|
||||
import WebFontLoaderPlugin from "phaser3-rex-plugins/plugins/webfontloader-plugin.js";
|
||||
import OutlinePipelinePlugin from "phaser3-rex-plugins/plugins/outlinepipeline-plugin.js";
|
||||
import { EntryScene } from "./Phaser/Login/EntryScene";
|
||||
import { coWebsiteManager } from "./WebRtc/CoWebsiteManager";
|
||||
import { MenuScene } from "./Phaser/Menu/MenuScene";
|
||||
import { localUserStore } from "./Connexion/LocalUserStore";
|
||||
import { ErrorScene } from "./Phaser/Reconnecting/ErrorScene";
|
||||
import { iframeListener } from "./Api/IframeListener";
|
||||
import { SelectCharacterMobileScene } from "./Phaser/Login/SelectCharacterMobileScene";
|
||||
import { HdpiManager } from "./Phaser/Services/HdpiManager";
|
||||
import { waScaleManager } from "./Phaser/Services/WaScaleManager";
|
||||
import { Game } from "./Phaser/Game/Game";
|
||||
import App from "./Components/App.svelte";
|
||||
import { HtmlUtils } from "./WebRtc/HtmlUtils";
|
||||
import WebGLRenderer = Phaser.Renderer.WebGL.WebGLRenderer;
|
||||
|
||||
|
||||
const {width, height} = coWebsiteManager.getGameSize();
|
||||
const { width, height } = coWebsiteManager.getGameSize();
|
||||
|
||||
const valueGameQuality = localUserStore.getGameQualityValue();
|
||||
const fps : Phaser.Types.Core.FPSConfig = {
|
||||
const fps: Phaser.Types.Core.FPSConfig = {
|
||||
/**
|
||||
* The minimum acceptable rendering rate, in frames per second.
|
||||
*/
|
||||
|
@ -53,30 +52,30 @@ const fps : Phaser.Types.Core.FPSConfig = {
|
|||
/**
|
||||
* Apply delta smoothing during the game update to help avoid spikes?
|
||||
*/
|
||||
smoothStep: false
|
||||
}
|
||||
smoothStep: false,
|
||||
};
|
||||
|
||||
// the ?phaserMode=canvas parameter can be used to force Canvas usage
|
||||
const params = new URLSearchParams(document.location.search.substring(1));
|
||||
const phaserMode = params.get("phaserMode");
|
||||
let mode: number;
|
||||
switch (phaserMode) {
|
||||
case 'auto':
|
||||
case "auto":
|
||||
case null:
|
||||
mode = Phaser.AUTO;
|
||||
break;
|
||||
case 'canvas':
|
||||
case "canvas":
|
||||
mode = Phaser.CANVAS;
|
||||
break;
|
||||
case 'webgl':
|
||||
case "webgl":
|
||||
mode = Phaser.WEBGL;
|
||||
break;
|
||||
default:
|
||||
throw new Error('phaserMode parameter must be one of "auto", "canvas" or "webgl"');
|
||||
}
|
||||
|
||||
const hdpiManager = new HdpiManager(640*480, 196*196);
|
||||
const { game: gameSize, real: realSize } = hdpiManager.getOptimalGameSize({width, height});
|
||||
const hdpiManager = new HdpiManager(640 * 480, 196 * 196);
|
||||
const { game: gameSize, real: realSize } = hdpiManager.getOptimalGameSize({ width, height });
|
||||
|
||||
const config: GameConfig = {
|
||||
type: mode,
|
||||
|
@ -87,9 +86,10 @@ const config: GameConfig = {
|
|||
height: gameSize.height,
|
||||
zoom: realSize.width / gameSize.width,
|
||||
autoRound: true,
|
||||
resizeInterval: 999999999999
|
||||
resizeInterval: 999999999999,
|
||||
},
|
||||
scene: [EntryScene,
|
||||
scene: [
|
||||
EntryScene,
|
||||
LoginScene,
|
||||
isMobile() ? SelectCharacterMobileScene : SelectCharacterScene,
|
||||
SelectCompanionScene,
|
||||
|
@ -102,37 +102,39 @@ const config: GameConfig = {
|
|||
//resolution: window.devicePixelRatio / 2,
|
||||
fps: fps,
|
||||
dom: {
|
||||
createContainer: true
|
||||
createContainer: true,
|
||||
},
|
||||
render: {
|
||||
pixelArt: true,
|
||||
roundPixels: true,
|
||||
antialias: false
|
||||
antialias: false,
|
||||
},
|
||||
plugins: {
|
||||
global: [{
|
||||
key: 'rexWebFontLoader',
|
||||
plugin: WebFontLoaderPlugin,
|
||||
start: true
|
||||
}]
|
||||
global: [
|
||||
{
|
||||
key: "rexWebFontLoader",
|
||||
plugin: WebFontLoaderPlugin,
|
||||
start: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
physics: {
|
||||
default: "arcade",
|
||||
arcade: {
|
||||
debug: DEBUG_MODE,
|
||||
}
|
||||
},
|
||||
},
|
||||
// Instruct systems with 2 GPU to choose the low power one. We don't need that extra power and we want to save battery
|
||||
powerPreference: "low-power",
|
||||
callbacks: {
|
||||
postBoot: game => {
|
||||
postBoot: (game) => {
|
||||
// Install rexOutlinePipeline only if the renderer is WebGL.
|
||||
const renderer = game.renderer;
|
||||
if (renderer instanceof WebGLRenderer) {
|
||||
game.plugins.install('rexOutlinePipeline', OutlinePipelinePlugin, true);
|
||||
game.plugins.install("rexOutlinePipeline", OutlinePipelinePlugin, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
//const game = new Phaser.Game(config);
|
||||
|
@ -140,7 +142,7 @@ const game = new Game(config);
|
|||
|
||||
waScaleManager.setGame(game);
|
||||
|
||||
window.addEventListener('resize', function (event) {
|
||||
window.addEventListener("resize", function (event) {
|
||||
coWebsiteManager.resetStyle();
|
||||
|
||||
waScaleManager.applyNewSize();
|
||||
|
@ -153,10 +155,23 @@ coWebsiteManager.onResize.subscribe(() => {
|
|||
iframeListener.init();
|
||||
|
||||
const app = new App({
|
||||
target: HtmlUtils.getElementByIdOrFail('svelte-overlay'),
|
||||
target: HtmlUtils.getElementByIdOrFail("svelte-overlay"),
|
||||
props: {
|
||||
game: game
|
||||
game: game,
|
||||
},
|
||||
})
|
||||
});
|
||||
|
||||
export default app
|
||||
export default app;
|
||||
|
||||
if ("serviceWorker" in navigator) {
|
||||
window.addEventListener("load", function () {
|
||||
navigator.serviceWorker
|
||||
.register("/resources/service-worker.js")
|
||||
.then((serviceWorker) => {
|
||||
console.log("Service Worker registered: ", serviceWorker);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error registering the Service Worker: ", error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue