Room.ts 2.5 KB
import { Connection } from "../connection/Connection";
import { v4 as uuidv4 } from "uuid";
import { User } from "../user/User";
import { MessageHandlerChain } from "../message/MessageHandlerChain";
import { MessageHandler } from "../message/MessageHandler";
import {
  ServerInboundMessage,
  ServerOutboundMessage,
  ServerOutboundMessageKey,
} from "../../common";
import { RoomDescription, RoomInfo, UserData } from "../../common/dataType";

export class Room {
  public readonly uuid: string;

  public name: string;
  public readonly maxUsers: number;

  public users: User[] = [];

  private closed: boolean = false;

  public handler: MessageHandler;

  constructor(name: string, maxUsers: number = 8) {
    this.uuid = uuidv4();
    this.name = name;
    this.maxUsers = maxUsers;

    this.handler = new MessageHandler({
      chat: (user, message) => {
        this.sendChat(user, message.message);
        return { ok: true };
      },
      leaveRoom: (user, message) => {
        this.disconnect(user);
        return { ok: true };
      },
    });
  }

  public connect(user: User): void {
    if (this.users.includes(user) || this.users.length >= this.maxUsers) {
      return;
    }

    this.broadcast("updateRoomUser", { state: "added", user: user.getData() });

    this.users.push(user);
    user.room = this;
  }

  public disconnect(user: User): void {
    const index = this.users.indexOf(user);
    if (index > -1) {
      this.users.splice(index, 1);
      user.room = undefined;

      this.broadcast("updateRoomUser", {
        state: "removed",
        user: user.getData(),
      });
    }
  }

  public sendChat(user: User, message: string): void {
    this.broadcast("chat", { sender: user.username, message: message });
  }

  public getDescription(): RoomDescription {
    return {
      uuid: this.uuid,
      name: this.name,
      currentUsers: this.users.length,
      maxUsers: this.maxUsers,
    };
  }

  public getInfo(): RoomInfo {
    var users: UserData[] = this.users.map((u) => u.getData());
    return {
      uuid: this.uuid,
      name: this.name,
      maxUsers: this.maxUsers,
      users: users,
    };
  }

  public broadcast<T extends ServerOutboundMessageKey>(
    type: T,
    message: ServerOutboundMessage<T>,
    except?: User
  ): void {
    this.users.forEach((u) => {
      if (u !== except) {
        u.connection.send(type, message);
      }
    });
  }

  public close(): void {
    if (!this.closed) {
      this.users.forEach((u) => this.disconnect(u));
      this.closed = true;
    }
  }
}