Spaces:
Paused
Paused
File size: 2,613 Bytes
2b43822 58ad246 e3cb794 2b43822 34a23a6 2b43822 58ad246 2b43822 34a23a6 2b43822 58ad246 2b43822 e3cb794 2b43822 58ad246 2b43822 d32b1fb 2b43822 58ad246 2b43822 d32b1fb 2b43822 58ad246 d32b1fb 2b43822 d32b1fb 2b43822 d32b1fb 2b43822 58ad246 2b43822 d32b1fb 2b43822 d32b1fb 2b43822 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
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,
})
);
}
}
|