File size: 1,783 Bytes
2b43822
 
 
e3cb794
2b43822
 
 
 
 
 
 
34a23a6
2b43822
 
 
34a23a6
2b43822
 
 
 
307d8b2
e3cb794
2b43822
 
 
 
 
 
d32b1fb
2b43822
 
 
 
 
d32b1fb
2b43822
 
 
d32b1fb
 
 
2b43822
d32b1fb
2b43822
 
d32b1fb
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
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,
            })
        );
    }
}