This repository has been 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
/
index.ts
1534 lines (1288 loc) · 46.7 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Ably from 'ably';
import throttle from 'lodash/throttle';
import { RealtimeEvent, TranscriptState } from '../../../common/types/events.types';
import { MeetingColors } from '../../../common/types/meeting-colors.types';
import { Participant, ParticipantType } from '../../../common/types/participant.types';
import { RealtimeStateTypes } from '../../../common/types/realtime.types';
import { Annotation } from '../../../components/comments/types';
import { ParticipantMouse } from '../../../components/presence-mouse/types';
import { ComponentNames } from '../../../components/types';
import { DrawingData } from '../../video-conference-manager/types';
import { RealtimeService } from '../base';
import { ParticipantInfo, StartRealtimeType } from '../base/types';
import {
AblyParticipant,
AblyRealtime,
AblyRealtimeData,
AblyTokenCallBack,
ParticipantDataInput,
RealtimeMessage,
} from './types';
const KICK_PARTICIPANTS_TIME = 1000 * 60;
const MESSAGE_SIZE_LIMIT = 60000;
const CLIENT_MESSAGE_SIZE_LIMIT = 10000;
const SYNC_PROPERTY_INTERVAL = 1000;
const SYNC_MOUSE_INTERVAL = 100;
let KICK_PARTICIPANTS_TIMEOUT = null;
export default class AblyRealtimeService extends RealtimeService implements AblyRealtime {
private client: Ably.Realtime;
private participants: Record<string, AblyParticipant> = {};
private participantsWIO: Record<string, AblyParticipant> = {};
private participantsMouse: Record<string, ParticipantMouse> = {};
private participantsOn3d: Record<string, AblyParticipant> = {};
private hostParticipantId: string = null;
private myParticipant: AblyParticipant = null;
private commentsChannel: Ably.Types.RealtimeChannelCallbacks = null;
private supervizChannel: Ably.Types.RealtimeChannelCallbacks = null;
private clientSyncChannel: Ably.Types.RealtimeChannelCallbacks = null;
private clientRoomStateChannel: Ably.Types.RealtimeChannelCallbacks = null;
private broadcastChannel: Ably.Types.RealtimeChannelCallbacks = null;
private presenceWIOChannel: Ably.Types.RealtimeChannelCallbacks = null;
private presenceMouseChannel: Ably.Types.RealtimeChannelCallbacks = null;
private presence3DChannel: Ably.Types.RealtimeChannelCallbacks = null;
private clientRoomState: Record<string, RealtimeMessage> = {};
private clientSyncPropertiesQueue: Record<string, RealtimeMessage[]> = {};
private isReconnecting: boolean = false;
public isJoinedRoom: boolean = false;
public isJoinedPresence3D: boolean = false;
private currentReconnectAttempt: number = 0;
private localRoomProperties?: AblyRealtimeData = null;
private enableSync: boolean = true;
private isSyncFrozen: boolean = false;
private roomId: string;
private shouldKickParticipantsOnHostLeave: boolean = false;
private readonly ablyKey: string;
private apiKey: string;
private readonly apiUrl: string;
private left: boolean = false;
private domainWhitelisted: boolean = true;
private state: RealtimeStateTypes = RealtimeStateTypes.DISCONNECTED;
private supervizChannelState: Ably.Types.ChannelStateChange;
private connectionState: Ably.Types.ConnectionStateChange;
constructor(apiUrl: string, ablyKey: string) {
super();
this.ablyKey = ablyKey;
this.apiUrl = apiUrl;
// bind ably callbacks
this.onAblyPresenceEnter = this.onAblyPresenceEnter.bind(this);
this.onAblyPresenceUpdate = this.onAblyPresenceUpdate.bind(this);
this.onAblyPresenceLeave = this.onAblyPresenceLeave.bind(this);
this.onAblyRoomUpdate = this.onAblyRoomUpdate.bind(this);
this.onClientSyncChannelUpdate = this.onClientSyncChannelUpdate.bind(this);
this.onAblyChannelStateChange = this.onAblyChannelStateChange.bind(this);
this.onAblyConnectionStateChange = this.onAblyConnectionStateChange.bind(this);
this.onReceiveBroadcastSync = this.onReceiveBroadcastSync.bind(this);
this.getParticipantSlot = this.getParticipantSlot.bind(this);
this.auth = this.auth.bind(this);
setInterval(() => {
this.publishClientSyncProperties();
}, 1000);
}
public get roomProperties() {
return this.localRoomProperties;
}
public get hostClientId() {
return this.roomProperties?.hostClientId;
}
public get isLocalParticipantHost(): boolean {
return this.hostClientId === this.localParticipantId;
}
public get isDomainWhitelisted(): boolean {
return this.domainWhitelisted;
}
public get getParticipants(): Record<string, AblyParticipant> {
return this.participants;
}
public get participant() {
return this.myParticipant;
}
public get localParticipantId(): string | null {
return this.myParticipant.data?.participantId ?? null;
}
public get isBroadcast(): boolean {
return Object.values(this.participants).some(
(participant) => participant.data.type === ParticipantType.AUDIENCE,
);
}
public start({ participant, roomId, apiKey }: StartRealtimeType): void {
this.myParticipant = {
data: {
...participant,
participantId: participant.id,
},
timestamp: null,
action: null,
clientId: participant.id,
connectionId: null,
encoding: null,
id: null,
extras: null,
};
this.enableSync = participant.type !== ParticipantType.AUDIENCE;
this.roomId = `superviz:${roomId.toLowerCase()}-${apiKey}`;
this.apiKey = apiKey;
if (!this.client) {
this.buildClient();
}
}
/**
* @function auth
* @description authenticates to the realtime service
* @param {Ably.Types.TokenParams} tokenParams
* @param {AblyTokenCallBack} callback
* @returns {void}
*/
private auth(tokenParams: Ably.Types.TokenParams, callback: AblyTokenCallBack): void {
if (!this.domainWhitelisted) return;
const ably = new Ably.Rest({ key: this.ablyKey });
const { origin } = window.location;
ably.auth.requestToken(
tokenParams,
{
authUrl: `${this.apiUrl}/realtime/auth`,
key: this.ablyKey,
authParams: {
domain: origin,
apiKey: this.apiKey,
},
},
(error, tokenRequest) => {
if (error) {
this.authenticationObserver.publish(RealtimeEvent.REALTIME_AUTHENTICATION_FAILED);
}
if (error?.message?.includes("this domain don't have permission")) {
this.domainWhitelisted = false;
this.domainRefusedObserver.publish(this.domainWhitelisted);
}
callback(error, tokenRequest);
},
);
}
/**
* @function join
* @description join realtime room
* @returns {void}
* @param joinProperties
*/
public join(participant?: Participant): void {
const participantInfo = participant
? Object.assign({}, participant, { participantId: participant.id })
: this.myParticipant.data;
this.logger.log('REALTIME', `Entering room. Room ID: ${this.roomId}`);
this.updateMyProperties(participantInfo);
// join custom sync channel
this.clientSyncChannel = this.client.channels.get(`${this.roomId}:client-sync`);
this.clientSyncChannel.subscribe(this.onClientSyncChannelUpdate);
this.clientRoomStateChannel = this.client.channels.get(`${this.roomId}:client-state`);
this.broadcastChannel = this.client.channels.get(`${this.roomId}:broadcast`);
if (!this.enableSync) {
this.broadcastChannel.subscribe('update', this.onReceiveBroadcastSync);
}
// join main room channel
this.supervizChannel = this.client.channels.get(this.roomId);
this.supervizChannel.on(this.onAblyChannelStateChange);
this.supervizChannel.subscribe('update', this.onAblyRoomUpdate);
// join the comments channel
this.commentsChannel = this.client.channels.get(`${this.roomId}:comments`);
this.commentsChannel.subscribe('update', this.onCommentsChannelUpdate);
// presence only in the main channel
this.supervizChannel.presence.subscribe('enter', this.onAblyPresenceEnter);
if (this.enableSync) {
this.supervizChannel.presence.subscribe('update', this.onAblyPresenceUpdate);
}
this.supervizChannel.presence.subscribe('leave', this.onAblyPresenceLeave);
// enter
this.supervizChannel.presence.enter(this.myParticipant.data);
}
/**
* @function leave
* @description leave realtime room
* @returns {void}
*/
public leave(): void {
this.logger.log('REALTIME', 'Disconnecting from ably servers');
this.client.close();
this.isJoinedRoom = false;
this.isReconnecting = false;
this.roomId = null;
this.participants = {};
this.hostParticipantId = null;
this.myParticipant = null;
this.supervizChannel = null;
this.clientSyncChannel = null;
this.client = null;
this.left = true;
}
/**
* @function setHost
* @param {string} participantId
* @description set a new host to the room
* @returns {void}
*/
public setHost = (participantId: string): Promise<void> => {
if (!participantId) {
this.updateRoomProperties({
hostClientId: null,
});
return;
}
const participant = this.participants[participantId];
this.updateRoomProperties({
hostClientId: participant.clientId,
});
};
/**
* @function setKickParticipant
* @param {string} kickParticipantId
* @description set a participant to be kicked from the room
* @returns {void}
*/
public setKickParticipant = (kickParticipantId: string): Promise<void> => {
if (!kickParticipantId) return;
const participant = this.participants[kickParticipantId];
this.updateRoomProperties({
kickParticipant: participant,
});
};
/**
* @function setGridMode
* @param {boolean} isGridModeEnable
* @description synchronizes the grid mode of the cameras in the room
* @returns {void}
*/
public setGridMode(isGridModeEnable: boolean): void {
const roomProperties = this.localRoomProperties;
this.updateRoomProperties(Object.assign({}, roomProperties, { isGridModeEnable }));
}
/**
* @function setDrawing
* @param drawing {DrawingData} - drawing payload*
* @description synchronizes the drawing in the room
* @returns {void}
*/
public setDrawing(drawing: DrawingData): void {
const roomProperties = this.localRoomProperties;
this.updateRoomProperties(Object.assign({}, roomProperties, { drawing }));
}
/**
* @function setTranscript
* @param state {TranscriptState}
* @description synchronizes the transcript state in the room
* @returns {void}
*/
public setTranscript(state: TranscriptState): void {
const roomProperties = this.localRoomProperties;
this.updateRoomProperties(Object.assign({}, roomProperties, { transcript: state }));
}
/**
* @function setSyncProperty
* @param {string} name
* @param {unknown} property
* @description add/change and sync a property in the room
* @returns {void}
*/
public setSyncProperty<T>(name: string, property: T): void {
// closure to create the event
const createEvent = (name: string, data: T): RealtimeMessage => {
return {
name,
data,
participantId: this.myParticipant.data.participantId,
timestamp: Date.now(),
};
};
// if the property is too big, don't add to the queue
if (this.isMessageTooBig(createEvent(name, property), CLIENT_MESSAGE_SIZE_LIMIT)) {
this.logger.log('REALTIME', 'Message too big, not sending');
this.throw('Message too long, the message limit size is 10kb.');
}
this.logger.log('adding to queue', name, property);
if (!this.clientSyncPropertiesQueue[name]) {
this.clientSyncPropertiesQueue[name] = [];
}
this.clientSyncPropertiesQueue[name].push(createEvent(name, property));
}
/**
* @function setFollowParticipant
* @param {string} participantId
* @description add/change and sync a property in the room
* @returns {void}
*/
public setFollowParticipant(participantId?: string): void {
this.updateRoomProperties({
followParticipantId: participantId,
});
}
/**
* @function setGather
* @param {boolean} active
* @description sync to all participants to go to the host position
* @returns {void}
*/
public setGather(active: boolean): void {
this.updateRoomProperties({
gather: active,
});
}
/**
* @function getParticipantSlot
* @param {string} participantId
* @returns {void}
*/
public getParticipantSlot(participantId: string): number {
if (participantId) {
const id = participantId.toString();
const exists = this.participants && this.participants[id];
if (exists) {
return this.participants[participantId]?.data?.slotIndex;
}
}
return MeetingColors['gray'];
}
/**
* @function freezeSync
* @param {boolean} isFrozen
* @description Detaches and unsubscribes from channels to freeze synchronization with the room.
* @returns {void}
*/
public freezeSync = (isFrozen: boolean): void => {
this.isSyncFrozen = isFrozen;
if (isFrozen) {
this.supervizChannel.detach();
this.clientSyncChannel.detach();
this.broadcastChannel?.detach();
this.supervizChannel.unsubscribe();
this.clientSyncChannel.unsubscribe();
this.broadcastChannel?.unsubscribe();
return;
}
this.join();
};
/**
* @function setParticipantData
* @param {ParticipantDataInput} data
* @returns {void}
*/
public setParticipantData = (data: ParticipantDataInput): void => {
this.myParticipant.data = Object.assign({}, this.myParticipant.data, data);
this.updateMyProperties(this.myParticipant.data);
this.updatePresence3D(this.myParticipant.data);
};
/**
* @function setKickParticipantsOnHostLeave
* @param {boolean} shouldKick
* @description set if the participants should be kicked when the host leaves
* @param shouldKick
*/
public setKickParticipantsOnHostLeave = (shouldKick: boolean): void => {
this.shouldKickParticipantsOnHostLeave = shouldKick;
};
/**
* @function publishClientSyncProperties
* @description publish client sync props
* @returns {void}
*/
private publishClientSyncProperties = (): void => {
if (this.state !== RealtimeStateTypes.CONNECTED) return;
Object.keys(this.clientSyncPropertiesQueue).forEach((name) => {
this.clientSyncPropertiesQueue[name] = this.clientSyncPropertiesQueue[name].sort(
(a, b) => a.timestamp - b.timestamp,
);
if (!this.clientSyncPropertiesQueue[name].length) return;
const { data, lengthToBeSplitted } = this.spliceArrayBySize(
this.clientSyncPropertiesQueue[name],
);
const eventQueue = data;
this.clientSyncPropertiesQueue[name].splice(0, lengthToBeSplitted);
this.clientSyncChannel.publish(name, eventQueue, (error) => {
if (!error) return;
this.logger.log('REALTIME', 'Error in publish client sync properties', error.message);
});
});
};
/**
* @function onAblyPresenceEnter
* @description callback that receives the event that a participant has entered the room
* @param {Ably.Types.PresenceMessage} presenceMessage
* @returns {void}
*/
private onAblyPresenceEnter(presenceMessage: Ably.Types.PresenceMessage): void {
if (presenceMessage.clientId === this.myParticipant.data.participantId) {
this.onJoinRoom(presenceMessage);
} else {
this.onParticipantJoin(presenceMessage);
}
}
/**
* @function onAblyPresenceUpdate
* @description callback that receives the event that
* a participant's properties have been updated
* @param {Ably.Types.PresenceMessage} presenceMessage
* @returns {void}
*/
private onAblyPresenceUpdate(presenceMessage: Ably.Types.PresenceMessage): void {
if (!this.isJoinedRoom) return;
const { clientId } = presenceMessage;
const participant: AblyParticipant = Object.assign({}, presenceMessage, {
participantId: presenceMessage.clientId,
});
const isLastUpdateInVideo = this.participants[
participant.clientId
]?.data?.activeComponents?.includes(ComponentNames.VIDEO_CONFERENCE);
const isNowInVideo = participant.data?.activeComponents?.includes(
ComponentNames.VIDEO_CONFERENCE,
);
const isLeftVideo = isLastUpdateInVideo && !isNowInVideo;
this.publishParticipantUpdate(participant);
if (this.participants && this.participants[clientId]) {
if (this.hostParticipantId === this.localParticipantId && this.isBroadcast) {
this.syncBroadcast();
}
}
if (isLeftVideo) {
this.hostPassingHandle();
}
}
/**
* @function onAblyPresenceLeave
* @description callback that receives the exit event from a participant
* @param {Ably.Types.PresenceMessage} presenceMessage
* @returns {void}
*/
private onAblyPresenceLeave(presenceMessage: Ably.Types.PresenceMessage): void {
this.onParticipantLeave(presenceMessage);
}
/**
* @function onClientSyncChannelUpdate
* @description callback that receives the update event from ably's channel
* @param {Ably.Types.Message} message
* @returns {void}
*/
private onClientSyncChannelUpdate(message: Ably.Types.Message): void {
const { name, data } = message;
const property = {};
property[name] = data;
this.syncPropertiesObserver.publish(property);
if (message.clientId === this.myParticipant.data.participantId) {
this.saveClientRoomState(name, data);
}
}
/**
* @function saveClientRoomState
* @description
Saves the latest state of the room for the client
and publishes it to the client room state channel.
* @param {string} name - The name of the room state to save.
* @param {RealtimeMessage[]} data - The data to save as the latest state of the room.
* @returns {void}
*/
private saveClientRoomState = async (name: string, data: RealtimeMessage[]): Promise<void> => {
const previusHistory = await this.fetchSyncClientProperty();
this.clientRoomState = Object.assign({}, previusHistory, {
[name]: data[data.length - 1],
});
this.clientRoomStateChannel.publish('update', this.clientRoomState);
this.logger.log('REALTIME', 'setting new room state backup', this.clientRoomState);
};
/**
* @function onReceiveBroadcastSync
* @description receive the info of all participants from the host
* @param {Ably.Types.Message} message
* @returns {void}
*/
private onReceiveBroadcastSync(message: Ably.Types.Message): void {
const participants = message.data;
participants.forEach((member) => {
const participantId = member.clientId;
this.participants[participantId] = member;
if (!member.data?.isAudience) {
this.participants[participantId].data = JSON.parse(this.participants[participantId].data);
this.publishParticipantUpdate(this.participants[participantId]);
}
});
}
/**
* @function onAblyRoomUpdate
* @description callback that receives the update event from ably's room
* @param {Ably.Types.Message} message
* @returns {void}
*/
private onAblyRoomUpdate(message: Ably.Types.Message): void {
this.updateLocalRoomState(message.data);
}
/**
* @function updateLocalRoomState
* @description update room data
* @param {AblyRealtimeData} data
* @returns {void}
*/
private updateLocalRoomState = async (data: AblyRealtimeData): Promise<void> => {
this.localRoomProperties = Object.assign({}, this.localRoomProperties, data);
this.roomInfoUpdatedObserver.publish(this.localRoomProperties);
const hasAnyParticipantInTheVideoConference = Object.values(this.participants).some(
(participant) => {
return (
participant.data?.activeComponents?.includes(ComponentNames.VIDEO_CONFERENCE) &&
participant.data.type === ParticipantType.HOST
);
},
);
if (data.hostClientId && hasAnyParticipantInTheVideoConference && KICK_PARTICIPANTS_TIMEOUT) {
clearTimeout(KICK_PARTICIPANTS_TIMEOUT);
KICK_PARTICIPANTS_TIMEOUT = null;
this.hostAvailabilityObserver.publish(true);
}
if (!data.hostClientId && hasAnyParticipantInTheVideoConference) {
this.hostParticipantId = null;
this.hostPassingHandle();
} else if (!!data?.hostClientId && data?.hostClientId !== this.hostParticipantId) {
this.updateHostInfo(data.hostClientId);
} else if (!hasAnyParticipantInTheVideoConference && !!data?.hostClientId) {
this.updateHostInfo(null);
} else if (
!data.hostClientId &&
!KICK_PARTICIPANTS_TIMEOUT &&
!hasAnyParticipantInTheVideoConference &&
this.hostParticipantId
) {
this.hostParticipantId = null;
this.hostPassingHandle();
}
this.updateParticipants();
if (data.kickParticipant && data.kickParticipant.clientId === this.myParticipant.clientId) {
this.updateRoomProperties({ kickParticipant: null });
this.kickParticipantObserver.publish(this.myParticipant.clientId);
}
};
/**
* @function updateMyProperties
* @param {ParticipantInfo} participantInfo
* @description updates local participant properties
* @returns {void}
*/
public updateMyProperties = throttle((newProperties: ParticipantInfo = {}): void => {
const properties = newProperties;
if (this.isMessageTooBig(properties) || this.left || !this.enableSync || this.isSyncFrozen) {
return;
}
if (properties.avatar === undefined) {
delete properties.avatar;
}
this.myParticipant.data = {
...this.myParticipant.data,
...properties,
};
if (!this.isJoinedRoom) return;
this.supervizChannel.presence.update(this.myParticipant.data);
this.logger.log('REALTIME', 'updating my properties', this.myParticipant.data);
}, SYNC_PROPERTY_INTERVAL);
/**
* @function updateRoomProperties
* @param {AblyRealtimeData} properties
* @description updates room properties
* @returns {void}
*/
private updateRoomProperties = (properties: AblyRealtimeData): void => {
if (this.isMessageTooBig(properties) || this.isSyncFrozen || this.left) return;
const newProperties = {
...this.localRoomProperties,
...properties,
};
this.supervizChannel.publish('update', newProperties);
};
/**
* @function buildClient
* @description ably client build
* @returns {void}
*/
private buildClient(): void {
if (this.client) {
this.throw('Tried to call buildClient@Ably is already initialized');
}
const options: Ably.Types.ClientOptions = {
key: this.ablyKey,
disconnectedRetryTimeout: 5000,
suspendedRetryTimeout: 5000,
clientId: this.myParticipant.data.participantId,
authCallback: this.auth,
};
this.client = new Ably.Realtime(options);
this.client.connection.on(this.onAblyConnectionStateChange);
}
/**
* @function publishParticipantUpdate
* @param {AblyParticipant} participant
* @description publish a participant's changes to observer
* @returns {void}
*/
private publishParticipantUpdate(participant: AblyParticipant): void {
this.participants[participant.clientId] = participant;
this.participantsObserver.publish(this.participants);
if (this.participantObservers[participant.clientId]) {
this.participantObservers[participant.clientId].publish(participant);
}
}
/**
* @function updateParticipants
* @description update participant list
* @returns {void}
*/
private updateParticipants = (): void => {
const participants = {};
this.supervizChannel.presence.get((_, members) => {
members.forEach((member) => {
participants[member.clientId] = { ...member };
});
this.participants = participants;
this.participantsObserver.publish(this.participants);
});
};
/**
* @function updateHostInfo
* @param {string} newHostId
* @description update host info
* @returns {void}
*/
private updateHostInfo = (newHostId: string): Promise<void> => {
const currentConnectedClients: Array<{ clientId: string; type: ParticipantType }> = [];
this.supervizChannel.presence.get((err, members) => {
members.forEach((member) => {
if (err) {
return;
}
currentConnectedClients.push({
clientId: member.clientId,
type: member.data.type,
});
});
});
if (
!newHostId ||
!currentConnectedClients.some(
(client) => client.clientId === newHostId && client.type === ParticipantType.HOST,
)
) {
this.hostPassingHandle();
return;
}
if (KICK_PARTICIPANTS_TIMEOUT) {
clearTimeout(KICK_PARTICIPANTS_TIMEOUT);
this.hostAvailabilityObserver.publish(true);
}
const oldHostParticipantId = this.hostParticipantId;
this.hostParticipantId = newHostId;
this.hostObserver.publish({
oldHostParticipantId,
newHostParticipantId: this.hostParticipantId,
});
this.logger.log(
'REALTIME',
`Master participant has been changed. New Master Participant: ${this.hostParticipantId}`,
);
};
/**
* @function initializeRoomProperties
* @description
Initializes the room properties,
including setting the host client ID and updating the participant list.
* @returns {Promise<void>}
*/
private initializeRoomProperties = (): void => {
const roomProperties: AblyRealtimeData = {
isGridModeEnable: false,
hostClientId: null,
followParticipantId: null,
gather: false,
drawing: null,
};
// set host to me if im candidate
if (this.myParticipant?.data.type === ParticipantType.HOST) {
roomProperties.hostClientId = this.myParticipant.data.participantId;
}
this.updateParticipants();
this.updateRoomProperties(roomProperties);
};
/**
* @function forceReconnect
* @description Forces a reconnection to the Ably server if the participant loses connection.
* If the client is already connected to the Ably server, it rejoins the room.
* @throws {Error} if roomId is not set
* @returns {void}
*/
private forceReconnect(): void {
this.logger.log(
'REALTIME',
`RECONNECT: Starting force realtime reconnect | Current attempt: ${this.currentReconnectAttempt}`,
);
if (!this.roomId) {
this.throw('Tried to reconnect without roomId set');
}
if (this.state === RealtimeStateTypes.READY_TO_JOIN) {
this.logger.log('REALTIME', 'Rejoining room since client already connected to ably servers.');
this.join();
return;
}
this.logger.log(
'REALTIME',
'RECONNECT: Restarting ably server since participant lost connection.',
);
this.buildClient();
this.updateMyProperties(this.myParticipant.data);
}
/**
* @function throw
* @param {string} message
* @returns {void}
*/
private throw(message: string): void {
this.logger.log(message);
throw new Error(message);
}
/**
* @function publishStateUpdate
* @description saves the room locally and publishes it to the sdk
* @param {RealtimeStateTypes} state
* @returns
*/
private publishStateUpdate(state: RealtimeStateTypes): void {
if (this.state === state) return;
this.state = state;
this.logger.log(
'REALTIME',
`Realtime state did change. New state: ${RealtimeStateTypes[this.state]}`,
);
this.realtimeStateObserver.publish(this.state);
}
/**
* @function fetchRoomProperties
* @returns {AblyRealtimeData | null}
*/
private fetchRoomProperties(): Promise<AblyRealtimeData | null> {
return new Promise((resolve, reject) => {
this.supervizChannel.history((error, resultPage) => {
if (error) {
reject(error);
}
const lastMessage = resultPage.items[0]?.data;
if (lastMessage) {
resolve(lastMessage);
} else {
resolve(null);
}
});
});
}
/**
* @function fetchSyncClientProperty
* @description
* @param {string} eventName - name event to be fetched
* @returns {Promise<RealtimeMessage | Record<string, RealtimeMessage>}
*/
public async fetchSyncClientProperty(
eventName?: string,
): Promise<RealtimeMessage | Record<string, RealtimeMessage>> {
try {
const clientHistory: Record<string, RealtimeMessage> = await new Promise(
(resolve, reject) => {
this.clientRoomStateChannel.history((error, resultPage) => {
if (error) reject(error);
const lastMessage = resultPage?.items[0]?.data;
if (lastMessage) {
resolve(lastMessage);
} else {
resolve(null);
}
});
},
);
if (eventName && !clientHistory[eventName]) {
throw new Error(`Event ${eventName} not found in the history`);
}
if (eventName) {
return clientHistory[eventName];
}
return clientHistory;
} catch (error) {
this.logger.log('REALTIME', 'Error in fetch client realtime data', error.message);
this.throw(error.message);
}
}
/**
* @function hostPassingHandle
* @description
determines when guest participants should wait for the host before entering the meeting room
* @returns {void}
*/
private hostPassingHandle = throttle(async (): Promise<void> => {
this.localRoomProperties = await this.fetchRoomProperties();
this.supervizChannel.presence.get((_, members) => {
const hostCandidates = members
.filter((member) => {
return member.data.type === ParticipantType.HOST;
})
.map((member) => member.clientId);
if (this.shouldKickParticipantsOnHostLeave && !hostCandidates.length) {
this.hostAvailabilityObserver.publish(false);
KICK_PARTICIPANTS_TIMEOUT = setTimeout(() => {
this.kickAllParticipantsObserver.publish(true);
}, KICK_PARTICIPANTS_TIME);
this.setHost(null);
return;
}
const nextHostCandidateParticipantId = hostCandidates[0];
// if there is no host candidate, or host candidate is me, update room properties
if (nextHostCandidateParticipantId === this.localParticipantId || !hostCandidates.length) {
this.setHost(nextHostCandidateParticipantId);
}
});
}, 1000);
/**
* @function findSlotIndex
* @description Finds an available slot index for the participant and confirms it.
* @param {Ably.Types.PresenceMessage} myPresenceParam - The presence message of the participant.
* @returns {void}
*/
findSlotIndex = (myPresenceParam: AblyParticipant | Ably.Types.PresenceMessage) => {
let myPresence = myPresenceParam;
let availableSlots = Array.apply(null, { length: 15 }).map(Number.call, Number);
this.supervizChannel.presence.get((error, members) => {
if (error) {