MWSE/frontend/Room.ts

119 lines
3.3 KiB
TypeScript

import EventTarget from "./EventTarget";
import MWSE from "./index";
import Peer from "./Peer";
export interface IRoomOptions
{
name: string;
description?:string;
joinType: "free"|"invite"|"password"|"lock";
credential?: string;
ifexistsJoin?: boolean;
accessType?: "public"|"private";
notifyActionInvite?: boolean;
notifyActionJoined?: boolean;
notifyActionEjected?: boolean;
}
export default class Room extends EventTarget
{
public mwse : MWSE;
public options! : IRoomOptions;
public roomId? : string;
public accessType? : "public"|"private";
public description? : string;
public joinType? : "free"|"invite"|"password"|"lock";
public name? : string;
public owner? : string;
public peers? : Map<string,Peer>;
public ifexistsJoin : boolean = false;
constructor(wsts:MWSE){
super();
this.mwse = wsts;
}
public setRoomOptions(options : IRoomOptions | string)
{
if(typeof options == "string")
{
this.roomId = options;
}else{
let defaultOptions = {
joinType: "free",
ifexistsJoin: true,
accessType: "private",
notifyActionInvite: true,
notifyActionJoined: true,
notifyActionEjected: true
};
Object.assign(defaultOptions,options);
this.options = defaultOptions as IRoomOptions;
}
}
setRoomId(uuid: string){
this.roomId = uuid;
}
async createRoom(roomOptions : IRoomOptions){
let options = this.options || roomOptions;
let result = await this.mwse.EventPooling.request({
type:'create-room',
...options
});
if(result.status == 'fail')
{
if(result.message == "ALREADY-EXISTS" && this.ifexistsJoin)
{
return this.join();
}
throw new Error(result.message || result.messages);
}else{
this.options = {
...this.options,
...result.room
};
this.roomId = result.room.id;
}
}
async join(){
let result = await this.mwse.EventPooling.request({
type:'joinroom',
name: this.options.name,
credential: this.options.credential
});
if(result.status == 'fail')
{
throw new Error(result.message);
}else{
this.options = {
...this.options,
...result.room
};
this.roomId = result.room.id;
}
}
async send(pack: any, wom:boolean = false){
await this.mwse.EventPooling.request({
type:'pack/room',
pack,
to: this.roomId,
wom
});
}
async fetchAllPeers(){
let {type, peers} = await this.mwse.EventPooling.request({
type:'room-peers',
roomId: this.roomId
}) as {type:"success"|"fail", peers: string[]};
if(type == 'fail')
{
throw new Error("Cant using peers on room")
}else if(type == 'success'){
for (const peer of peers) {
this.mwse.peer(peer);
}
}
}
}