This repository was archived by the owner on Oct 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
96 lines (78 loc) · 2.71 KB
/
index.ts
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 * as Socket from '@superviz/socket-client';
import {
INDEX_IS_WHITE_TEXT,
MeetingColors,
MeetingColorsHex,
} from '../../common/types/meeting-colors.types';
import { Participant, Slot } from '../../common/types/participant.types';
import { AblyRealtimeService } from '../realtime';
export class SlotService {
private room: Socket.Room;
private participant: Participant;
private slotIndex: number;
private static instance: SlotService;
// @NOTE - reciving old realtime service instance until we migrate to new IO
constructor(room: Socket.Room, participant: Participant) {
this.room = room;
this.participant = participant;
this.room.presence.on(Socket.PresenceEvents.UPDATE, this.onPresenceUpdate);
}
/**
* @function assignSlot
* @description Assigns a slot to the participant
* @returns void
*/
public async assignSlot(): Promise<Slot> {
try {
const slot = Math.floor(Math.random() * 16);
const isUsing = await new Promise((resolve, reject) => {
this.room.presence.get((presences) => {
if (!presences || !presences.length) resolve(false);
if (presences.length >= 16) {
reject(new Error('[SuperViz] - No more slots available'));
return;
}
presences.forEach((presence: Socket.PresenceEvent<Participant>) => {
if (presence.id === this.participant.id) return;
if (presence.data?.slot?.index === slot) resolve(true);
});
resolve(false);
});
});
if (isUsing) {
const slotData = await this.assignSlot();
return slotData;
}
const slotData = {
index: slot,
color: MeetingColorsHex[slot],
textColor: INDEX_IS_WHITE_TEXT.includes(slot) ? '#fff' : '#000',
colorName: MeetingColors[slot],
timestamp: Date.now(),
};
this.slotIndex = slot;
this.participant = {
...this.participant,
slot: slotData,
};
return slotData;
} catch (error) {
console.error(error);
return null;
}
}
private onPresenceUpdate = async (event: Socket.PresenceEvent<Participant>) => {
if (!event.data.slot || !this.participant?.slot) return;
if (event.id === this.participant.id) {
this.participant = event.data;
this.slotIndex = event.data.slot.index;
return;
}
const slotOccupied = event.data.slot.timestamp < this.participant?.slot?.timestamp;
// if someone else has the same slot as me, and they were assigned first, I should reassign
if (event.data.slot?.index === this.slotIndex && slotOccupied) {
const slotData = await this.assignSlot();
this.room.presence.update({ slot: slotData });
}
};
}