-
Notifications
You must be signed in to change notification settings - Fork 50
/
device.ts
1595 lines (1355 loc) · 45.1 KB
/
device.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
/**
* @packageDocumentation
* @module Voice
* @preferred
* @publicapi
*/
import { EventEmitter } from 'events';
import { levels as LogLevels, LogLevelDesc } from 'loglevel';
import AudioHelper from './audiohelper';
import Call from './call';
import DialtonePlayer from './dialtonePlayer';
import {
AuthorizationErrors,
ClientErrors,
GeneralErrors,
getErrorByCode,
hasErrorByCode,
InvalidArgumentError,
InvalidStateError,
NotSupportedError,
TwilioError,
} from './errors';
import Log from './log';
import { PreflightTest } from './preflight/preflight';
import {
getChunderURIs,
getRegionShortcode,
Region,
regionToEdge,
} from './regions';
import {
isLegacyEdge,
isUnifiedPlanDefault,
queryToJson,
} from './util';
const C = require('./constants');
const Publisher = require('./eventpublisher');
const PStream = require('./pstream');
const rtc = require('./rtc');
const getUserMedia = require('./rtc/getusermedia');
const Sound = require('./sound');
// Placeholders until we convert the respective files to TypeScript.
/**
* @private
*/
export type IPStream = any;
/**
* @private
*/
export type IPublisher = any;
/**
* @private
*/
export type ISound = any;
const REGISTRATION_INTERVAL = 30000;
const RINGTONE_PLAY_TIMEOUT = 2000;
const PUBLISHER_PRODUCT_NAME = 'twilio-js-sdk';
const INVALID_TOKEN_MESSAGE = 'Parameter "token" must be of type "string".';
declare const RTCRtpTransceiver: any;
declare const webkitAudioContext: typeof AudioContext;
/**
* Options that may be passed to the {@link Device} constructor for internal testing.
* @private
*/
export interface IExtendedDeviceOptions extends Device.Options {
/**
* Custom {@link AudioHelper} constructor
*/
AudioHelper?: typeof AudioHelper;
/**
* The max amount of time in milliseconds to allow stream (re)-connect
* backoffs.
*/
backoffMaxMs?: number;
/**
* Custom {@link Call} constructor
*/
Call?: typeof Call;
/**
* Hostname of the signaling gateway to connect to.
*/
chunderw?: string | string[];
/**
* Hostname of the event gateway to connect to.
*/
eventgw?: string;
/**
* File input stream to use instead of reading from mic
*/
fileInputStream?: MediaStream;
/**
* Ignore browser support, disabling the exception that is thrown when neither WebRTC nor
* ORTC are supported.
*/
ignoreBrowserSupport?: boolean;
/**
* MediaStream constructor.
*/
MediaStream?: typeof MediaStream;
/**
* Whether this is a preflight call or not
*/
preflight?: boolean;
/**
* Custom PStream constructor
*/
PStream?: IPStream;
/**
* Custom Publisher constructor
*/
Publisher?: IPublisher;
/**
* Whether or not to publish events to insights using {@link Device._publisher}.
*/
publishEvents?: boolean;
/**
* MediaStreamConstraints to pass to getUserMedia when making or accepting a Call.
*/
rtcConstraints?: Call.AcceptOptions['rtcConstraints'];
/**
* Custom Sound constructor
*/
Sound?: ISound;
}
/**
* A sound definition used to initialize a Sound file.
* @private
*/
export interface ISoundDefinition {
/**
* Name of the sound file.
*/
filename: string;
/**
* The amount of time this sound file should play before being stopped automatically.
*/
maxDuration?: number;
/**
* Whether or not this sound should loop after playthrough finishes.
*/
shouldLoop?: boolean;
}
/**
* Twilio Device. Allows registration for incoming calls, and placing outgoing calls.
* @publicapi
*/
class Device extends EventEmitter {
/**
* The AudioContext to be used by {@link Device} instances.
* @private
*/
static get audioContext(): AudioContext | undefined {
return Device._audioContext;
}
/**
* Which sound file extension is supported.
* @private
*/
static get extension(): 'mp3' | 'ogg' {
// NOTE(mroberts): Node workaround.
const a: any = typeof document !== 'undefined'
? document.createElement('audio') : { canPlayType: false };
let canPlayMp3;
try {
canPlayMp3 = a.canPlayType && !!a.canPlayType('audio/mpeg').replace(/no/, '');
} catch (e) {
canPlayMp3 = false;
}
let canPlayVorbis;
try {
canPlayVorbis = a.canPlayType && !!a.canPlayType('audio/ogg;codecs=\'vorbis\'').replace(/no/, '');
} catch (e) {
canPlayVorbis = false;
}
return (canPlayVorbis && !canPlayMp3) ? 'ogg' : 'mp3';
}
/**
* Whether or not this SDK is supported by the current browser.
*/
static get isSupported(): boolean { return rtc.enabled(); }
/**
* Package name of the SDK.
*/
static get packageName(): string { return C.PACKAGE_NAME; }
/**
* Run some tests to identify issues, if any, prohibiting successful calling.
* @param token - A Twilio JWT token string
* @param options
*/
static runPreflight(token: string, options?: PreflightTest.Options): PreflightTest {
return new PreflightTest(token, { audioContext: Device._getOrCreateAudioContext(), ...options });
}
/**
* String representation of {@link Device} class.
* @private
*/
static toString(): string {
return '[Twilio.Device class]';
}
/**
* Current SDK version.
*/
static get version(): string { return C.RELEASE_VERSION; }
/**
* An AudioContext to share between {@link Device}s.
*/
private static _audioContext?: AudioContext;
private static _defaultSounds: Record<string, ISoundDefinition> = {
disconnect: { filename: 'disconnect', maxDuration: 3000 },
dtmf0: { filename: 'dtmf-0', maxDuration: 1000 },
dtmf1: { filename: 'dtmf-1', maxDuration: 1000 },
dtmf2: { filename: 'dtmf-2', maxDuration: 1000 },
dtmf3: { filename: 'dtmf-3', maxDuration: 1000 },
dtmf4: { filename: 'dtmf-4', maxDuration: 1000 },
dtmf5: { filename: 'dtmf-5', maxDuration: 1000 },
dtmf6: { filename: 'dtmf-6', maxDuration: 1000 },
dtmf7: { filename: 'dtmf-7', maxDuration: 1000 },
dtmf8: { filename: 'dtmf-8', maxDuration: 1000 },
dtmf9: { filename: 'dtmf-9', maxDuration: 1000 },
dtmfh: { filename: 'dtmf-hash', maxDuration: 1000 },
dtmfs: { filename: 'dtmf-star', maxDuration: 1000 },
incoming: { filename: 'incoming', shouldLoop: true },
outgoing: { filename: 'outgoing', maxDuration: 3000 },
};
/**
* A DialtonePlayer to play mock DTMF sounds through.
*/
private static _dialtonePlayer?: DialtonePlayer;
/**
* Whether or not the browser uses unified-plan SDP by default.
*/
private static _isUnifiedPlanDefault: boolean | undefined;
/**
* Initializes the AudioContext instance shared across the Voice SDK,
* or returns the existing instance if one has already been initialized.
*/
private static _getOrCreateAudioContext(): AudioContext | undefined {
if (!Device._audioContext) {
if (typeof AudioContext !== 'undefined') {
Device._audioContext = new AudioContext();
} else if (typeof webkitAudioContext !== 'undefined') {
Device._audioContext = new webkitAudioContext();
}
}
return Device._audioContext;
}
/**
* The currently active {@link Call}, if there is one.
*/
private _activeCall: Call | null = null;
/**
* The AudioHelper instance associated with this {@link Device}.
*/
private _audio: AudioHelper | null = null;
/**
* {@link Device._confirmClose} bound to the specific {@link Device} instance.
*/
private _boundConfirmClose: typeof Device.prototype._confirmClose;
/**
* {@link Device.destroy} bound to the specific {@link Device} instance.
*/
private _boundDestroy: typeof Device.prototype.destroy;
/**
* An audio input MediaStream to pass to new {@link Call} instances.
*/
private _callInputStream: MediaStream | null = null;
/**
* An array of {@link Call}s. Though only one can be active, multiple may exist when there
* are multiple incoming, unanswered {@link Call}s.
*/
private _calls: Call[] = [];
/**
* An array of {@link Device} IDs to be used to play sounds through, to be passed to
* new {@link Call} instances.
*/
private _callSinkIds: string[] = ['default'];
/**
* The list of chunder URIs that will be passed to PStream
*/
private _chunderURIs: string[] = [];
/**
* Default options used by {@link Device}.
*/
private readonly _defaultOptions: IExtendedDeviceOptions = {
allowIncomingWhileBusy: false,
closeProtection: false,
codecPreferences: [Call.Codec.PCMU, Call.Codec.Opus],
dscp: true,
eventgw: 'eventgw.twilio.com',
forceAggressiveIceNomination: false,
logLevel: LogLevels.ERROR,
preflight: false,
sounds: { },
};
/**
* The name of the edge the {@link Device} is connected to.
*/
private _edge: string | null = null;
/**
* Whether each sound is enabled.
*/
private _enabledSounds: Record<Device.ToggleableSound, boolean> = {
[Device.SoundName.Disconnect]: true,
[Device.SoundName.Incoming]: true,
[Device.SoundName.Outgoing]: true,
};
/**
* Whether SDK is run as a browser extension
*/
private _isBrowserExtension: boolean;
/**
* An instance of Logger to use.
*/
private _log: Log = Log.getInstance();
/**
* Network related information
* See https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API
*/
private _networkInformation: any;
/**
* The options passed to {@link Device} constructor or {@link Device.updateOptions}.
*/
private _options: IExtendedDeviceOptions = { };
/**
* An Insights Event Publisher.
*/
private _publisher: IPublisher | null = null;
/**
* The region the {@link Device} is connected to.
*/
private _region: string | null = null;
/**
* A timeout ID for a setTimeout schedule to re-register the {@link Device}.
*/
private _regTimer: NodeJS.Timer | null = null;
/**
* Boolean representing whether or not the {@link Device} was registered when
* receiving a signaling `offline`. Determines if the {@link Device} attempts
* a `re-register` once signaling is re-established when receiving a
* `connected` event from the stream.
*/
private _shouldReRegister: boolean = false;
/**
* A Map of Sounds to play.
*/
private _soundcache: Map<Device.SoundName, ISound> = new Map();
/**
* The current status of the {@link Device}.
*/
private _state: Device.State = Device.State.Unregistered;
/**
* A map from {@link Device.State} to {@link Device.EventName}.
*/
private readonly _stateEventMapping: Record<Device.State, Device.EventName> = {
[Device.State.Destroyed]: Device.EventName.Destroyed,
[Device.State.Unregistered]: Device.EventName.Unregistered,
[Device.State.Registering]: Device.EventName.Registering,
[Device.State.Registered]: Device.EventName.Registered,
};
/**
* The Signaling stream.
*/
private _stream: IPStream | null = null;
/**
* A promise that will resolve when the Signaling stream is ready.
*/
private _streamConnectedPromise: Promise<IPStream> | null = null;
/**
* The JWT string currently being used to authenticate this {@link Device}.
*/
private _token: string;
/**
* Construct a {@link Device} instance. The {@link Device} can be registered
* to make and listen for calls using {@link Device.register}.
* @constructor
* @param options
*/
constructor(token: string, options: Device.Options = { }) {
super();
this.updateToken(token);
if (isLegacyEdge()) {
throw new NotSupportedError(
'Microsoft Edge Legacy (https://support.microsoft.com/en-us/help/4533505/what-is-microsoft-edge-legacy) ' +
'is deprecated and will not be able to connect to Twilio to make or receive calls after September 1st, 2020. ' +
'Please see this documentation for a list of supported browsers ' +
'https://www.twilio.com/docs/voice/client/javascript#supported-browsers',
);
}
if (!Device.isSupported && (options as IExtendedDeviceOptions).ignoreBrowserSupport) {
if (window && window.location && window.location.protocol === 'http:') {
throw new NotSupportedError(`twilio.js wasn't able to find WebRTC browser support. \
This is most likely because this page is served over http rather than https, \
which does not support WebRTC in many browsers. Please load this page over https and \
try again.`);
}
throw new NotSupportedError(`twilio.js 1.3+ SDKs require WebRTC browser support. \
For more information, see <https://www.twilio.com/docs/api/client/twilio-js>. \
If you have any questions about this announcement, please contact \
Twilio Support at <help@twilio.com>.`);
}
if (window) {
const root: any = window as any;
const browser: any = root.msBrowser || root.browser || root.chrome;
this._isBrowserExtension = (!!browser && !!browser.runtime && !!browser.runtime.id)
|| (!!root.safari && !!root.safari.extension);
}
if (this._isBrowserExtension) {
this._log.info('Running as browser extension.');
}
if (navigator) {
const n = navigator as any;
this._networkInformation = n.connection
|| n.mozConnection
|| n.webkitConnection;
}
if (this._networkInformation && typeof this._networkInformation.addEventListener === 'function') {
this._networkInformation.addEventListener('change', this._publishNetworkChange);
}
Device._getOrCreateAudioContext();
if (Device._audioContext) {
if (!Device._dialtonePlayer) {
Device._dialtonePlayer = new DialtonePlayer(Device._audioContext);
}
}
if (typeof Device._isUnifiedPlanDefault === 'undefined') {
Device._isUnifiedPlanDefault = typeof window !== 'undefined'
&& typeof RTCPeerConnection !== 'undefined'
&& typeof RTCRtpTransceiver !== 'undefined'
? isUnifiedPlanDefault(window, window.navigator, RTCPeerConnection, RTCRtpTransceiver)
: false;
}
this._boundDestroy = this.destroy.bind(this);
this._boundConfirmClose = this._confirmClose.bind(this);
if (typeof window !== 'undefined' && window.addEventListener) {
window.addEventListener('unload', this._boundDestroy);
window.addEventListener('pagehide', this._boundDestroy);
}
this.updateOptions(options);
}
/**
* Return the {@link AudioHelper} used by this {@link Device}.
*/
get audio(): AudioHelper | null {
return this._audio;
}
/**
* Make an outgoing Call.
* @param options
*/
async connect(options: Device.ConnectOptions = { }): Promise<Call> {
this._throwIfDestroyed();
if (this._activeCall) {
throw new InvalidStateError('A Call is already active');
}
const activeCall = this._activeCall = await this._makeCall(options.params || { }, {
rtcConfiguration: options.rtcConfiguration,
});
// Make sure any incoming calls are ignored
this._calls.splice(0).forEach(call => call.ignore());
// Stop the incoming sound if it's playing
this._soundcache.get(Device.SoundName.Incoming).stop();
activeCall.accept({ rtcConstraints: options.rtcConstraints });
this._publishNetworkChange();
return activeCall;
}
/**
* Return the calls that this {@link Device} is maintaining.
*/
get calls(): Call[] {
return this._calls;
}
/**
* Destroy the {@link Device}, freeing references to be garbage collected.
*/
destroy(): void {
this.disconnectAll();
this._stopRegistrationTimer();
if (this._audio) {
this._audio._unbind();
}
this._destroyStream();
this._destroyPublisher();
this._destroyAudioHelper();
if (this._networkInformation && typeof this._networkInformation.removeEventListener === 'function') {
this._networkInformation.removeEventListener('change', this._publishNetworkChange);
}
if (typeof window !== 'undefined' && window.removeEventListener) {
window.removeEventListener('beforeunload', this._boundConfirmClose);
window.removeEventListener('unload', this._boundDestroy);
window.removeEventListener('pagehide', this._boundDestroy);
}
this._setState(Device.State.Destroyed);
}
/**
* Disconnect all {@link Call}s.
*/
disconnectAll(): void {
const calls = this._calls.splice(0);
calls.forEach((call: Call) => call.disconnect());
if (this._activeCall) {
this._activeCall.disconnect();
}
}
/**
* Returns the {@link Edge} value the {@link Device} is currently connected
* to. The value will be `null` when the {@link Device} is offline.
*/
get edge(): string | null {
return this._edge;
}
/**
* Whether the Device is currently on an active Call.
*/
get isBusy(): boolean {
return !!this._activeCall;
}
/**
* Register the `Device` to the Twilio backend, allowing it to receive calls.
*/
async register(): Promise<void> {
if (this.state !== Device.State.Unregistered) {
throw new InvalidStateError(
`Attempt to register when device is in state "${this.state}". ` +
`Must be "${Device.State.Unregistered}".`,
);
}
this._setState(Device.State.Registering);
const stream = await (this._streamConnectedPromise || this._setupStream());
const streamReadyPromise = new Promise(resolve => {
this.once(Device.State.Registered, resolve);
});
await this._sendPresence(true);
await streamReadyPromise;
}
/**
* Get the state of this {@link Device} instance
*/
get state(): Device.State {
return this._state;
}
/**
* Get the token used by this {@link Device}.
*/
get token(): string | null {
return this._token;
}
/**
* String representation of {@link Device} instance.
* @private
*/
toString() {
return '[Twilio.Device instance]';
}
/**
* Unregister the `Device` to the Twilio backend, disallowing it to receive
* calls.
*/
async unregister(): Promise<void> {
if (this.state !== Device.State.Registered) {
throw new InvalidStateError(
`Attempt to unregister when device is in state "${this.state}". ` +
`Must be "${Device.State.Registered}".`,
);
}
this._shouldReRegister = false;
const stream = await this._streamConnectedPromise;
const streamOfflinePromise = new Promise(resolve => {
stream.on('offline', resolve);
});
await this._sendPresence(false);
await streamOfflinePromise;
}
/**
* Set the options used within the {@link Device}.
* @param options
*/
updateOptions(options: Device.Options = { }): void {
if (this.state === Device.State.Destroyed) {
throw new InvalidStateError(
`Attempt to "updateOptions" when device is in state "${this.state}".`,
);
}
this._options = { ...this._defaultOptions, ...this._options, ...options };
const originalChunderURIs: Set<string> = new Set(this._chunderURIs);
const chunderw = typeof this._options.chunderw === 'string'
? [this._options.chunderw]
: Array.isArray(this._options.chunderw) && this._options.chunderw;
const newChunderURIs = this._chunderURIs = (
chunderw || getChunderURIs(
this._options.edge,
undefined,
this._log.warn.bind(this._log),
)
).map((uri: string) => `wss://${uri}/signal`);
let hasChunderURIsChanged =
originalChunderURIs.size !== newChunderURIs.length;
if (!hasChunderURIsChanged) {
for (const uri of newChunderURIs) {
if (!originalChunderURIs.has(uri)) {
hasChunderURIsChanged = true;
break;
}
}
}
if (this.isBusy && hasChunderURIsChanged) {
throw new InvalidStateError('Cannot change Edge while on an active Call');
}
this._log.setDefaultLevel(
typeof this._options.logLevel === 'number'
? this._options.logLevel
: LogLevels.ERROR,
);
if (this._options.dscp) {
if (!this._options.rtcConstraints) {
this._options.rtcConstraints = { };
}
(this._options.rtcConstraints as any).optional = [{ googDscp: true }];
}
for (const name of Object.keys(Device._defaultSounds)) {
const soundDef: ISoundDefinition = Device._defaultSounds[name];
const defaultUrl: string = `${C.SOUNDS_BASE_URL}/${soundDef.filename}.${Device.extension}`
+ `?cache=${C.RELEASE_VERSION}`;
const soundUrl: string = this._options.sounds && this._options.sounds[name as Device.SoundName] || defaultUrl;
const sound: any = new (this._options.Sound || Sound)(name, soundUrl, {
audioContext: this._options.disableAudioContextSounds ? null : Device.audioContext,
maxDuration: soundDef.maxDuration,
shouldLoop: soundDef.shouldLoop,
});
this._soundcache.set(name as Device.SoundName, sound);
}
this._setupAudioHelper();
this._setupPublisher();
if (hasChunderURIsChanged && this._streamConnectedPromise) {
this._setupStream();
}
// Setup close protection and make sure we clean up ongoing calls on unload.
if (
typeof window !== 'undefined' &&
typeof window.addEventListener === 'function' &&
this._options.closeProtection
) {
window.removeEventListener('beforeunload', this._boundConfirmClose);
window.addEventListener('beforeunload', this._boundConfirmClose);
}
}
/**
* Update the token used by this {@link Device} to connect to Twilio.
* @param token
*/
updateToken(token: string) {
if (this.state === Device.State.Destroyed) {
throw new InvalidStateError(
`Attempt to "updateToken" when device is in state "${this.state}".`,
);
}
if (typeof token !== 'string') {
throw new InvalidArgumentError(INVALID_TOKEN_MESSAGE);
}
this._token = token;
if (this._stream) {
this._stream.setToken(this._token);
}
if (this._publisher) {
this._publisher.setToken(this._token);
}
}
/**
* Called on window's beforeunload event if closeProtection is enabled,
* preventing users from accidentally navigating away from an active call.
* @param event
*/
private _confirmClose(event: any): string {
if (!this._activeCall) { return ''; }
const closeProtection: boolean | string = this._options.closeProtection || false;
const confirmationMsg: string = typeof closeProtection !== 'string'
? 'A call is currently in-progress. Leaving or reloading this page will end the call.'
: closeProtection;
(event || window.event).returnValue = confirmationMsg;
return confirmationMsg;
}
/**
* Create the default Insights payload
* @param call
*/
private _createDefaultPayload = (call?: Call): Record<string, any> => {
const payload: Record<string, any> = {
aggressive_nomination: this._options.forceAggressiveIceNomination,
browser_extension: this._isBrowserExtension,
dscp: !!this._options.dscp,
ice_restart_enabled: true,
platform: rtc.getMediaEngine(),
sdk_version: C.RELEASE_VERSION,
};
function setIfDefined(propertyName: string, value: string | undefined | null) {
if (value) { payload[propertyName] = value; }
}
if (call) {
const callSid = call.parameters.CallSid;
setIfDefined('call_sid', /^TJ/.test(callSid) ? undefined : callSid);
setIfDefined('temp_call_sid', call.outboundConnectionId);
setIfDefined('audio_codec', call.codec);
payload.direction = call.direction;
}
setIfDefined('gateway', this._stream && this._stream.gateway);
setIfDefined('region', this._stream && this._stream.region);
return payload;
}
/**
* Destroy the AudioHelper.
*/
private _destroyAudioHelper() {
if (!this._audio) { return; }
this._audio.removeAllListeners();
this._audio = null;
}
/**
* Destroy the publisher.
*/
private _destroyPublisher() {
// Attempt to destroy non-existent publisher.
if (!this._publisher) { return; }
this._publisher = null;
}
/**
* Destroy the connection to the signaling server.
*/
private _destroyStream() {
if (this._stream) {
this._stream.destroy();
this._stream = null;
}
this._streamConnectedPromise = null;
}
/**
* Find a {@link Call} by its CallSid.
* @param callSid
*/
private _findCall(callSid: string): Call | null {
return this._calls.find(call => call.parameters.CallSid === callSid
|| call.outboundConnectionId === callSid) || null;
}
/**
* Create a new {@link Call}.
* @param twimlParams - A flat object containing key:value pairs to be sent to the TwiML app.
* @param options - Options to be used to instantiate the {@link Call}.
*/
private async _makeCall(twimlParams: Record<string, string>, options?: Call.Options): Promise<Call> {
if (typeof Device._isUnifiedPlanDefault === 'undefined') {
throw new InvalidStateError('Device has not been initialized.');
}
const config: Call.Config = {
audioHelper: this._audio,
getUserMedia,
isUnifiedPlanDefault: Device._isUnifiedPlanDefault,
pstream: await (this._streamConnectedPromise || this._setupStream()),
publisher: this._publisher,
soundcache: this._soundcache,
};
options = Object.assign({
MediaStream: this._options.MediaStream || rtc.PeerConnection,
beforeAccept: (currentCall: Call) => {
if (!this._activeCall || this._activeCall === currentCall) {
return;
}
this._activeCall.disconnect();
this._removeCall(this._activeCall);
},
codecPreferences: this._options.codecPreferences,
dialtonePlayer: Device._dialtonePlayer,
dscp: this._options.dscp,
forceAggressiveIceNomination: this._options.forceAggressiveIceNomination,
getInputStream: (): MediaStream | null => this._options.fileInputStream || this._callInputStream,
getSinkIds: (): string[] => this._callSinkIds,
maxAverageBitrate: this._options.maxAverageBitrate,
preflight: this._options.preflight,
rtcConstraints: this._options.rtcConstraints,
shouldPlayDisconnect: () => this._enabledSounds.disconnect,
twimlParams,
}, options);
const call = new (this._options.Call || Call)(config, options);
call.once('accept', () => {
this._removeCall(call);
this._activeCall = call;
if (this._audio) {
this._audio._maybeStartPollingVolume();
}
if (call.direction === Call.CallDirection.Outgoing && this._enabledSounds.outgoing) {
this._soundcache.get(Device.SoundName.Outgoing).play();
}
const data: any = { edge: this._edge || this._region };
if (this._options.edge) {
data['selected_edge'] = Array.isArray(this._options.edge)
? this._options.edge
: [this._options.edge];
}
this._publisher.info('settings', 'edge', data, call);
});
call.addListener('error', (error: TwilioError) => {
if (call.status() === 'closed') {
this._removeCall(call);
}
if (this._audio) {
this._audio._maybeStopPollingVolume();
}
this._maybeStopIncomingSound();
});
call.once('cancel', () => {
this._log.info(`Canceled: ${call.parameters.CallSid}`);
this._removeCall(call);
if (this._audio) {
this._audio._maybeStopPollingVolume();
}
this._maybeStopIncomingSound();
});
call.once('disconnect', () => {
if (this._audio) {
this._audio._maybeStopPollingVolume();
}
this._removeCall(call);
});
call.once('reject', () => {
this._log.info(`Rejected: ${call.parameters.CallSid}`);
if (this._audio) {
this._audio._maybeStopPollingVolume();
}
this._removeCall(call);
this._maybeStopIncomingSound();
});
call.once('transportClose', () => {
if (call.status() !== Call.State.Pending) {
return;
}
if (this._audio) {
this._audio._maybeStopPollingVolume();
}
this._removeCall(call);
this._maybeStopIncomingSound();
});
return call;
}
/**
* Stop the incoming sound if no {@link Call}s remain.
*/