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
/
Copy pathindex.ts
384 lines (317 loc) · 12.3 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
import { isEqual } from 'lodash';
import { ParticipantEvent, RealtimeEvent } from '../../common/types/events.types';
import { Group, Participant, ParticipantType } from '../../common/types/participant.types';
import { Observable } from '../../common/utils';
import { Logger } from '../../common/utils/logger';
import { BaseComponent } from '../../components/base';
import { ComponentNames } from '../../components/types';
import ApiService from '../../services/api';
import config from '../../services/config';
import { EventBus } from '../../services/event-bus';
import LimitsService from '../../services/limits';
import { AblyRealtimeService } from '../../services/realtime';
import { AblyParticipant } from '../../services/realtime/ably/types';
import { DefaultLauncher, LauncherFacade, LauncherOptions } from './types';
export class Launcher extends Observable implements DefaultLauncher {
protected readonly logger: Logger;
private isDestroyed = false;
private activeComponents: ComponentNames[] = [];
private componentsToAttachAfterJoin: Partial<BaseComponent>[] = [];
private activeComponentsInstances: Partial<BaseComponent>[] = [];
private participant: Participant;
private group: Group;
private realtime: AblyRealtimeService;
private eventBus: EventBus = new EventBus();
private participants: Participant[] = [];
constructor({ participant, group }: LauncherOptions) {
super();
this.participant = {
...participant,
type: ParticipantType.GUEST,
};
this.group = group;
this.logger = new Logger('@superviz/sdk/launcher');
this.realtime = new AblyRealtimeService(
config.get<string>('apiUrl'),
config.get<string>('ablyKey'),
);
// internal events without realtime
this.eventBus = new EventBus();
this.logger.log('launcher created');
this.startRealtime();
}
/**
* @function addComponent
* @description add component to launcher
* @param component - component to add
* @returns {void}
*/
public addComponent = (component: Partial<BaseComponent>): void => {
if (!this.canAddComponent(component)) return;
if (!this.realtime.isJoinedRoom) {
this.logger.log('launcher service @ addComponent - not joined yet');
this.componentsToAttachAfterJoin.push(component);
return;
}
component.attach({
localParticipant: this.participant,
realtime: this.realtime,
group: this.group,
config: config.configuration,
eventBus: this.eventBus,
});
this.activeComponents.push(component.name);
this.activeComponentsInstances.push(component);
this.realtime.updateMyProperties({ activeComponents: this.activeComponents });
ApiService.sendActivity(this.participant.id, this.group.id, this.group.name, component.name);
};
/**
* @function attachComponentsAfterJoin
* @description attach components after join
* @returns {void}
*/
private attachComponentsAfterJoin = (): void => {
this.logger.log('launcher service @ attachComponentsAfterJoin');
this.componentsToAttachAfterJoin.forEach((component) => {
this.logger.log(
'launcher service @ attachComponentsAfterJoin - attaching component',
component.name,
);
this.addComponent(component);
});
this.componentsToAttachAfterJoin = [];
};
/**
* @function removeComponent
* @description remove component from launcher
* @param component - component to remove
* @returns {void}
*/
public removeComponent = (component: Partial<BaseComponent>): void => {
if (!this.activeComponents.includes(component.name)) {
const message = `Component ${component.name} is not initialized yet.`;
this.logger.log(message);
console.error(message);
return;
}
component.detach();
this.activeComponentsInstances = this.activeComponentsInstances.filter((c) => {
return c.name !== component.name;
});
this.activeComponents.splice(this.activeComponents.indexOf(component.name), 1);
this.realtime.updateMyProperties({ activeComponents: this.activeComponents });
};
/**
* @function destroy
* @description destroy launcher and all components
* @returns {void}
*/
public destroy = (): void => {
this.logger.log('launcher service @ destroy');
this.activeComponentsInstances.forEach((component: BaseComponent) => {
this.logger.log('launcher service @ destroy - removing component', component.name);
this.removeComponent(component);
});
this.activeComponents = [];
this.activeComponentsInstances = [];
this.participant = undefined;
this.eventBus.destroy();
this.eventBus = undefined;
this.realtime.authenticationObserver.unsubscribe(this.onAuthentication);
this.realtime.sameAccountObserver.unsubscribe(this.onSameAccount);
this.realtime.participantJoinedObserver.unsubscribe(this.onParticipantJoined);
this.realtime.participantLeaveObserver.unsubscribe(this.onParticipantLeave);
this.realtime.participantsObserver.unsubscribe(this.onParticipantListUpdate);
this.realtime.leave();
this.realtime = undefined;
this.isDestroyed = true;
// clean window object
window.SUPERVIZ = undefined;
};
/**
* @function canAddComponent
* @description verifies if component can be added
* @param component - component to be added
* @returns {boolean}
*/
private canAddComponent = (component: Partial<BaseComponent>): boolean => {
const hasComponentLimit = LimitsService.checkComponentLimit(component.name);
const isComponentActive = this.activeComponents.includes(component.name);
const verifications = [
{
isValid: !this.isDestroyed,
message:
'Component can not be added because the superviz room is destroyed. Initialize a new room to add and use components.',
},
{
isValid: !isComponentActive,
message: `Component ${component.name} is already active. Please remove it first`,
},
{
isValid: hasComponentLimit,
message: `You reached the limit usage of ${component.name}`,
},
];
for (let i = 0; i < verifications.length; i++) {
const { isValid, message } = verifications[i];
if (!isValid) {
this.logger.log(message);
console.error(message);
return false;
}
}
return true;
};
/**
* @function startRealtime
* @description start realtime service and join to room
* @returns {void}
*/
private startRealtime = (): void => {
this.logger.log('launcher service @ startRealtime');
this.realtime.start({
participant: this.participant,
apiKey: config.get<string>('apiKey'),
roomId: config.get<string>('roomId'),
});
this.realtime.join();
// subscribe to realtime events
this.subscribeToRealtimeEvents();
};
/**
* @function subscribeToRealtimeEvents
* @description subscribe to realtime events
* @returns {void}
*/
private subscribeToRealtimeEvents = (): void => {
this.realtime.authenticationObserver.subscribe(this.onAuthentication);
this.realtime.sameAccountObserver.subscribe(this.onSameAccount);
this.realtime.participantJoinedObserver.subscribe(this.onParticipantJoined);
this.realtime.participantLeaveObserver.subscribe(this.onParticipantLeave);
this.realtime.participantsObserver.subscribe(this.onParticipantListUpdate);
};
/** Realtime Listeners */
private onAuthentication = (event: RealtimeEvent): void => {
if (event !== RealtimeEvent.REALTIME_AUTHENTICATION_FAILED) return;
this.destroy();
console.error(
`Room can't be initialized because this website's domain is not whitelisted. If you are the developer, please add your domain in https://dashboard.superviz.com/developer`,
);
};
/**
* @function onParticipantListUpdate
* @description on participant list update
* @param participants - participants list
* @returns {void}
*/
private onParticipantListUpdate = (participants: Record<string, AblyParticipant>): void => {
this.logger.log('launcher service @ onParticipantListUpdate', participants);
const participantList: Participant[] = Object.values(participants).map((participant) => ({
id: participant.data.id,
name: participant.data?.name,
type: participant.data?.type,
avatar: participant.data?.avatar,
avatarConfig: participant.data?.avatarConfig,
isHost: this.realtime.hostClientId === participant.clientId,
color: this.realtime.getSlotColor(participant.data?.slotIndex).color,
activeComponents: participant.data?.activeComponents,
}));
const localParticipant = participantList.find((participant) => {
return participant?.id === this.participant?.id;
});
if (!isEqual(this.participants, participantList)) {
this.participants = participantList;
this.publish(ParticipantEvent.LIST_UPDATED, participantList);
this.logger.log('Publishing ParticipantEvent.LIST_UPDATED', participantList);
}
if (localParticipant && !isEqual(this.participant, localParticipant)) {
this.activeComponents = localParticipant.activeComponents ?? [];
this.activeComponentsInstances = this.activeComponentsInstances.filter((component) => {
/**
* @NOTE - Prevents removing all components when
* in the first update, activeComponents is undefined.
* It means we should keep all instances
*/
if (!localParticipant.activeComponents) return true;
return this.activeComponents.includes(component.name);
});
this.participant = localParticipant;
this.publish(ParticipantEvent.LOCAL_UPDATED, localParticipant);
this.logger.log('Publishing ParticipantEvent.UPDATED', localParticipant);
}
this.logger.log(
'launcher service @ onParticipantListUpdate - participants updated',
participantList,
);
};
/**
* @function onParticipantJoined
* @description on participant joined
* @param ablyParticipant - ably participant
* @returns {void}
*/
private onParticipantJoined = (ablyParticipant: AblyParticipant): void => {
this.logger.log('launcher service @ onParticipantJoined');
const participant = this.participants.find(
(participant) => participant.id === ablyParticipant.data.id,
);
if (!participant) return;
if (participant.id === this.participant.id) {
this.logger.log('launcher service @ onParticipantJoined - local participant joined');
this.publish(ParticipantEvent.LOCAL_JOINED, participant);
this.attachComponentsAfterJoin();
}
this.logger.log('launcher service @ onParticipantJoined - participant joined', participant);
this.publish(ParticipantEvent.JOINED, participant);
};
/**
* @function onParticipantLeave
* @description on participant leave
* @param ablyParticipant - ably participant
* @returns {void}
*/
private onParticipantLeave = (ablyParticipant: AblyParticipant): void => {
this.logger.log('launcher service @ onParticipantLeave');
const participant = this.participants.find((participant) => {
return participant.id === ablyParticipant.data.id;
});
if (!participant) return;
if (participant.id === this.participant.id) {
this.logger.log('launcher service @ onParticipantLeave - local participant left');
this.publish(ParticipantEvent.LOCAL_LEFT, participant);
}
this.logger.log('launcher service @ onParticipantLeave - participant left', participant);
this.publish(ParticipantEvent.LEFT, participant);
};
private onSameAccount = (): void => {
this.publish(ParticipantEvent.SAME_ACCOUNT_ERROR);
this.destroy();
};
}
/**
* @function Launcher
* @description create launcher instance
* @param options - launcher options
* @returns {LauncherFacade}
*/
export default (options: LauncherOptions): LauncherFacade => {
if (window.SUPERVIZ) {
console.warn('[SUPERVIZ] Room already initialized');
return {
destroy: window.SUPERVIZ.destroy,
subscribe: window.SUPERVIZ.subscribe,
unsubscribe: window.SUPERVIZ.unsubscribe,
addComponent: window.SUPERVIZ.addComponent,
removeComponent: window.SUPERVIZ.removeComponent,
};
}
const launcher = new Launcher(options);
window.SUPERVIZ = launcher;
return {
destroy: launcher.destroy,
subscribe: launcher.subscribe,
unsubscribe: launcher.unsubscribe,
addComponent: launcher.addComponent,
removeComponent: launcher.removeComponent,
};
};