-
Notifications
You must be signed in to change notification settings - Fork 706
/
Copy pathsession-manager.ts
1603 lines (1450 loc) · 58.6 KB
/
session-manager.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 } from "../../../api/info.js";
import { Invitation } from "../../../api/invitation.js";
import { InvitationAcceptOptions } from "../../../api/invitation-accept-options.js";
import { Inviter } from "../../../api/inviter.js";
import { InviterInviteOptions } from "../../../api/inviter-invite-options.js";
import { InviterOptions } from "../../../api/inviter-options.js";
import { Message } from "../../../api/message.js";
import { Messager } from "../../../api/messager.js";
import { Notification } from "../../../api/notification.js";
import { Referral } from "../../../api/referral.js";
import { Registerer } from "../../../api/registerer.js";
import { RegistererOptions } from "../../../api/registerer-options.js";
import { RegistererRegisterOptions } from "../../../api/registerer-register-options.js";
import { RegistererState } from "../../../api/registerer-state.js";
import { RegistererUnregisterOptions } from "../../../api/registerer-unregister-options.js";
import { RequestPendingError } from "../../../api/exceptions/request-pending.js";
import { Session } from "../../../api/session.js";
import { SessionInviteOptions } from "../../../api/session-invite-options.js";
import { SessionReferOptions } from "../../../api/session-refer-options.js";
import { SessionState } from "../../../api/session-state.js";
import { UserAgent } from "../../../api/user-agent.js";
import { UserAgentOptions } from "../../../api/user-agent-options.js";
import { UserAgentState } from "../../../api/user-agent-state.js";
import { Logger } from "../../../core/log/logger.js";
import { OutgoingRequest } from "../../../core/messages/outgoing-request.js";
import { URI } from "../../../grammar/uri.js";
import { SessionDescriptionHandler } from "../session-description-handler/session-description-handler.js";
import { SessionDescriptionHandlerOptions } from "../session-description-handler/session-description-handler-options.js";
import { Transport } from "../transport/transport.js";
import { ManagedSession } from "./managed-session.js";
import { SessionManagerDelegate } from "./session-manager-delegate.js";
import { SessionManagerOptions } from "./session-manager-options.js";
import { defaultManagedSessionFactory } from "./managed-session-factory-default.js";
/**
* A session manager for SIP.js sessions.
* @public
*/
export class SessionManager {
/** Delegate. */
public delegate: SessionManagerDelegate | undefined;
/** Sessions being managed. */
public managedSessions: Array<ManagedSession> = [];
/** User agent which created sessions being managed. */
public userAgent: UserAgent;
private attemptingReconnection = false;
private logger: Logger;
private options: Required<SessionManagerOptions>;
private optionsPingFailure = false;
private optionsPingRequest?: OutgoingRequest;
private optionsPingRunning = false;
private optionsPingTimeout?: ReturnType<typeof setTimeout>;
private registrationAttemptTimeout?: ReturnType<typeof setTimeout>;
private registerer?: Registerer;
private registererOptions?: RegistererOptions;
private registererRegisterOptions: RegistererRegisterOptions;
private shouldBeConnected = false;
private shouldBeRegistered = false;
/**
* Constructs a new instance of the `SessionManager` class.
* @param server - SIP WebSocket Server URL.
* @param options - Options bucket. See {@link SessionManagerOptions} for details.
*/
constructor(server: string, options: SessionManagerOptions = {}) {
// Delegate
this.delegate = options.delegate;
// Copy options
this.options = {
// Defaults
...{
aor: "",
autoStop: true,
delegate: {},
iceStopWaitingOnServerReflexive: false,
managedSessionFactory: defaultManagedSessionFactory(),
maxSimultaneousSessions: 2,
media: {},
optionsPingInterval: -1,
optionsPingRequestURI: "",
reconnectionAttempts: 3,
reconnectionDelay: 4,
registrationRetry: false,
registrationRetryInterval: 3,
registerGuard: null,
registererOptions: {},
registererRegisterOptions: {},
sendDTMFUsingSessionDescriptionHandler: false,
userAgentOptions: {}
},
...SessionManager.stripUndefinedProperties(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(`Connected`);
if (this.delegate && this.delegate.onServerConnect) {
this.delegate.onServerConnect();
}
// Attempt to register if we are supposed to be registered
if (this.shouldBeRegistered) {
this.register();
}
// Start OPTIONS pings if we are to be pinging
if (this.options.optionsPingInterval > 0) {
this.optionsPingStart();
}
},
// Handle connection with server lost
onDisconnect: async (error?: Error): Promise<void> => {
this.logger.log(`Disconnected`);
// Stop OPTIONS ping if need be.
let optionsPingFailure = false;
if (this.options.optionsPingInterval > 0) {
optionsPingFailure = this.optionsPingFailure;
this.optionsPingFailure = false;
this.optionsPingStop();
}
// Let delgate know we have disconnected
if (this.delegate && this.delegate.onServerDisconnect) {
this.delegate.onServerDisconnect(error);
}
// If the user called `disconnect` a graceful cleanup will be done therein.
// Only cleanup if network/server dropped the connection.
// Only reconnect if network/server dropped the connection
if (error || optionsPingFailure) {
// There is no transport at this point, so we are not expecting to be able to
// send messages much less get responses. So just dispose of everything without
// waiting for anything to succeed.
if (this.registerer) {
this.logger.log(`Disposing of registerer...`);
this.registerer.dispose().catch((e: Error) => {
this.logger.debug(`Error occurred disposing of registerer after connection with server was lost.`);
this.logger.debug(e.toString());
});
this.registerer = undefined;
}
this.managedSessions
.slice()
.map((el) => el.session)
.forEach(async (session) => {
this.logger.log(`Disposing of session...`);
session.dispose().catch((e: Error) => {
this.logger.debug(`Error occurred disposing of a session after connection with server was lost.`);
this.logger.debug(e.toString());
});
});
// Attempt to reconnect if we are supposed to be connected.
if (this.shouldBeConnected) {
this.attemptReconnection();
}
}
},
// Handle incoming invitations
onInvite: (invitation: Invitation): void => {
this.logger.log(`[${invitation.id}] Received INVITE`);
// Guard against a maximum number of pre-existing sessions.
// 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.
const maxSessions = this.options.maxSimultaneousSessions;
if (maxSessions !== 0 && this.managedSessions.length > maxSessions) {
this.logger.warn(`[${invitation.id}] Session already in progress, rejecting INVITE...`);
invitation
.reject()
.then(() => {
this.logger.log(`[${invitation.id}] Rejected INVITE`);
})
.catch((error: Error) => {
this.logger.error(`[${invitation.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(invitation);
} else {
this.logger.warn(`[${invitation.id}] No handler available, rejecting INVITE...`);
invitation
.reject()
.then(() => {
this.logger.log(`[${invitation.id}] Rejected INVITE`);
})
.catch((error: Error) => {
this.logger.error(`[${invitation.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);
}
});
},
// Handle incoming notifications
onNotify: (notification: Notification): void => {
notification.accept().then(() => {
if (this.delegate && this.delegate.onNotificationReceived) {
this.delegate.onNotificationReceived(notification);
}
});
}
};
// RegistererOptions
this.registererOptions = {
...options.registererOptions
};
// RegistererRegisterOptions
this.registererRegisterOptions = {
...options.registererRegisterOptions
};
// Retry registration on failure or rejection.
if (this.options.registrationRetry) {
// If the register request is rejected, try again...
this.registererRegisterOptions.requestDelegate = this.registererRegisterOptions.requestDelegate || {};
const existingOnReject = this.registererRegisterOptions.requestDelegate.onReject;
this.registererRegisterOptions.requestDelegate.onReject = (response) => {
existingOnReject && existingOnReject(response);
// If at first we don't succeed, try try again...
this.attemptRegistration();
};
}
// Use the SIP.js logger
this.logger = this.userAgent.getLogger("sip.SessionManager");
// Monitor network connectivity and attempt reconnection and reregistration when we come online
window.addEventListener("online", () => {
this.logger.log(`Online`);
if (this.shouldBeConnected) {
this.connect();
}
});
// NOTE: The autoStop option does not currently work as one likley expects.
// This code is here because the "autoStop behavior" and this assoicated
// implemenation has been a recurring request. So instead of removing
// the implementation again (because it doesn't work) and then having
// to explain agian the issue over and over again to those who want it,
// we have included it here to break that cycle. The implementation is
// harmless and serves to provide an explaination for those interested.
if (this.options.autoStop) {
// Standard operation workflow will resume after this callback exits, meaning
// that any asynchronous operations are likely not going to be finished, especially
// if they are guaranteed to not be executed in the current tick (promises fall
// under this category, they will never be resolved synchronously by design).
window.addEventListener("beforeunload", async () => {
this.shouldBeConnected = false;
this.shouldBeRegistered = false;
if (this.userAgent.state !== UserAgentState.Stopped) {
// The stop() method returns a promise which will not resolve before the page unloads.
await this.userAgent.stop();
}
});
}
}
/**
* Strip properties with undefined values from options.
* This is a work around while waiting for missing vs undefined to be addressed (or not)...
* https://github.com/Microsoft/TypeScript/issues/13195
* @param options - Options to reduce
*/
private static stripUndefinedProperties(options: Partial<SessionManagerOptions>): Partial<SessionManagerOptions> {
return Object.keys(options).reduce((object, key) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((options as any)[key] !== undefined) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(object as any)[key] = (options as any)[key];
}
return object;
}, {});
}
/**
* The local media stream. Undefined if call not answered.
* @param session - Session to get the media stream from.
*/
public getLocalMediaStream(session: Session): MediaStream | undefined {
const sdh = 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.
* @param session - Session to get the media stream from.
*/
public getRemoteMediaStream(session: Session): MediaStream | undefined {
const sdh = 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.
* @param session - Session to get track from.
* @deprecated Use localMediaStream and get track from the stream.
*/
public getLocalAudioTrack(session: Session): MediaStreamTrack | undefined {
return this.getLocalMediaStream(session)
?.getTracks()
.find((track) => track.kind === "audio");
}
/**
* The local video track, if available.
* @param session - Session to get track from.
* @deprecated Use localMediaStream and get track from the stream.
*/
public getLocalVideoTrack(session: Session): MediaStreamTrack | undefined {
return this.getLocalMediaStream(session)
?.getTracks()
.find((track) => track.kind === "video");
}
/**
* The remote audio track, if available.
* @param session - Session to get track from.
* @deprecated Use remoteMediaStream and get track from the stream.
*/
public getRemoteAudioTrack(session: Session): MediaStreamTrack | undefined {
return this.getRemoteMediaStream(session)
?.getTracks()
.find((track) => track.kind === "audio");
}
/**
* The remote video track, if available.
* @param session - Session to get track from.
* @deprecated Use remoteMediaStream and get track from the stream.
*/
public getRemoteVideoTrack(session: Session): MediaStreamTrack | undefined {
return this.getRemoteMediaStream(session)
?.getTracks()
.find((track) => track.kind === "video");
}
/**
* Connect.
* @remarks
* If not started, starts the UserAgent connecting the WebSocket Transport.
* Otherwise reconnects the UserAgent's WebSocket Transport.
* Attempts will be made to reconnect as needed.
*/
public async connect(): Promise<void> {
this.logger.log(`Connecting UserAgent...`);
this.shouldBeConnected = true;
if (this.userAgent.state !== UserAgentState.Started) {
return this.userAgent.start();
}
return this.userAgent.reconnect();
}
/**
* Disconnect.
* @remarks
* If not stopped, stops the UserAgent disconnecting the WebSocket Transport.
*/
public async disconnect(): Promise<void> {
this.logger.log(`Disconnecting UserAgent...`);
if (this.userAgent.state === UserAgentState.Stopped) {
return Promise.resolve();
}
this.shouldBeConnected = false;
this.shouldBeRegistered = false;
this.registerer = undefined;
return this.userAgent.stop();
}
/**
* Return true if transport is 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.
* Attempts will be made to re-register as needed.
*/
public async register(registererRegisterOptions?: RegistererRegisterOptions): Promise<void> {
this.logger.log(`Registering UserAgent...`);
this.shouldBeRegistered = true;
if (registererRegisterOptions !== undefined) {
this.registererRegisterOptions = {
...registererRegisterOptions
};
}
if (!this.registerer) {
this.registerer = new Registerer(this.userAgent, this.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();
}
// If we transition to an unregister state, attempt to get back to a registered state.
if (this.shouldBeRegistered) {
this.attemptRegistration();
}
break;
case RegistererState.Terminated:
break;
default:
throw new Error("Unknown registerer state.");
}
});
}
return this.attemptRegistration(true);
}
/**
* 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 async unregister(registererUnregisterOptions?: RegistererUnregisterOptions): Promise<void> {
this.logger.log(`Unregistering UserAgent...`);
this.shouldBeRegistered = false;
if (!this.registerer) {
this.logger.warn(`No registerer to unregister.`);
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 async call(
destination: string,
inviterOptions?: InviterOptions,
inviterInviteOptions?: InviterInviteOptions
): Promise<Inviter> {
this.logger.log(`Beginning Session...`);
// Guard against a maximum number of pre-existing sessions.
// 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.
const maxSessions = this.options.maxSimultaneousSessions;
if (maxSessions !== 0 && this.managedSessions.length > maxSessions) {
return Promise.reject(new Error("Maximum number of sessions 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;
}
// If utilizing early media, add a handler to catch 183 Session Progress
// messages and then to play the associated remote media (the early media).
if (inviterOptions.earlyMedia) {
inviterInviteOptions = inviterInviteOptions || {};
inviterInviteOptions.requestDelegate = inviterInviteOptions.requestDelegate || {};
const existingOnProgress = inviterInviteOptions.requestDelegate.onProgress;
inviterInviteOptions.requestDelegate.onProgress = (response) => {
if (response.message.statusCode === 183) {
this.setupRemoteMedia(inviter);
}
existingOnProgress && existingOnProgress(response);
};
}
// TODO: Any existing onSessionDescriptionHandler is getting clobbered here.
// If we get a server reflexive candidate, stop waiting on ICE gathering to complete.
// The candidate is a server reflexive candidate; the ip indicates an intermediary
// address assigned by the STUN server to represent the candidate's peer anonymously.
if (this.options.iceStopWaitingOnServerReflexive) {
inviterOptions.delegate = inviterOptions.delegate || {};
inviterOptions.delegate.onSessionDescriptionHandler = (sessionDescriptionHandler) => {
if (!(sessionDescriptionHandler instanceof SessionDescriptionHandler)) {
throw new Error("Session description handler not instance of SessionDescriptionHandler");
}
sessionDescriptionHandler.peerConnectionDelegate = {
onicecandidate: (event) => {
if (event.candidate?.type === "srflx") {
this.logger.log(`[${inviter.id}] Found srflx ICE candidate, stop waiting...`);
// In sip.js > 0.20.1 this cast should be removed as iceGatheringComplete will be public
const sdh = sessionDescriptionHandler as SessionDescriptionHandler & {
iceGatheringComplete: () => void;
};
sdh.iceGatheringComplete();
}
}
};
};
}
// 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 inviter;
});
}
/**
* Hangup a call.
* @param session - Session to hangup.
* @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 `onCallHangup` delegate method to determine if and when call is ended.
*/
public async hangup(session: Session): Promise<void> {
this.logger.log(`[${session.id}] Hangup...`);
if (!this.sessionExists(session)) {
return Promise.reject(new Error("Session does not exist."));
}
return this.terminate(session);
}
/**
* Answer an incoming call.
* @param session - Session to answer.
* @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 async answer(session: Session, invitationAcceptOptions?: InvitationAcceptOptions): Promise<void> {
this.logger.log(`[${session.id}] Accepting Invitation...`);
if (!this.sessionExists(session)) {
return Promise.reject(new Error("Session does not exist."));
}
if (!(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 session.accept(invitationAcceptOptions);
}
/**
* Decline an incoming call.
* @param session - Session to decline.
* @remarks
* Reject an incoming INVITE request.
* Resolves with the response is sent, otherwise rejects.
* Use `onCallHangup` delegate method to determine if and when call is ended.
*/
public async decline(session: Session): Promise<void> {
this.logger.log(`[${session.id}] Rejecting Invitation...`);
if (!this.sessionExists(session)) {
return Promise.reject(new Error("Session does not exist."));
}
if (!(session instanceof Invitation)) {
return Promise.reject(new Error("Session not instance of Invitation."));
}
return session.reject();
}
/**
* Hold call
* @param session - Session to hold.
* @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 async hold(session: Session): Promise<void> {
this.logger.log(`[${session.id}] Holding session...`);
return this.setHold(session, true);
}
/**
* Unhold call.
* @param session - Session to unhold.
* @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 async unhold(session: Session): Promise<void> {
this.logger.log(`[${session.id}] Unholding session...`);
return this.setHold(session, false);
}
/**
* Hold state.
* @param session - Session to check.
* @remarks
* True if session is on hold.
*/
public isHeld(session: Session): boolean {
const managedSession = this.sessionManaged(session);
return managedSession ? managedSession.held : false;
}
/**
* Mute call.
* @param session - Session to mute.
* @remarks
* Disable sender's media tracks.
*/
public mute(session: Session): void {
this.logger.log(`[${session.id}] Disabling media tracks...`);
this.setMute(session, true);
}
/**
* Unmute call.
* @param session - Session to unmute.
* @remarks
* Enable sender's media tracks.
*/
public unmute(session: Session): void {
this.logger.log(`[${session.id}] Enabling media tracks...`);
this.setMute(session, false);
}
/**
* Mute state.
* @param session - Session to check.
* @remarks
* True if sender's media track is disabled.
*/
public isMuted(session: Session): boolean {
const managedSession = this.sessionManaged(session);
return managedSession ? managedSession.muted : false;
}
/**
* Send DTMF.
* @param session - Session to send on.
* @remarks
* Send an INFO request with content type application/dtmf-relay.
* @param tone - Tone to send.
*/
public async sendDTMF(session: Session, tone: string): Promise<void> {
this.logger.log(`[${session.id}] Sending DTMF...`);
// Validate tone
if (!/^[0-9A-D#*,]$/.exec(tone)) {
return Promise.reject(new Error("Invalid DTMF tone."));
}
if (!this.sessionExists(session)) {
return Promise.reject(new Error("Session does not exist."));
}
this.logger.log(`[${session.id}] Sending DTMF tone: ${tone}`);
if (this.options.sendDTMFUsingSessionDescriptionHandler) {
if (!session.sessionDescriptionHandler) {
return Promise.reject(new Error("Session desciption handler undefined."));
}
if (!session.sessionDescriptionHandler.sendDtmf(tone)) {
return Promise.reject(new Error("Failed to send DTMF"));
}
return Promise.resolve();
} else {
// 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
// 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
const dtmf = tone;
const duration = 2000;
const body = {
contentDisposition: "render",
contentType: "application/dtmf-relay",
content: "Signal=" + dtmf + "\r\nDuration=" + duration
};
const requestOptions = { body };
return session.info({ requestOptions }).then(() => {
return;
});
}
}
/**
* Transfer.
* @param session - Session with the transferee to transfer.
* @param target - The referral target.
* @remarks
* If target is a Session this is an attended transfer completion (REFER with Replaces),
* otherwise this is a blind transfer (REFER). Attempting an attended transfer
* completion on a call that has not been answered will be rejected. To implement
* an attended transfer with early completion, hangup the call with the target
* and execute a blind transfer to the target.
*/
public async transfer(session: Session, target: Session | string, options?: SessionReferOptions): Promise<void> {
this.logger.log(`[${session.id}] Referring session...`);
if (target instanceof Session) {
return session.refer(target, options).then(() => {
return;
});
}
const uri = UserAgent.makeURI(target);
if (!uri) {
return Promise.reject(new Error(`Failed to create a valid URI from "${target}"`));
}
return session.refer(uri, options).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 async message(destination: string, message: string): Promise<void> {
this.logger.log(`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 `reconnectionAttempts` times.
* @param reconnectionAttempt - Current attempt number.
*/
private attemptReconnection(reconnectionAttempt = 1): void {
const reconnectionAttempts = this.options.reconnectionAttempts;
const reconnectionDelay = this.options.reconnectionDelay;
if (!this.shouldBeConnected) {
this.logger.log(`Should not be connected currently`);
return; // If intentionally disconnected, don't reconnect.
}
if (this.attemptingReconnection) {
this.logger.log(`Reconnection attempt already in progress`);
}
if (reconnectionAttempt > reconnectionAttempts) {
this.logger.log(`Reconnection maximum attempts reached`);
return;
}
if (reconnectionAttempt === 1) {
this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying`);
} else {
this.logger.log(
`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - trying in ${reconnectionDelay} seconds`
);
}
this.attemptingReconnection = true;
setTimeout(
() => {
if (!this.shouldBeConnected) {
this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - aborted`);
this.attemptingReconnection = false;
return; // If intentionally disconnected, don't reconnect.
}
this.userAgent
.reconnect()
.then(() => {
this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - succeeded`);
this.attemptingReconnection = false;
})
.catch((error: Error) => {
this.logger.log(`Reconnection attempt ${reconnectionAttempt} of ${reconnectionAttempts} - failed`);
this.logger.error(error.message);
this.attemptingReconnection = false;
this.attemptReconnection(++reconnectionAttempt);
});
},
reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000
);
}
/**
* Register to receive calls.
* @param withoutDelay - If true attempt immediately, otherwise wait `registrationRetryInterval`.
*/
private attemptRegistration(withoutDelay = false): Promise<void> {
this.logger.log(`Registration attempt ${withoutDelay ? "without delay" : ""}`);
if (!this.shouldBeRegistered) {
this.logger.log(`Should not be registered currently`);
return Promise.resolve();
}
// It only makes sense to have one attempt in progress at a time.
// Perhaps we shall (or should) try once again.
if (this.registrationAttemptTimeout !== undefined) {
this.logger.log(`Registration attempt already in progress`);
return Promise.resolve();
}
// Helper function to send the register request.
const _register = (): Promise<void> => {
// If we do not have a registerer, it is not worth trying to register.
if (!this.registerer) {
this.logger.log(`Registerer undefined`);
return Promise.resolve();
}
// If the WebSocket transport is not connected, it is not worth trying to register.
// Perhpas we shall (or should) try once we are connected.
if (!this.isConnected()) {
this.logger.log(`User agent not connected`);
return Promise.resolve();
}
// If the UserAgent is stopped, it is not worth trying to register.
// Perhaps we shall (or should) try once the UserAgent is running.
if (this.userAgent.state === UserAgentState.Stopped) {
this.logger.log(`User agent stopped`);
return Promise.resolve();
}
// If no guard defined, we are good to proceed without any further ado.
if (!this.options.registerGuard) {
return this.registerer.register(this.registererRegisterOptions).then(() => {
return;
});
}
// Otherwise check to make sure the guard does not want us halt.
return this.options
.registerGuard()
.catch((error) => {
this.logger.log(`Register guard rejected will making registration attempt`);
throw error;
})
.then((halt) => {
if (halt || !this.registerer) {
return Promise.resolve();
}
return this.registerer.register(this.registererRegisterOptions).then(() => {
return;
});
});
};
// Compute an amount of time in seconds to wait before sending another register request.
// This is a small attempt to avoid DOS attacking our own backend in the event that a
// relatively large number of clients sychonously keep retrying register reqeusts.
// This is known to happen when the backend goes down for a period and all clients
// are attempting to register again - the backend gets slammed with synced reqeusts.
const computeRegistrationTimeout = (lowerBound: number): number => {
const upperBound = lowerBound * 2;
return 1000 * (Math.random() * (upperBound - lowerBound) + lowerBound);
};
// Send register request after a delay
return new Promise<void>((resolve, reject) => {
this.registrationAttemptTimeout = setTimeout(
() => {
_register()
.then(() => {
this.registrationAttemptTimeout = undefined;