-
Notifications
You must be signed in to change notification settings - Fork 708
/
Copy pathsimple-user.ts
1099 lines (987 loc) · 36.1 KB
/
simple-user.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 {
Info,
Invitation,
InvitationAcceptOptions,
Inviter,
InviterInviteOptions,
InviterOptions,
Message,
Messager,
Referral,
Registerer,
RegistererOptions,
RegistererRegisterOptions,
RegistererState,
RegistererUnregisterOptions,
RequestPendingError,
Session,
SessionInviteOptions,
SessionState,
UserAgent,
UserAgentOptions,
UserAgentState
} from "../../../api";
import { Logger } from "../../../core";
import { SessionDescriptionHandler, SessionDescriptionHandlerOptions } from "../session-description-handler";
import { Transport } from "../transport";
import { SimpleUserDelegate } from "./simple-user-delegate";
import { SimpleUserOptions } from "./simple-user-options";
/**
* A simple SIP user class.
* @remarks
* While this class is completely functional for simple use cases, it is not intended
* to provide an interface which is suitable for most (must less all) applications.
* While this class has many limitations (for example, it only handles a single concurrent session),
* it is, however, intended to serve as a simple example of using the SIP.js API.
* @public
*/
export class SimpleUser {
/** Delegate. */
public delegate: SimpleUserDelegate | undefined;
private attemptingReconnection = false;
private connectRequested = false;
private logger: Logger;
private held = false;
private muted = false;
private options: SimpleUserOptions;
private registerer: Registerer | undefined = undefined;
private registerRequested = false;
private session: Session | undefined = undefined;
private userAgent: UserAgent;
/**
* Constructs a new instance of the `SimpleUser` class.
* @param server - SIP WebSocket Server URL.
* @param options - Options bucket. See {@link SimpleUserOptions} for details.
*/
constructor(server: string, options: SimpleUserOptions = {}) {
// Delegate
this.delegate = options.delegate;
// Copy options
this.options = { ...options };
// UserAgentOptions
const userAgentOptions: UserAgentOptions = {
...options.userAgentOptions
};
// Transport
if (!userAgentOptions.transportConstructor) {
userAgentOptions.transportConstructor = Transport;
}
// TransportOptions
if (!userAgentOptions.transportOptions) {
userAgentOptions.transportOptions = {
server
};
}
// URI
if (!userAgentOptions.uri) {
// If an AOR was provided, convert it to a URI
if (options.aor) {
const uri = UserAgent.makeURI(options.aor);
if (!uri) {
throw new Error(`Failed to create valid URI from ${options.aor}`);
}
userAgentOptions.uri = uri;
}
}
// UserAgent
this.userAgent = new UserAgent(userAgentOptions);
// UserAgent's delegate
this.userAgent.delegate = {
// Handle connection with server established
onConnect: (): void => {
this.logger.log(`[${this.id}] Connected`);
if (this.delegate && this.delegate.onServerConnect) {
this.delegate.onServerConnect();
}
if (this.registerer && this.registerRequested) {
this.logger.log(`[${this.id}] Registering...`);
this.registerer.register().catch((e: Error) => {
this.logger.error(`[${this.id}] Error occurred registering after connection with server was obtained.`);
this.logger.error(e.toString());
});
}
},
// Handle connection with server lost
onDisconnect: (error?: Error): void => {
this.logger.log(`[${this.id}] Disconnected`);
if (this.delegate && this.delegate.onServerDisconnect) {
this.delegate.onServerDisconnect(error);
}
if (this.session) {
this.logger.log(`[${this.id}] Hanging up...`);
this.hangup() // cleanup hung calls
.catch((e: Error) => {
this.logger.error(`[${this.id}] Error occurred hanging up call after connection with server was lost.`);
this.logger.error(e.toString());
});
}
if (this.registerer) {
this.logger.log(`[${this.id}] Unregistering...`);
this.registerer
.unregister() // cleanup invalid registrations
.catch((e: Error) => {
this.logger.error(`[${this.id}] Error occurred unregistering after connection with server was lost.`);
this.logger.error(e.toString());
});
}
// Only attempt to reconnect if network/server dropped the connection.
if (error) {
this.attemptReconnection();
}
},
// Handle incoming invitations
onInvite: (invitation: Invitation): void => {
this.logger.log(`[${this.id}] Received INVITE`);
// Guard against a pre-existing session. This implementation only supports one session at a time.
// However an incoming INVITE request may be received at any time and/or while in the process
// of sending an outgoing INVITE request. So we reject any incoming INVITE in those cases.
if (this.session) {
this.logger.warn(`[${this.id}] Session already in progress, rejecting INVITE...`);
invitation
.reject()
.then(() => {
this.logger.log(`[${this.id}] Rejected INVITE`);
})
.catch((error: Error) => {
this.logger.error(`[${this.id}] Failed to reject INVITE`);
this.logger.error(error.toString());
});
return;
}
// Use our configured constraints as options for any Inviter created as result of a REFER
const referralInviterOptions: InviterOptions = {
sessionDescriptionHandlerOptions: { constraints: this.constraints }
};
// Initialize our session
this.initSession(invitation, referralInviterOptions);
// Delegate
if (this.delegate && this.delegate.onCallReceived) {
this.delegate.onCallReceived();
} else {
this.logger.warn(`[${this.id}] No handler available, rejecting INVITE...`);
invitation
.reject()
.then(() => {
this.logger.log(`[${this.id}] Rejected INVITE`);
})
.catch((error: Error) => {
this.logger.error(`[${this.id}] Failed to reject INVITE`);
this.logger.error(error.toString());
});
}
},
// Handle incoming messages
onMessage: (message: Message): void => {
message.accept().then(() => {
if (this.delegate && this.delegate.onMessageReceived) {
this.delegate.onMessageReceived(message.request.body);
}
});
}
};
// Use the SIP.js logger
this.logger = this.userAgent.getLogger("sip.SimpleUser");
// Monitor network connectivity and attempt reconnection when we come online
window.addEventListener("online", () => {
this.logger.log(`[${this.id}] Online`);
this.attemptReconnection();
});
}
/**
* Instance identifier.
* @internal
*/
get id(): string {
return (this.options.userAgentOptions && this.options.userAgentOptions.displayName) || "Anonymous";
}
/** The local media stream. Undefined if call not answered. */
get localMediaStream(): MediaStream | undefined {
const sdh = this.session?.sessionDescriptionHandler;
if (!sdh) {
return undefined;
}
if (!(sdh instanceof SessionDescriptionHandler)) {
throw new Error("Session description handler not instance of web SessionDescriptionHandler");
}
return sdh.localMediaStream;
}
/** The remote media stream. Undefined if call not answered. */
get remoteMediaStream(): MediaStream | undefined {
const sdh = this.session?.sessionDescriptionHandler;
if (!sdh) {
return undefined;
}
if (!(sdh instanceof SessionDescriptionHandler)) {
throw new Error("Session description handler not instance of web SessionDescriptionHandler");
}
return sdh.remoteMediaStream;
}
/**
* The local audio track, if available.
* @deprecated Use localMediaStream and get track from the stream.
*/
get localAudioTrack(): MediaStreamTrack | undefined {
return this.localMediaStream?.getTracks().find((track) => track.kind === "audio");
}
/**
* The local video track, if available.
* @deprecated Use localMediaStream and get track from the stream.
*/
get localVideoTrack(): MediaStreamTrack | undefined {
return this.localMediaStream?.getTracks().find((track) => track.kind === "video");
}
/**
* The remote audio track, if available.
* @deprecated Use remoteMediaStream and get track from the stream.
*/
get remoteAudioTrack(): MediaStreamTrack | undefined {
return this.remoteMediaStream?.getTracks().find((track) => track.kind === "audio");
}
/**
* The remote video track, if available.
* @deprecated Use remoteMediaStream and get track from the stream.
*/
get remoteVideoTrack(): MediaStreamTrack | undefined {
return this.remoteMediaStream?.getTracks().find((track) => track.kind === "video");
}
/**
* Connect.
* @remarks
* Start the UserAgent's WebSocket Transport.
*/
public connect(): Promise<void> {
this.logger.log(`[${this.id}] Connecting UserAgent...`);
this.connectRequested = true;
if (this.userAgent.state !== UserAgentState.Started) {
return this.userAgent.start();
}
return this.userAgent.reconnect();
}
/**
* Disconnect.
* @remarks
* Stop the UserAgent's WebSocket Transport.
*/
public disconnect(): Promise<void> {
this.logger.log(`[${this.id}] Disconnecting UserAgent...`);
this.connectRequested = false;
return this.userAgent.stop();
}
/**
* Return true if connected.
*/
public isConnected(): boolean {
return this.userAgent.isConnected();
}
/**
* Start receiving incoming calls.
* @remarks
* Send a REGISTER request for the UserAgent's AOR.
* Resolves when the REGISTER request is sent, otherwise rejects.
*/
public register(
registererOptions?: RegistererOptions,
registererRegisterOptions?: RegistererRegisterOptions
): Promise<void> {
this.logger.log(`[${this.id}] Registering UserAgent...`);
this.registerRequested = true;
if (!this.registerer) {
this.registerer = new Registerer(this.userAgent, registererOptions);
this.registerer.stateChange.addListener((state: RegistererState) => {
switch (state) {
case RegistererState.Initial:
break;
case RegistererState.Registered:
if (this.delegate && this.delegate.onRegistered) {
this.delegate.onRegistered();
}
break;
case RegistererState.Unregistered:
if (this.delegate && this.delegate.onUnregistered) {
this.delegate.onUnregistered();
}
break;
case RegistererState.Terminated:
this.registerer = undefined;
break;
default:
throw new Error("Unknown registerer state.");
}
});
}
return this.registerer.register(registererRegisterOptions).then(() => {
return;
});
}
/**
* Stop receiving incoming calls.
* @remarks
* Send an un-REGISTER request for the UserAgent's AOR.
* Resolves when the un-REGISTER request is sent, otherwise rejects.
*/
public unregister(registererUnregisterOptions?: RegistererUnregisterOptions): Promise<void> {
this.logger.log(`[${this.id}] Unregistering UserAgent...`);
this.registerRequested = false;
if (!this.registerer) {
return Promise.resolve();
}
return this.registerer.unregister(registererUnregisterOptions).then(() => {
return;
});
}
/**
* Make an outgoing call.
* @remarks
* Send an INVITE request to create a new Session.
* Resolves when the INVITE request is sent, otherwise rejects.
* Use `onCallAnswered` delegate method to determine if Session is established.
* @param destination - The target destination to call. A SIP address to send the INVITE to.
* @param inviterOptions - Optional options for Inviter constructor.
* @param inviterInviteOptions - Optional options for Inviter.invite().
*/
public call(
destination: string,
inviterOptions?: InviterOptions,
inviterInviteOptions?: InviterInviteOptions
): Promise<void> {
this.logger.log(`[${this.id}] Beginning Session...`);
if (this.session) {
return Promise.reject(new Error("Session already exists."));
}
const target = UserAgent.makeURI(destination);
if (!target) {
return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`));
}
// Use our configured constraints as InviterOptions if none provided
if (!inviterOptions) {
inviterOptions = {};
}
if (!inviterOptions.sessionDescriptionHandlerOptions) {
inviterOptions.sessionDescriptionHandlerOptions = {};
}
if (!inviterOptions.sessionDescriptionHandlerOptions.constraints) {
inviterOptions.sessionDescriptionHandlerOptions.constraints = this.constraints;
}
// Create a new Inviter for the outgoing Session
const inviter = new Inviter(this.userAgent, target, inviterOptions);
// Send INVITE
return this.sendInvite(inviter, inviterOptions, inviterInviteOptions).then(() => {
return;
});
}
/**
* Hangup a call.
* @remarks
* Send a BYE request, CANCEL request or reject response to end the current Session.
* Resolves when the request/response is sent, otherwise rejects.
* Use `onCallTerminated` delegate method to determine if and when call is ended.
*/
public hangup(): Promise<void> {
this.logger.log(`[${this.id}] Hangup...`);
return this.terminate();
}
/**
* Answer an incoming call.
* @remarks
* Accept an incoming INVITE request creating a new Session.
* Resolves with the response is sent, otherwise rejects.
* Use `onCallAnswered` delegate method to determine if and when call is established.
* @param invitationAcceptOptions - Optional options for Inviter.accept().
*/
public answer(invitationAcceptOptions?: InvitationAcceptOptions): Promise<void> {
this.logger.log(`[${this.id}] Accepting Invitation...`);
if (!this.session) {
return Promise.reject(new Error("Session does not exist."));
}
if (!(this.session instanceof Invitation)) {
return Promise.reject(new Error("Session not instance of Invitation."));
}
// Use our configured constraints as InvitationAcceptOptions if none provided
if (!invitationAcceptOptions) {
invitationAcceptOptions = {};
}
if (!invitationAcceptOptions.sessionDescriptionHandlerOptions) {
invitationAcceptOptions.sessionDescriptionHandlerOptions = {};
}
if (!invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints) {
invitationAcceptOptions.sessionDescriptionHandlerOptions.constraints = this.constraints;
}
return this.session.accept(invitationAcceptOptions);
}
/**
* Decline an incoming call.
* @remarks
* Reject an incoming INVITE request.
* Resolves with the response is sent, otherwise rejects.
* Use `onCallTerminated` delegate method to determine if and when call is ended.
*/
public decline(): Promise<void> {
this.logger.log(`[${this.id}] rejecting Invitation...`);
if (!this.session) {
return Promise.reject(new Error("Session does not exist."));
}
if (!(this.session instanceof Invitation)) {
return Promise.reject(new Error("Session not instance of Invitation."));
}
return this.session.reject();
}
/**
* Hold call
* @remarks
* Send a re-INVITE with new offer indicating "hold".
* Resolves when the re-INVITE request is sent, otherwise rejects.
* Use `onCallHold` delegate method to determine if request is accepted or rejected.
* See: https://tools.ietf.org/html/rfc6337
*/
public hold(): Promise<void> {
this.logger.log(`[${this.id}] holding session...`);
return this.setHold(true);
}
/**
* Unhold call.
* @remarks
* Send a re-INVITE with new offer indicating "unhold".
* Resolves when the re-INVITE request is sent, otherwise rejects.
* Use `onCallHold` delegate method to determine if request is accepted or rejected.
* See: https://tools.ietf.org/html/rfc6337
*/
public unhold(): Promise<void> {
this.logger.log(`[${this.id}] unholding session...`);
return this.setHold(false);
}
/**
* Hold state.
* @remarks
* True if session media is on hold.
*/
public isHeld(): boolean {
return this.held;
}
/**
* Mute call.
* @remarks
* Disable sender's media tracks.
*/
public mute(): void {
this.logger.log(`[${this.id}] disabling media tracks...`);
this.setMute(true);
}
/**
* Unmute call.
* @remarks
* Enable sender's media tracks.
*/
public unmute(): void {
this.logger.log(`[${this.id}] enabling media tracks...`);
this.setMute(false);
}
/**
* Mute state.
* @remarks
* True if sender's media track is disabled.
*/
public isMuted(): boolean {
return this.muted;
}
/**
* Send DTMF.
* @remarks
* Send an INFO request with content type application/dtmf-relay.
* @param tone - Tone to send.
*/
public sendDTMF(tone: string): Promise<void> {
this.logger.log(`[${this.id}] sending DTMF...`);
// As RFC 6086 states, sending DTMF via INFO is not standardized...
//
// Companies have been using INFO messages in order to transport
// Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are
// proprietary and have not been standardized.
// https://tools.ietf.org/html/rfc6086#section-2
//
// It is however widely supported based on this draft:
// https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00
// Validate tone
if (!/^[0-9A-D#*,]$/.exec(tone)) {
return Promise.reject(new Error("Invalid DTMF tone."));
}
if (!this.session) {
return Promise.reject(new Error("Session does not exist."));
}
// The UA MUST populate the "application/dtmf-relay" body, as defined
// earlier, with the button pressed and the duration it was pressed
// for. Technically, this actually requires the INFO to be generated
// when the user *releases* the button, however if the user has still
// not released a button after 5 seconds, which is the maximum duration
// supported by this mechanism, the UA should generate the INFO at that
// time.
// https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00#section-5.3
this.logger.log(`[${this.id}] Sending DTMF tone: ${tone}`);
const dtmf = tone;
const duration = 2000;
const body = {
contentDisposition: "render",
contentType: "application/dtmf-relay",
content: "Signal=" + dtmf + "\r\nDuration=" + duration
};
const requestOptions = { body };
return this.session.info({ requestOptions }).then(() => {
return;
});
}
/**
* Send a message.
* @remarks
* Send a MESSAGE request.
* @param destination - The target destination for the message. A SIP address to send the MESSAGE to.
*/
public message(destination: string, message: string): Promise<void> {
this.logger.log(`[${this.id}] sending message...`);
const target = UserAgent.makeURI(destination);
if (!target) {
return Promise.reject(new Error(`Failed to create a valid URI from "${destination}"`));
}
return new Messager(this.userAgent, target, message).message();
}
/** Media constraints. */
private get constraints(): { audio: boolean; video: boolean } {
let constraints = { audio: true, video: false }; // default to audio only calls
if (this.options.media?.constraints) {
constraints = { ...this.options.media.constraints };
}
return constraints;
}
/**
* Attempt reconnection up to `maxReconnectionAttempts` times.
* @param reconnectionAttempt - Current attempt number.
*/
private attemptReconnection(reconnectionAttempt = 1): void {
const reconnectionAttempts = this.options.reconnectionAttempts || 3;
const reconnectionDelay = this.options.reconnectionDelay || 4;
if (!this.connectRequested) {
this.logger.log(`[${this.id}] Reconnection not currently desired`);
return; // If intentionally disconnected, don't reconnect.
}
if (this.attemptingReconnection) {
this.logger.log(`[${this.id}] Reconnection attempt already in progress`);
}
if (reconnectionAttempt > reconnectionAttempts) {
this.logger.log(`[${this.id}] Reconnection maximum attempts reached`);
return;
}
if (reconnectionAttempt === 1) {
this.logger.log(`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`);
} else {
this.logger.log(
`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying in ${reconnectionDelay} seconds`
);
}
this.attemptingReconnection = true;
setTimeout(
() => {
if (!this.connectRequested) {
this.logger.log(
`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - aborted`
);
this.attemptingReconnection = false;
return; // If intentionally disconnected, don't reconnect.
}
this.userAgent
.reconnect()
.then(() => {
this.logger.log(
`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`
);
this.attemptingReconnection = false;
})
.catch((error: Error) => {
this.logger.log(
`[${this.id}] Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`
);
this.logger.error(error.message);
this.attemptingReconnection = false;
this.attemptReconnection(++reconnectionAttempt);
});
},
reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000
);
}
/** Helper function to remove media from html elements. */
private cleanupMedia(): void {
if (this.options.media) {
if (this.options.media.local) {
if (this.options.media.local.video) {
this.options.media.local.video.srcObject = null;
this.options.media.local.video.pause();
}
}
if (this.options.media.remote) {
if (this.options.media.remote.audio) {
this.options.media.remote.audio.srcObject = null;
this.options.media.remote.audio.pause();
}
if (this.options.media.remote.video) {
this.options.media.remote.video.srcObject = null;
this.options.media.remote.video.pause();
}
}
}
}
/** Helper function to enable/disable media tracks. */
private enableReceiverTracks(enable: boolean): void {
if (!this.session) {
throw new Error("Session does not exist.");
}
const sessionDescriptionHandler = this.session.sessionDescriptionHandler;
if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) {
throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");
}
const peerConnection = sessionDescriptionHandler.peerConnection;
if (!peerConnection) {
throw new Error("Peer connection closed.");
}
peerConnection.getReceivers().forEach((receiver) => {
if (receiver.track) {
receiver.track.enabled = enable;
}
});
}
/** Helper function to enable/disable media tracks. */
private enableSenderTracks(enable: boolean): void {
if (!this.session) {
throw new Error("Session does not exist.");
}
const sessionDescriptionHandler = this.session.sessionDescriptionHandler;
if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) {
throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");
}
const peerConnection = sessionDescriptionHandler.peerConnection;
if (!peerConnection) {
throw new Error("Peer connection closed.");
}
peerConnection.getSenders().forEach((sender) => {
if (sender.track) {
sender.track.enabled = enable;
}
});
}
/**
* Setup session delegate and state change handler.
* @param session - Session to setup
* @param referralInviterOptions - Options for any Inviter created as result of a REFER.
*/
private initSession(session: Session, referralInviterOptions?: InviterOptions): void {
// Set session
this.session = session;
// Call session created callback
if (this.delegate && this.delegate.onCallCreated) {
this.delegate.onCallCreated();
}
// Setup session state change handler
this.session.stateChange.addListener((state: SessionState) => {
if (this.session !== session) {
return; // if our session has changed, just return
}
this.logger.log(`[${this.id}] session state changed to ${state}`);
switch (state) {
case SessionState.Initial:
break;
case SessionState.Establishing:
break;
case SessionState.Established:
this.setupLocalMedia();
this.setupRemoteMedia();
if (this.delegate && this.delegate.onCallAnswered) {
this.delegate.onCallAnswered();
}
break;
case SessionState.Terminating:
// fall through
case SessionState.Terminated:
this.session = undefined;
this.cleanupMedia();
if (this.delegate && this.delegate.onCallHangup) {
this.delegate.onCallHangup();
}
break;
default:
throw new Error("Unknown session state.");
}
});
// Setup delegate
this.session.delegate = {
onInfo: (info: Info): void => {
// As RFC 6086 states, sending DTMF via INFO is not standardized...
//
// Companies have been using INFO messages in order to transport
// Dual-Tone Multi-Frequency (DTMF) tones. All mechanisms are
// proprietary and have not been standardized.
// https://tools.ietf.org/html/rfc6086#section-2
//
// It is however widely supported based on this draft:
// https://tools.ietf.org/html/draft-kaplan-dispatch-info-dtmf-package-00
// FIXME: TODO: We should reject correctly...
//
// If a UA receives an INFO request associated with an Info Package that
// the UA has not indicated willingness to receive, the UA MUST send a
// 469 (Bad Info Package) response (see Section 11.6), which contains a
// Recv-Info header field with Info Packages for which the UA is willing
// to receive INFO requests.
// https://tools.ietf.org/html/rfc6086#section-4.2.2
// No delegate
if (this.delegate?.onCallDTMFReceived === undefined) {
info.reject();
return;
}
// Invalid content type
const contentType = info.request.getHeader("content-type");
if (!contentType || !/^application\/dtmf-relay/i.exec(contentType)) {
info.reject();
return;
}
// Invalid body
const body = info.request.body.split("\r\n", 2);
if (body.length !== 2) {
info.reject();
return;
}
// Invalid tone
let tone: string | undefined;
const toneRegExp = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;
if (toneRegExp.test(body[0])) {
tone = body[0].replace(toneRegExp, "$2");
}
if (!tone) {
info.reject();
return;
}
// Invalid duration
let duration: number | undefined;
const durationRegExp = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;
if (durationRegExp.test(body[1])) {
duration = parseInt(body[1].replace(durationRegExp, "$2"), 10);
}
if (!duration) {
info.reject();
return;
}
info
.accept()
.then(() => {
if (this.delegate && this.delegate.onCallDTMFReceived) {
if (!tone || !duration) {
throw new Error("Tone or duration undefined.");
}
this.delegate.onCallDTMFReceived(tone, duration);
}
})
.catch((error: Error) => {
this.logger.error(error.message);
});
},
onRefer: (referral: Referral): void => {
referral
.accept()
.then(() => this.sendInvite(referral.makeInviter(referralInviterOptions), referralInviterOptions))
.catch((error: Error) => {
this.logger.error(error.message);
});
}
};
}
/** Helper function to init send then send invite. */
private sendInvite(
inviter: Inviter,
inviterOptions?: InviterOptions,
inviterInviteOptions?: InviterInviteOptions
): Promise<void> {
// Initialize our session
this.initSession(inviter, inviterOptions);
// Send the INVITE
return inviter.invite(inviterInviteOptions).then(() => {
this.logger.log(`[${this.id}] sent INVITE`);
});
}
/**
* Puts Session on hold.
* @param hold - Hold on if true, off if false.
*/
private setHold(hold: boolean): Promise<void> {
if (!this.session) {
return Promise.reject(new Error("Session does not exist."));
}
const session = this.session;
// Just resolve if we are already in correct state
if (this.held === hold) {
return Promise.resolve();
}
const sessionDescriptionHandler = this.session.sessionDescriptionHandler;
if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) {
throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");
}
const options: SessionInviteOptions = {
requestDelegate: {
onAccept: (): void => {
this.held = hold;
this.enableReceiverTracks(!this.held);
this.enableSenderTracks(!this.held && !this.muted);
if (this.delegate && this.delegate.onCallHold) {
this.delegate.onCallHold(this.held);
}
},
onReject: (): void => {
this.logger.warn(`[${this.id}] re-invite request was rejected`);
this.enableReceiverTracks(!this.held);
this.enableSenderTracks(!this.held && !this.muted);
if (this.delegate && this.delegate.onCallHold) {
this.delegate.onCallHold(this.held);
}
}
}
};
// Session properties used to pass options to the SessionDescriptionHandler:
//
// 1) Session.sessionDescriptionHandlerOptions
// SDH options for the initial INVITE transaction.
// - Used in all cases when handling the initial INVITE transaction as either UAC or UAS.
// - May be set directly at anytime.
// - May optionally be set via constructor option.
// - May optionally be set via options passed to Inviter.invite() or Invitation.accept().
//
// 2) Session.sessionDescriptionHandlerOptionsReInvite
// SDH options for re-INVITE transactions.
// - Used in all cases when handling a re-INVITE transaction as either UAC or UAS.
// - May be set directly at anytime.
// - May optionally be set via constructor option.
// - May optionally be set via options passed to Session.invite().
const sessionDescriptionHandlerOptions = session.sessionDescriptionHandlerOptionsReInvite as SessionDescriptionHandlerOptions;
sessionDescriptionHandlerOptions.hold = hold;
session.sessionDescriptionHandlerOptionsReInvite = sessionDescriptionHandlerOptions;
// Send re-INVITE
return this.session
.invite(options)
.then(() => {
// preemptively enable/disable tracks
this.enableReceiverTracks(!hold);
this.enableSenderTracks(!hold && !this.muted);
})
.catch((error: Error) => {
if (error instanceof RequestPendingError) {
this.logger.error(`[${this.id}] A hold request is already in progress.`);
}
throw error;
});
}
/**
* Puts Session on mute.
* @param mute - Mute on if true, off if false.
*/
private setMute(mute: boolean): void {
if (!this.session) {
this.logger.warn(`[${this.id}] A session is required to enabled/disable media tracks`);
return;
}
if (this.session.state !== SessionState.Established) {
this.logger.warn(`[${this.id}] An established session is required to enable/disable media tracks`);
return;
}
this.muted = mute;
this.enableSenderTracks(!this.held && !this.muted);
}
/** Helper function to attach local media to html elements. */
private setupLocalMedia(): void {
if (!this.session) {
throw new Error("Session does not exist.");
}
const mediaElement = this.options.media?.local?.video;