import { generateSessionToken } from "../helpers"; import { User } from "./hapticLinkServer"; export interface UserData { username: string; id: string; online: boolean; lastOnline: number; } export class Room { static roomIdLength: number = 6; id: string; users: User[]; constructor(roomId?: string) { this.id = roomId || generateSessionToken(Room.roomIdLength); this.users = []; } addUser(user: User) { // Generate random roomId if one wasn't created. if (this.users.includes(user)) return; this.users.push(user); this.updateRoom(); } removeUserById(id: string): boolean { const oldSize = this.users.length; this.users = this.users.filter((user) => user.id != id); this.updateRoom(); return oldSize > this.users.length; } hasUser(id: string): boolean { return this.users.some((user) => user.id == id); } /** * @param message Message to send to users * @param filter Array of user ID to ignore when sending **/ broadcast(message: string, filter: string[] = []) { this.users.forEach((user) => { if (filter.includes(user.id)) return; user.socket.send(message); }); } updateRoom() { const usersData: UserData[] = []; this.users.forEach((user) => { usersData.push({ username: user.username || "Unknown", id: user.id, online: true, lastOnline: 0, }); }); this.broadcast( JSON.stringify({ message: "room_update", roomId: this.id, users: usersData, }) ); } }