Room.ts 2.2 KB
import { Connection } from "../connection/Connection";
import { v4 as uuidv4 } from "uuid";
import { RoomData } from "./types";
import {
  Message,
  RoomInfoMessage,
  RoomUserUpdateMessage,
} from "../message/types";
import { UserData } from "../user/types";

export class Room {
  public readonly uuid: string;

  public name: string;
  public readonly maxConnections: number;

  private connections: Connection[] = [];

  private closed: boolean = false;

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

  public connect(connection: Connection): void {
    // TODO: 더 나은 인증 처리
    const user = connection.user;
    if (user === undefined) {
      return;
    }

    if (
      this.connections.includes(connection) ||
      this.connections.length >= this.maxConnections
    ) {
      return;
    }

    this.connections.push(connection);
    connection.room = this; // TODO: 더 나은 관리

    this.broadcast(new RoomUserUpdateMessage("added", user.getData()));

    var users: UserData[] = [];
    this.connections.forEach((con) => {
      if (con.user !== undefined && connection !== con) {
        users.push(con.user.getData());
      }
    });
    connection.send(new RoomInfoMessage(users));
  }

  public disconnect(connection: Connection): void {
    const index = this.connections.indexOf(connection);
    if (connection.user !== undefined && index > -1) {
      this.connections.splice(index, 1);
      connection.room = undefined;

      this.broadcast(
        new RoomUserUpdateMessage("removed", connection.user.getData())
      );
    }
  }

  public getData(): RoomData {
    return {
      uuid: this.uuid,
      name: this.name,
      currentConnections: this.connections.length,
      maxConnections: this.maxConnections,
    };
  }

  public broadcast(message: Message, except?: Connection): void {
    this.connections.forEach((connection) => {
      if (connection !== except) {
        connection.send(message);
      }
    });
  }

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