-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathheadset.ts
More file actions
362 lines (296 loc) · 14.4 KB
/
headset.ts
File metadata and controls
362 lines (296 loc) · 14.4 KB
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
import { Observable, Subject, Subscription } from 'rxjs';
import { HeadsetEvents, VendorImplementation } from 'softphone-vendor-headsets';
import GenesysCloudWebrtcSdk from '../client';
import { SdkHeadsetBase } from './sdk-headset-base';
import { SdkHeadsetServiceFake } from './sdk-headset-service-fake';
import { HeadsetControlsChanged, HeadsetControlsRejection, HeadsetControlsRejectionReason, HeadsetControlsRequest, HeadsetControlsRequestType, MediaMessageEvent, SessionTypes } from 'genesys-cloud-streaming-client';
import { SdkHeadsetService } from './sdk-headset-service';
import { HeadsetRequestType } from '../types/interfaces';
import { ExpandedConsumedHeadsetEvents, ISdkHeadsetService, OrchestrationState } from './headset-types';
import { HeadsetChangesQueue } from './headset-utils';
import { MediaHandling } from '../types/enums';
const REQUEST_PRIORITY: {[key in HeadsetControlsRequestType]: number} = {
'mediaHelper': 30,
'prioritized': 20,
'standard': 10
};
const ORCHESTRATION_WAIT_TIME = 1500;
export class HeadsetProxyService implements ISdkHeadsetService {
private currentHeadsetService: SdkHeadsetBase;
private currentEventSubscription: Subscription;
private headsetEventsSub: Subject<ExpandedConsumedHeadsetEvents>;
private orchestrationWaitTimer: NodeJS.Timeout;
// TODO: PCM-2060 - remove this
private useHeadsetOrchestration = true;
headsetEvents$: Observable<ExpandedConsumedHeadsetEvents>;
orchestrationState: OrchestrationState = 'notStarted';
constructor (protected sdk: GenesysCloudWebrtcSdk) {
this.headsetEventsSub = new Subject();
this.headsetEvents$ = this.headsetEventsSub.asObservable();
}
initialize () {
if (this.sdk.isGuest) {
return;
}
this.sdk._streamingConnection.messenger.on('mediaMessage', this.handleMediaMessage.bind(this));
this.setUseHeadsets(!!this.sdk._config.useHeadsets);
}
// this is to be called externally to start/stop headsets, not internally
setUseHeadsets (useHeadsets: boolean) {
// TODO: PCM-2060 - remove this
this.useHeadsetOrchestration = !this.sdk._config.disableHeadsetControlsOrchestration;
if (this.sdk._mediaHandling === MediaHandling.reducedMedia) {
this.sdk.logger.warn('setUseHeadsets was called with `true` but media handling is set to `reducedMedia`; headsets are not supported in this configuration - not handling media. Not activating headsets.');
useHeadsets = false;
}
// currently only softphone is supported
const headsetsIsSupported = this.sdk._config.allowedSessionTypes.includes(SessionTypes.softphone);
if (useHeadsets && !headsetsIsSupported) {
this.sdk.logger.warn('setUseHeadsets was called with `true` but headsets are not supported in this configuration - headset is not supported. Not activating headsets.');
useHeadsets = false;
}
if (this.currentHeadsetService) {
// if this is the real headset service, this will clean up the current device
this.currentHeadsetService.updateAudioInputDevice(null);
}
if (this.currentEventSubscription) {
this.currentEventSubscription.unsubscribe();
}
if (useHeadsets) {
this.currentHeadsetService = new SdkHeadsetService(this.sdk);
this.currentEventSubscription = this.currentHeadsetService.headsetEvents$.subscribe((event) => this.handleHeadsetEvent(event));
this.setOrchestrationState('notStarted');
// select sdk default device or system default if one exists
const initialDeviceId = this.sdk._config.defaults.audioDeviceId ||
(this.sdk.media.getAudioDevices().length && this.sdk.media.getAudioDevices()[0].deviceId);
this.updateAudioInputDevice(initialDeviceId);
} else {
this.currentHeadsetService = new SdkHeadsetServiceFake(this.sdk);
}
}
get currentSelectedImplementation (): VendorImplementation {
return this.currentHeadsetService.currentSelectedImplementation;
}
private handleHeadsetEvent (event: ExpandedConsumedHeadsetEvents) {
if (event.event === HeadsetEvents.deviceConnectionStatusChanged && event.payload === 'noVendor' && this.orchestrationState === 'alternativeClient') {
return;
}
this.headsetEventsSub.next(event);
}
updateAudioInputDevice (newMicDeviceId: string): void {
if (!this.sdk._config.useHeadsets) {
return;
}
// if deviceId is falsey, we will pass it to the headset service so it deactivates the service
//
// updating the input device to a supported device triggers the activation of the headset controls so
// we only want to update the device if we have headset controls
// TODO: PCM-2060 - remove !this.useHeadsetOrchestration condition
if (!newMicDeviceId || this.orchestrationState === 'hasControls' || !this.useHeadsetOrchestration) {
return this.currentHeadsetService.updateAudioInputDevice(newMicDeviceId);
}
// if the device is a supported device and we don't have controls yet, start the orchestration and let
// it assign the device afterwards
const device = this.sdk.media.findCachedDeviceByIdAndKind(newMicDeviceId, 'audioinput');
const isSupported = device && this.currentHeadsetService.deviceIsSupported({ micLabel: device.label });
if (isSupported) {
if (this.orchestrationState === 'notStarted' || this.orchestrationState === 'negotiating') {
this.startHeadsetOrchestration(device);
} else {
this.setOrchestrationState('alternativeClient', true);
}
} else {
// this can happen particularly during initialization where we might start negotiating a sys default
// then change to an actual device. If this happens, we need to cancel the negotiation timer.
if (this.orchestrationState === 'negotiating') {
this.orchestrationState = 'notStarted';
clearTimeout(this.orchestrationWaitTimer);
}
this.headsetEventsSub.next({ event: HeadsetEvents.deviceConnectionStatusChanged, payload: 'noVendor' });
}
}
private async startHeadsetOrchestration (deviceToActiveOnSuccess: MediaDeviceInfo) {
clearTimeout(this.orchestrationWaitTimer);
this.setOrchestrationState('negotiating');
this.orchestrationWaitTimer = setTimeout(() => {
this.sdk.logger.info('No rejections received during orchestration, taking headsetCallControls');
this.sendControlsChangedMessage(true);
this.setOrchestrationState('hasControls');
this.updateAudioInputDevice(deviceToActiveOnSuccess.deviceId);
}, ORCHESTRATION_WAIT_TIME) as unknown as NodeJS.Timeout;
this.sdk.logger.info('Starting headsetCallControls orchestration');
let requestType: HeadsetControlsRequestType;
if (this.sdk._mediaHandling === MediaHandling.alertingLeaderMedia) {
requestType = 'prioritized';
} else {
requestType = this.sdk._config.headsetRequestType || 'standard';
}
const headsetControlsRequest: HeadsetControlsRequest = {
jsonrpc: '2.0',
method: 'headsetControlsRequest',
params: {
requestType
}
};
this.sdk._streamingConnection.messenger.broadcastMessage({
mediaMessage: headsetControlsRequest
});
}
private setOrchestrationState (state: OrchestrationState, forceUpdate = false) {
// TODO: PCM-2060 - remove this
if (!this.useHeadsetOrchestration) {
return;
}
if (state === this.orchestrationState && !forceUpdate) {
return;
}
this.sdk.logger.debug('Headset Orchestration state change', { oldState: this.orchestrationState, newState: state });
if (state === 'alternativeClient') {
clearTimeout(this.orchestrationWaitTimer);
}
this.orchestrationState = state;
this.headsetEventsSub.next({
event: HeadsetEvents.deviceConnectionStatusChanged,
payload: this.orchestrationState
});
}
// this fn handles xmpp messages needed to orchestrate which client/instance gets to have headset controls
private handleMediaMessage (msg: MediaMessageEvent) {
// TODO: PCM-2060 - remove !this.useHeadsetOrchestration condition
if (!this.sdk._config.useHeadsets || !this.useHeadsetOrchestration) {
return;
}
// I cant think of a case where we would care to handle the message if it is an echo from this client
if (msg.fromMyClient) {
return;
}
switch(msg.mediaMessage.method) {
case 'headsetControlsRequest':
this.handleHeadsetControlsRequest(msg);
break;
case 'headsetControlsRejection':
this.handleHeadsetControlsRejection(msg);
break;
case 'headsetControlsChanged':
this.handleHeadsetControlsChanged(msg);
break;
}
}
private getRequestPriority (requestType: HeadsetRequestType | string | undefined): number {
let priority = REQUEST_PRIORITY[requestType];
if (!priority) {
this.sdk.logger.warn('Unable to resolve requestType priority, defaulting to standard', { requestType });
priority = REQUEST_PRIORITY.standard;
}
return priority;
}
// in all these handlers we need to handle if we are receiving the message during negotiation or during a headset connected state
private handleHeadsetControlsRequest (msg: MediaMessageEvent) {
const mediaMessage = msg.mediaMessage as HeadsetControlsRequest;
this.sdk.logger.debug('Received headsetControlsRequest message', { requestType: mediaMessage.params.requestType });
if (this.sdk._mediaHandling === MediaHandling.alertingLeaderMedia) {
// we still yield to media-helper
if (this.getRequestPriority(mediaMessage.params.requestType) === this.getRequestPriority('mediaHelper')) {
this.sdk.logger.info('Handling alerting leader media, but yielding headset controls to media-helper', { requestType: mediaMessage.params.requestType });
this.setOrchestrationState('alternativeClient');
} else if (this.getRequestPriority(mediaMessage.params.requestType) === this.getRequestPriority('prioritized')) {
this.sdk.logger.info('Currently handling alerting leader media, but yielding headset controls to new alerting leader', { requestType: mediaMessage.params.requestType });
this.setOrchestrationState('alternativeClient');
} else {
this.sendControlsRejectionMessage(msg, 'priority');
}
return;
}
// if incoming request is lower priority, reject
if (this.getRequestPriority(mediaMessage.params.requestType) < this.getRequestPriority(this.sdk._config.headsetRequestType)) {
this.sendControlsRejectionMessage(msg, this.sdk._config.headsetRequestType === 'mediaHelper' ? 'mediaHelper' : 'priority');
}
// if incoming request is same or higher priority
if (this.getRequestPriority(mediaMessage.params.requestType) >= this.getRequestPriority(this.sdk._config.headsetRequestType)) {
// we are in the negotiating state, we want to yield
if (this.orchestrationState === 'negotiating') {
this.sdk.logger.info('Yielding headset controls to requestor', { requestType: mediaMessage.params.requestType });
this.setOrchestrationState('alternativeClient');
// if we have we have an active call OR an idle persistent connection, reject
} else if (this.sdk.sessionManager.getAllActiveSessions().filter(s => s.sessionType === 'softphone').length) {
this.sendControlsRejectionMessage(msg, 'activeCall');
}
}
}
private handleHeadsetControlsRejection (msg: MediaMessageEvent) {
const mediaMessage = msg.mediaMessage as HeadsetControlsRejection;
if (this.orchestrationState === 'negotiating') {
this.sdk.logger.info('Received headsetControlsRejection message', { reason: mediaMessage.params.reason });
this.setOrchestrationState('alternativeClient');
}
}
private handleHeadsetControlsChanged (msg: MediaMessageEvent) {
const mediaMessage = msg.mediaMessage as HeadsetControlsChanged;
const hasControlOrWaitingForControl = (['hasControls', 'negotiating'] as OrchestrationState[]).includes(this.orchestrationState);
// if some other client has taken control, we yield
if (mediaMessage.params.hasControls && hasControlOrWaitingForControl) {
HeadsetChangesQueue.clearQueue();
this.currentHeadsetService.updateAudioInputDevice(null, 'alternativeClient');
if (this.orchestrationState === 'hasControls') {
this.sendControlsChangedMessage(false);
}
this.setOrchestrationState('alternativeClient');
}
}
private sendControlsRejectionMessage (request: MediaMessageEvent, reason: HeadsetControlsRejectionReason) {
this.sdk._streamingConnection.messenger.broadcastMessage({
mediaMessage: {
jsonrpc: '2.0',
method: 'headsetControlsRejection',
params: {
requestId: request.id,
reason
}
}
});
}
private sendControlsChangedMessage (hasControls: boolean) {
this.sdk._streamingConnection.messenger.broadcastMessage({
mediaMessage: {
jsonrpc: '2.0',
method: 'headsetControlsChanged',
params: {
hasControls
}
}
});
}
showRetry (): boolean {
return this.currentHeadsetService.showRetry();
}
retryConnection (micDeviceLabel: string): Promise<void> {
return this.currentHeadsetService.retryConnection(micDeviceLabel);
}
setRinging (callInfo: { conversationId: string, contactName?: string }, hasOtherActiveCalls: boolean): Promise<void> {
return this.currentHeadsetService.setRinging(callInfo, hasOtherActiveCalls);
}
outgoingCall (callInfo: { conversationId: string, contactName: string }): Promise<void> {
return this.currentHeadsetService.outgoingCall(callInfo);
}
endCurrentCall (conversationId: string, hasOtherActiveCalls: boolean): Promise<void> {
return this.currentHeadsetService.endCurrentCall(conversationId, hasOtherActiveCalls);
}
endAllCalls (): Promise<void> {
return this.currentHeadsetService.endAllCalls();
}
answerIncomingCall (conversationId: string, autoAnswer: boolean): Promise<void> {
return this.currentHeadsetService.answerIncomingCall(conversationId, autoAnswer);
}
rejectIncomingCall (conversationId: string, expectExistingConversation = true): Promise<void> {
return this.currentHeadsetService.rejectIncomingCall(conversationId, expectExistingConversation);
}
setMute (isMuted: boolean): Promise<void> {
return this.currentHeadsetService.setMute(isMuted);
}
setHold (conversationId: string, isHeld: boolean): Promise<void> {
return this.currentHeadsetService.setHold(conversationId, isHeld);
}
resetHeadsetStateForCall(conversationId: string): Promise<void> {
return this.currentHeadsetService.resetHeadsetStateForCall(conversationId);
}
}