Anne Lefebvre
Added comments
58ad246 unverified
import { generateSessionToken } from "../helpers";
import { User } from "./hapticLinkServer";
// User data that is safe to reveal to users
export interface UserData {
username: string;
id: string;
online: boolean;
lastOnline: number;
}
export class Room {
static roomIdLength: number = 6;
id: string;
users: User[];
/**
* @constructor
* @param roomId Optional, a secure one will be generated
*/
constructor(roomId?: string) {
this.id = roomId || generateSessionToken(Room.roomIdLength);
this.users = [];
}
/**
* Add a user to room, broadcasts message to all room users
* when user if user is successfully added. Won't add user
* if they are alreadu part of it
* @param {User} user
* @returns
*/
addUser(user: User) {
if (this.users.includes(user)) return;
this.users.push(user);
this.updateRoom();
}
/**
* Removed user from an ID
* @param {string} id User's ID
* @returns {boolean} true/false whether the user was deleted or not
*/
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;
}
/**
* Used to check if a room contains a user
* @param {string} id User's ID
* @returns {boolean} true/false whether the room has that user
*/
hasUser(id: string): boolean {
return this.users.some((user) => user.id == id);
}
/**
* Broadcasts a message to every user in room
* @param {string} message Message to send to users
* @param {string[]} 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);
});
}
/**
* Broadcasts the user list of the current room.
* Should be used when a user is added or removed.
*/
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,
})
);
}
}