-
Notifications
You must be signed in to change notification settings - Fork 214
/
Call.java
2577 lines (2326 loc) · 117 KB
/
Call.java
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
/*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.telephony;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.ReceiveTimeout;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorContext;
import akka.actor.UntypedActorFactory;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.apache.commons.configuration.Configuration;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.mobicents.javax.servlet.sip.SipFactoryExt;
import org.mobicents.javax.servlet.sip.SipSessionExt;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import org.restcomm.connect.commons.configuration.RestcommConfiguration;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.fsm.Action;
import org.restcomm.connect.commons.fsm.FiniteStateMachine;
import org.restcomm.connect.commons.fsm.State;
import org.restcomm.connect.commons.fsm.Transition;
import org.restcomm.connect.commons.fsm.TransitionFailedException;
import org.restcomm.connect.commons.fsm.TransitionNotFoundException;
import org.restcomm.connect.commons.fsm.TransitionRollbackException;
import org.restcomm.connect.commons.patterns.Observe;
import org.restcomm.connect.commons.patterns.Observing;
import org.restcomm.connect.commons.patterns.StopObserving;
import org.restcomm.connect.commons.util.SdpUtils;
import org.restcomm.connect.dao.CallDetailRecordsDao;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.entities.CallDetailRecord;
import org.restcomm.connect.http.client.Downloader;
import org.restcomm.connect.http.client.HttpRequestDescriptor;
import org.restcomm.connect.mscontrol.api.messages.CloseMediaSession;
import org.restcomm.connect.mscontrol.api.messages.Collect;
import org.restcomm.connect.mscontrol.api.messages.CreateMediaSession;
import org.restcomm.connect.mscontrol.api.messages.JoinBridge;
import org.restcomm.connect.mscontrol.api.messages.JoinComplete;
import org.restcomm.connect.mscontrol.api.messages.JoinConference;
import org.restcomm.connect.mscontrol.api.messages.Leave;
import org.restcomm.connect.mscontrol.api.messages.Left;
import org.restcomm.connect.mscontrol.api.messages.MediaGroupResponse;
import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerStateChanged;
import org.restcomm.connect.mscontrol.api.messages.MediaSessionInfo;
import org.restcomm.connect.mscontrol.api.messages.Mute;
import org.restcomm.connect.mscontrol.api.messages.Play;
import org.restcomm.connect.mscontrol.api.messages.Record;
import org.restcomm.connect.mscontrol.api.messages.StartRecording;
import org.restcomm.connect.mscontrol.api.messages.Stop;
import org.restcomm.connect.mscontrol.api.messages.StopMediaGroup;
import org.restcomm.connect.mscontrol.api.messages.StopRecording;
import org.restcomm.connect.mscontrol.api.messages.Unmute;
import org.restcomm.connect.mscontrol.api.messages.UpdateMediaSession;
import org.restcomm.connect.telephony.api.Answer;
import org.restcomm.connect.telephony.api.BridgeStateChanged;
import org.restcomm.connect.telephony.api.CallFail;
import org.restcomm.connect.telephony.api.CallHoldStateChange;
import org.restcomm.connect.telephony.api.CallInfo;
import org.restcomm.connect.telephony.api.CallResponse;
import org.restcomm.connect.telephony.api.CallStateChanged;
import org.restcomm.connect.telephony.api.Cancel;
import org.restcomm.connect.telephony.api.ChangeCallDirection;
import org.restcomm.connect.telephony.api.ConferenceInfo;
import org.restcomm.connect.telephony.api.ConferenceResponse;
import org.restcomm.connect.telephony.api.CreateCall;
import org.restcomm.connect.telephony.api.Dial;
import org.restcomm.connect.telephony.api.GetCallInfo;
import org.restcomm.connect.telephony.api.GetCallObservers;
import org.restcomm.connect.telephony.api.Hangup;
import org.restcomm.connect.telephony.api.InitializeOutbound;
import org.restcomm.connect.telephony.api.Reject;
import org.restcomm.connect.telephony.api.RemoveParticipant;
import scala.concurrent.duration.Duration;
import javax.sdp.SdpException;
import javax.servlet.sip.Address;
import javax.servlet.sip.AuthInfo;
import javax.servlet.sip.ServletParseException;
import javax.servlet.sip.SipApplicationSession;
import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipServletMessage;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.SipSession;
import javax.servlet.sip.SipURI;
import javax.servlet.sip.TelURL;
import javax.sip.header.RecordRouteHeader;
import javax.sip.header.RouteHeader;
import javax.sip.message.Response;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Currency;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* @author quintana.thomas@gmail.com (Thomas Quintana)
* @author jean.deruelle@telestax.com (Jean Deruelle)
* @author amit.bhayani@telestax.com (Amit Bhayani)
* @author gvagenas@telestax.com (George Vagenas)
* @author henrique.rosa@telestax.com (Henrique Rosa)
*
*/
@Immutable
public final class Call extends UntypedActor {
// Logging
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
// Response Code for Media Server Failure
private static final int MEDIA_SERVER_FAILURE_RESPONSE_CODE = 569;
// Define possible directions.
private static final String INBOUND = "inbound";
private static final String OUTBOUND_API = "outbound-api";
private static final String OUTBOUND_DIAL = "outbound-dial";
// Call Hold actions
private static final String CALL_ON_HOLD_ACTION = "action=onHold";
private static final String CALL_OFF_HOLD_ACTION = "action=offHold";
// Finite State Machine
private final FiniteStateMachine fsm;
private final State uninitialized;
private final State initializing;
private final State waitingForAnswer;
private final State queued;
private final State failingBusy;
private final State ringing;
private final State busy;
private final State notFound;
private final State canceling;
private final State canceled;
private final State failingNoAnswer;
private final State noAnswer;
private final State dialing;
private final State updatingMediaSession;
private final State inProgress;
private final State joining;
private final State leaving;
private final State stopping;
private final State completed;
private final State failed;
private final State inDialogRequest;
private boolean fail;
// SIP runtime stuff
private final SipFactory factory;
private String apiVersion;
private Sid accountId;
private String name;
private SipURI from;
private javax.servlet.sip.URI to;
// custom headers for SIP Out https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out
private Map<String, String> headers;
private String username;
private String password;
private CreateCall.Type type;
private long timeout;
private SipServletRequest invite;
private SipServletRequest inDialogInvite;
private SipServletResponse lastResponse;
private boolean isFromApi;
// Call runtime stuff.
private final Sid id;
private final String instanceId;
private CallStateChanged.State external;
private String direction;
private String forwardedFrom;
private DateTime created;
private DateTime callUpdatedTime;
private final List<ActorRef> observers;
private boolean receivedBye;
private boolean sentBye;
private boolean muted;
private boolean webrtc;
private boolean initialInviteOkSent;
// Conferencing
private ActorRef conference;
private boolean conferencing;
private Sid conferenceSid;
// Call Bridging
private ActorRef bridge;
// Media Session Control runtime stuff
private final ActorRef msController;
private MediaSessionInfo mediaSessionInfo;
// Media Group runtime stuff
private CallDetailRecord outgoingCallRecord;
private CallDetailRecordsDao recordsDao;
private DaoManager daoManager;
private boolean liveCallModification;
private boolean recording;
private URI recordingUri;
private Sid recordingSid;
private Sid parentCallSid;
// Runtime Setting
private Configuration runtimeSettings;
private Configuration configuration;
private boolean disableSdpPatchingOnUpdatingMediaSession;
private Sid inboundCallSid;
private boolean inboundConfirmCall;
private int collectTimeout;
private String collectFinishKey;
private boolean collectSipInfoDtmf = false;
private boolean enable200OkDelay;
private boolean outboundToIms;
private String imsProxyAddress;
private int imsProxyPort;
private boolean actAsImsUa;
private boolean isOnHold;
private int callDuration;
private DateTime recordingStart;
private long recordingDuration;
private HttpRequestDescriptor requestCallback;
ActorRef downloader = null;
ActorSystem system = null;
private URI statusCallback;
private String statusCallbackMethod;
private List<String> statusCallbackEvent;
public static enum CallbackState {
INITIATED("initiated"), RINGING("ringing"), ANSWERED("answered"), COMPLETED("completed");
private final String text;
private CallbackState(final String text) {
this.text = text;
}
@Override
public String toString() {
return text;
}
};
public Call(final SipFactory factory, final ActorRef mediaSessionController, final Configuration configuration,
final URI statusCallback, final String statusCallbackMethod, final List<String> statusCallbackEvent) {
super();
final ActorRef source = self();
this.system = context().system();
this.statusCallback = statusCallback;
this.statusCallbackMethod = statusCallbackMethod;
this.statusCallbackEvent = statusCallbackEvent;
if (statusCallback != null) {
downloader = downloader();
}
// States for the FSM
this.uninitialized = new State("uninitialized", null, null);
this.initializing = new State("initializing", new Initializing(source), null);
this.waitingForAnswer = new State("waiting for answer", new WaitingForAnswer(source), null);
this.queued = new State("queued", new Queued(source), null);
this.ringing = new State("ringing", new Ringing(source), null);
this.failingBusy = new State("failing busy", new FailingBusy(source), null);
this.busy = new State("busy", new Busy(source), null);
this.notFound = new State("not found", new NotFound(source), null);
//This time the --new Canceling(source)-- is an ActionOnState. Overloaded constructor is used here
this.canceling = new State("canceling", new Canceling(source));
this.canceled = new State("canceled", new Canceled(source), null);
this.failingNoAnswer = new State("failing no answer", new FailingNoAnswer(source), null);
this.noAnswer = new State("no answer", new NoAnswer(source), null);
this.dialing = new State("dialing", new Dialing(source), null);
this.updatingMediaSession = new State("updating media session", new UpdatingMediaSession(source), null);
this.inProgress = new State("in progress", new InProgress(source), null);
this.joining = new State("joining", new Joining(source), null);
this.leaving = new State("leaving", new Leaving(source), null);
this.stopping = new State("stopping", new Stopping(source), null);
this.completed = new State("completed", new Completed(source), null);
this.failed = new State("failed", new Failed(source), null);
this.inDialogRequest = new State("InDialogRequest", new InDialogRequest(source), null);
// Transitions for the FSM
final Set<Transition> transitions = new HashSet<Transition>();
transitions.add(new Transition(this.uninitialized, this.ringing));
transitions.add(new Transition(this.uninitialized, this.queued));
transitions.add(new Transition(this.uninitialized, this.canceled));
transitions.add(new Transition(this.uninitialized, this.completed));
transitions.add(new Transition(this.queued, this.canceled));
transitions.add(new Transition(this.queued, this.initializing));
transitions.add(new Transition(this.ringing, this.busy));
transitions.add(new Transition(this.ringing, this.notFound));
transitions.add(new Transition(this.ringing, this.canceling));
transitions.add(new Transition(this.ringing, this.canceled));
transitions.add(new Transition(this.ringing, this.failingNoAnswer));
transitions.add(new Transition(this.ringing, this.failingBusy));
transitions.add(new Transition(this.ringing, this.noAnswer));
transitions.add(new Transition(this.ringing, this.initializing));
transitions.add(new Transition(this.ringing, this.updatingMediaSession));
transitions.add(new Transition(this.ringing, this.completed));
transitions.add(new Transition(this.ringing, this.stopping));
transitions.add(new Transition(this.ringing, this.failed));
transitions.add(new Transition(this.initializing, this.canceling));
transitions.add(new Transition(this.initializing, this.dialing));
transitions.add(new Transition(this.initializing, this.failed));
transitions.add(new Transition(this.initializing, this.inProgress));
transitions.add(new Transition(this.initializing, this.waitingForAnswer));
transitions.add(new Transition(this.initializing, this.stopping));
transitions.add(new Transition(this.waitingForAnswer, this.inProgress));
transitions.add(new Transition(this.waitingForAnswer, this.joining));
transitions.add(new Transition(this.waitingForAnswer, this.canceling));
transitions.add(new Transition(this.waitingForAnswer, this.completed));
transitions.add(new Transition(this.waitingForAnswer, this.stopping));
transitions.add(new Transition(this.dialing, this.canceling));
transitions.add(new Transition(this.dialing, this.stopping));
transitions.add(new Transition(this.dialing, this.failingBusy));
transitions.add(new Transition(this.dialing, this.ringing));
transitions.add(new Transition(this.dialing, this.failed));
transitions.add(new Transition(this.dialing, this.failingNoAnswer));
transitions.add(new Transition(this.dialing, this.noAnswer));
transitions.add(new Transition(this.dialing, this.updatingMediaSession));
transitions.add(new Transition(this.inProgress, this.stopping));
transitions.add(new Transition(this.inProgress, this.joining));
transitions.add(new Transition(this.inProgress, this.leaving));
transitions.add(new Transition(this.inProgress, this.failed));
transitions.add(new Transition(this.inProgress, this.inDialogRequest));
transitions.add(new Transition(this.joining, this.inProgress));
transitions.add(new Transition(this.joining, this.stopping));
transitions.add(new Transition(this.joining, this.failed));
transitions.add(new Transition(this.leaving, this.inProgress));
transitions.add(new Transition(this.leaving, this.stopping));
transitions.add(new Transition(this.leaving, this.failed));
transitions.add(new Transition(this.leaving, this.completed));
transitions.add(new Transition(this.canceling, this.canceled));
transitions.add(new Transition(this.canceling, this.completed));
transitions.add(new Transition(this.failingBusy, this.busy));
transitions.add(new Transition(this.failingNoAnswer, this.noAnswer));
transitions.add(new Transition(this.failingNoAnswer, this.canceling));
transitions.add(new Transition(this.updatingMediaSession, this.inProgress));
transitions.add(new Transition(this.updatingMediaSession, this.failed));
transitions.add(new Transition(this.stopping, this.completed));
transitions.add(new Transition(this.stopping, this.failed));
transitions.add(new Transition(this.failed, this.completed));
transitions.add(new Transition(this.completed, this.stopping));
transitions.add(new Transition(this.completed, this.failed));
// FSM
this.fsm = new FiniteStateMachine(this.uninitialized, transitions);
// SIP runtime stuff.
this.factory = factory;
// Conferencing
this.conferencing = false;
// Media Session Control runtime stuff.
this.msController = mediaSessionController;
this.fail = false;
// Initialize the runtime stuff.
this.id = Sid.generate(Sid.Type.CALL);
this.instanceId = RestcommConfiguration.getInstance().getMain().getInstanceId();
this.created = DateTime.now();
this.observers = Collections.synchronizedList(new ArrayList<ActorRef>());
this.receivedBye = false;
// Media Group runtime stuff
this.liveCallModification = false;
this.recording = false;
this.configuration = configuration;
final Configuration runtime = this.configuration.subset("runtime-settings");
this.disableSdpPatchingOnUpdatingMediaSession = runtime.getBoolean("disable-sdp-patching-on-updating-mediasession", false);
this.enable200OkDelay = runtime.getBoolean("enable-200-ok-delay",false);
if(!runtime.subset("ims-authentication").isEmpty()){
final Configuration imsAuthentication = runtime.subset("ims-authentication");
this.actAsImsUa = imsAuthentication.getBoolean("act-as-ims-ua");
}
}
ActorRef downloader() {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new Downloader();
}
});
return system.actorOf(props);
}
private boolean is(State state) {
return this.fsm.state().equals(state);
}
private boolean isInbound() {
return INBOUND.equals(this.direction);
}
private boolean isOutbound() {
return !isInbound();
}
private CallResponse<CallInfo> info() {
try {
final String from = this.from.getUser();
String to = null;
if (this.to.isSipURI()) {
to = ((SipURI) this.to).getUser();
} else {
to = ((TelURL) this.to).getPhoneNumber();
}
final CallInfo info = new CallInfo(id, external, type, direction, created, forwardedFrom, name, from, to, invite, lastResponse, webrtc, muted, isFromApi, callUpdatedTime);
return new CallResponse<CallInfo>(info);
} catch (Exception e) {
if (logger.isInfoEnabled()) {
logger.info("Problem during preparing call info, exception {}",e);
}
}
return null;
}
private List<NameValuePair> dialStatusCallbackParameters(final CallbackState state) {
final List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("InstanceId", RestcommConfiguration.getInstance().getMain().getInstanceId()));
parameters.add(new BasicNameValuePair("AccountSid", accountId.toString()));
parameters.add(new BasicNameValuePair("CallSid", id.toString()));
parameters.add(new BasicNameValuePair("From", this.from.getUser()));
String to = null;
if (this.to.isSipURI()) {
to = ((SipURI) this.to).getUser();
} else {
to = ((TelURL) this.to).getPhoneNumber();
}
parameters.add(new BasicNameValuePair("To", to));
parameters.add(new BasicNameValuePair("Direction", direction));
parameters.add(new BasicNameValuePair("CallerName", from.getUser()));
parameters.add(new BasicNameValuePair("ForwardedFrom", forwardedFrom));
if (parentCallSid != null)
parameters.add(new BasicNameValuePair("ParentCallSid", parentCallSid.toString()));
parameters.add(new BasicNameValuePair("CallStatus", state.toString()));
if (state.equals(CallbackState.COMPLETED)) {
parameters.add(new BasicNameValuePair("CallDuration", String.valueOf(callDuration)));
//We never record an outgoing call leg, we only record parent call leg and both legs of the call
//are mixed down into a single channel
//The recording duration will be used only for REST-API created calls
if (recording && direction.equalsIgnoreCase("outbound-api")) {
if (recordingUri != null)
parameters.add(new BasicNameValuePair("RecordingUrl", recordingUri.toString()));
if (recordingSid != null)
parameters.add(new BasicNameValuePair("RecordingSid", recordingSid.toString()));
if (recordingDuration > -1)
parameters.add(new BasicNameValuePair("RecordingDuration", String.valueOf(recordingDuration)));
}
}
//RFC 2822 (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE, dd MMM YYYY HH:mm:ss ZZZZ");
final String timestamp = DateTime.now().toString(fmt);
parameters.add(new BasicNameValuePair("Timestamp", timestamp));
parameters.add(new BasicNameValuePair("CallbackSource", "call-progress-events"));
String sequence = "0";
switch (state) {
case INITIATED:
sequence = "0";
break;
case RINGING:
sequence = "1";
break;
case ANSWERED:
sequence = "2";
break;
case COMPLETED:
sequence = "3";
break;
default:
sequence = "0";
break;
}
parameters.add(new BasicNameValuePair("SequenceNumber", sequence));
if (logger.isDebugEnabled()) {
String msg = String.format("Created parameters for Call StatusCallback for state %s and sequence %s uri %s",state,sequence,statusCallback.toString());
logger.debug(msg);
}
return parameters;
}
private void executeStatusCallback(final CallbackState state) {
if (statusCallback != null) {
if (statusCallbackEvent.contains(state.toString())) {
if (logger.isDebugEnabled()) {
String msg = String.format("About to execute Call StatusCallback to %s for state %s",statusCallback.toString(), state.text);
logger.debug(msg);
}
if (statusCallbackMethod == null) {
statusCallbackMethod = "POST";
}
final List<NameValuePair> parameters = dialStatusCallbackParameters(state);
if (parameters != null) {
requestCallback = new HttpRequestDescriptor(statusCallback, statusCallbackMethod, parameters);
downloader.tell(requestCallback, null);
}
} else {
if (logger.isDebugEnabled()) {
String msg = String.format("Call StatusCallback did not run because state %s no in the statusCallbackEvent list", state.text);
logger.debug(msg);
}
}
} else if(logger.isInfoEnabled()){
logger.info("status callback is null");
}
}
private void forwarding(final Object message) {
// XXX does nothing
}
private SipURI getInitialIpAddressPort(SipServletMessage message) throws ServletParseException, UnknownHostException {
// Issue #268 - https://bitbucket.org/telestax/telscale-restcomm/issue/268
// First get the Initial Remote Address (real address that the request came from)
// Then check the following:
// 1. If contact header address is private network address
// 2. If there are no "Record-Route" headers (there is no proxy in the call)
// 3. If contact header address != real ip address
// Finally, if all of the above are true, create a SIP URI using the realIP address and the SIP port
// and store it to the sip session to be used as request uri later
SipURI uri = null;
try {
String realIP = message.getInitialRemoteAddr();
Integer realPort = message.getInitialRemotePort();
if (realPort == null || realPort == -1) {
realPort = 5060;
}
if (realPort == 0) {
realPort = message.getRemotePort();
}
final ListIterator<String> recordRouteHeaders = message.getHeaders("Record-Route");
final Address contactAddr = factory.createAddress(message.getHeader("Contact"));
InetAddress contactInetAddress = InetAddress.getByName(((SipURI) contactAddr.getURI()).getHost());
InetAddress inetAddress = InetAddress.getByName(realIP);
int remotePort = message.getRemotePort();
int contactPort = ((SipURI) contactAddr.getURI()).getPort();
String remoteAddress = message.getRemoteAddr();
// Issue #332: https://telestax.atlassian.net/browse/RESTCOMM-332
final String initialIpBeforeLB = message.getHeader("X-Sip-Balancer-InitialRemoteAddr");
String initialPortBeforeLB = message.getHeader("X-Sip-Balancer-InitialRemotePort");
String contactAddress = ((SipURI) contactAddr.getURI()).getHost();
if (initialIpBeforeLB != null) {
if (initialPortBeforeLB == null)
initialPortBeforeLB = "5060";
if(logger.isInfoEnabled()) {
logger.info("We are behind load balancer, storing Initial Remote Address " + initialIpBeforeLB + ":"
+ initialPortBeforeLB + " to the session for later use");
}
realIP = initialIpBeforeLB + ":" + initialPortBeforeLB;
uri = factory.createSipURI(null, realIP);
} else if (contactInetAddress.isSiteLocalAddress() && !recordRouteHeaders.hasNext()
&& !contactInetAddress.toString().equalsIgnoreCase(inetAddress.toString())) {
if(logger.isInfoEnabled()) {
logger.info("Contact header address " + contactAddr.toString()
+ " is a private network ip address, storing Initial Remote Address " + realIP + ":" + realPort
+ " to the session for later use");
}
realIP = realIP + ":" + realPort;
uri = factory.createSipURI(null, realIP);
}
} catch (Exception e) {
logger.warning("Exception while trying to get the Initial IP Address and Port: "+e);
}
return uri;
}
@Override
public void onReceive(Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef self = self();
final ActorRef sender = sender();
final State state = fsm.state();
if(logger.isInfoEnabled()) {
logger.info("********** Call's " + self().path() + " Current State: \"" + state.toString()+" direction: "+direction);
logger.info("********** Call " + self().path() + " Processing Message: \"" + klass.getName() + " sender : "
+ sender.path().toString());
}
if (Observe.class.equals(klass)) {
onObserve((Observe) message, self, sender);
} else if (StopObserving.class.equals(klass)) {
onStopObserving((StopObserving) message, self, sender);
} else if (GetCallObservers.class.equals(klass)) {
onGetCallObservers((GetCallObservers) message, self, sender);
} else if (GetCallInfo.class.equals(klass)) {
onGetCallInfo((GetCallInfo) message, sender);
} else if (InitializeOutbound.class.equals(klass)) {
onInitializeOutbound((InitializeOutbound) message, self, sender);
} else if (ChangeCallDirection.class.equals(klass)) {
onChangeCallDirection((ChangeCallDirection) message, self, sender);
} else if (Answer.class.equals(klass)) {
onAnswer((Answer) message, self, sender);
} else if (Dial.class.equals(klass)) {
onDial((Dial) message, self, sender);
} else if (Reject.class.equals(klass)) {
onReject((Reject) message, self, sender);
} else if (CallFail.class.equals(klass)) {
fsm.transition(message, failed);
} else if (JoinComplete.class.equals(klass)) {
onJoinComplete((JoinComplete) message, self, sender);
} else if (StartRecording.class.equals(klass)) {
onStartRecordingCall((StartRecording) message, self, sender);
} else if (StopRecording.class.equals(klass)) {
onStopRecordingCall((StopRecording) message, self, sender);
} else if (Cancel.class.equals(klass)) {
onCancel((Cancel) message, self, sender);
} else if (message instanceof ReceiveTimeout) {
onReceiveTimeout((ReceiveTimeout) message, self, sender);
} else if (message instanceof SipServletRequest) {
onSipServletRequest((SipServletRequest) message, self, sender);
} else if (message instanceof SipServletResponse) {
onSipServletResponse((SipServletResponse) message, self, sender);
} else if (Hangup.class.equals(klass)) {
onHangup((Hangup) message, self, sender);
} else if (org.restcomm.connect.telephony.api.NotFound.class.equals(klass)) {
onNotFound((org.restcomm.connect.telephony.api.NotFound) message, self, sender);
} else if (MediaServerControllerStateChanged.class.equals(klass)) {
onMediaServerControllerStateChanged((MediaServerControllerStateChanged) message, self, sender);
} else if (JoinConference.class.equals(klass)) {
onJoinConference((JoinConference) message, self, sender);
} else if (JoinBridge.class.equals(klass)) {
onJoinBridge((JoinBridge) message, self, sender);
} else if (Leave.class.equals(klass)) {
onLeave((Leave) message, self, sender);
} else if (Left.class.equals(klass)) {
onLeft((Left) message, self, sender);
} else if (Record.class.equals(klass)) {
onRecord((Record) message, self, sender);
} else if (Play.class.equals(klass)) {
onPlay((Play) message, self, sender);
} else if (Collect.class.equals(klass)) {
onCollect((Collect) message, self, sender);
} else if (StopMediaGroup.class.equals(klass)) {
onStopMediaGroup((StopMediaGroup) message, self, sender);
} else if (Mute.class.equals(klass)) {
onMute((Mute) message, self, sender);
} else if (Unmute.class.equals(klass)) {
onUnmute((Unmute) message, self, sender);
} else if (ConferenceResponse.class.equals(klass)) {
onConferenceResponse((ConferenceResponse) message);
} else if (BridgeStateChanged.class.equals(klass)) {
onBridgeStateChanged((BridgeStateChanged) message, self, sender);
} else if (CallHoldStateChange.class.equals(klass)) {
onCallHoldStateChange((CallHoldStateChange)message, sender);
}
}
private void onConferenceResponse(ConferenceResponse conferenceResponse) {
//ConferenceResponse received
ConferenceInfo ci = (ConferenceInfo) conferenceResponse.get();
if (logger.isInfoEnabled()) {
String infoMsg = String.format("Conference response, name %s, state %s, participants %d", ci.name(), ci.state(), ci.globalParticipants());
logger.info(infoMsg);
}
}
private void onCallHoldStateChange(CallHoldStateChange message, ActorRef sender) throws IOException{
if (logger.isInfoEnabled()) {
logger.info("CallHoldStateChange received, state: " + message.state() + " isOnHold " + isOnHold);
}
if(is(inProgress)){
if (!isOnHold && CallHoldStateChange.State.ONHOLD.equals(message.state())) {
final SipServletRequest messageRequest = invite.getSession().createRequest("MESSAGE");
messageRequest.setContent(CALL_ON_HOLD_ACTION, "text/plain");
messageRequest.send();
isOnHold = true;
} else if (isOnHold && CallHoldStateChange.State.OFFHOLD.equals(message.state())) {
final SipServletRequest messageRequest = invite.getSession().createRequest("MESSAGE");
messageRequest.setContent(CALL_OFF_HOLD_ACTION, "text/plain");
messageRequest.send();
isOnHold = false;
}
}
}
private void addCustomHeaders(SipServletMessage message) {
if (apiVersion != null)
message.addHeader("X-RestComm-ApiVersion", apiVersion);
if (accountId != null)
message.addHeader("X-RestComm-AccountSid", accountId.toString());
message.addHeader("X-RestComm-CallSid", instanceId+"-"+id.toString());
}
// Allow updating of the callInfo at the VoiceInterpreter so that we can do Dial SIP Screening
// (https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out) accurately from latest response
// received
private void sendCallInfoToObservers() {
for (final ActorRef observer : this.observers) {
observer.tell(info(), self());
}
}
private void processInfo(final SipServletRequest request) throws IOException {
//Seems we will receive DTMF over SIP INFO, we should start timeout timer
//to simulate the collect timeout when using the RMS
collectSipInfoDtmf = true;
context().setReceiveTimeout(Duration.create(collectTimeout, TimeUnit.SECONDS));
final SipServletResponse okay = request.createResponse(SipServletResponse.SC_OK);
addCustomHeaders(okay);
okay.send();
String digits = null;
if (request.getContentType().equalsIgnoreCase("application/dtmf-relay")) {
final String content = new String(request.getRawContent());
digits = content.split("\n")[0].replaceFirst("Signal=", "").trim();
} else {
digits = new String(request.getRawContent());
}
if (digits != null) {
MediaGroupResponse<String> infoResponse = new MediaGroupResponse<String>(digits);
for (final ActorRef observer : observers) {
observer.tell(infoResponse, self());
}
this.msController.tell(new Stop(), self());
}
}
/*
* ACTIONS
*/
private abstract class AbstractAction implements Action {
protected final ActorRef source;
public AbstractAction(final ActorRef source) {
super();
this.source = source;
}
}
private final class Queued extends AbstractAction {
public Queued(final ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
final InitializeOutbound request = (InitializeOutbound) message;
name = request.name();
from = request.from();
to = request.to();
apiVersion = request.apiVersion();
accountId = request.accountId();
username = request.username();
password = request.password();
type = request.type();
parentCallSid = request.getParentCallSid();
recordsDao = request.getDaoManager().getCallDetailRecordsDao();
isFromApi = request.isFromApi();
outboundToIms = request.isOutboundToIms();
imsProxyAddress = request.getImsProxyAddress();
imsProxyPort = request.getImsProxyPort();
String toHeaderString = to.toString();
if (toHeaderString.indexOf('?') != -1) {
// custom headers parsing for SIP Out
// https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out
headers = new HashMap<String, String>();
// we keep only the to URI without the headers
to = (SipURI) factory.createURI(toHeaderString.substring(0, toHeaderString.lastIndexOf('?')));
String headersString = toHeaderString.substring(toHeaderString.lastIndexOf('?') + 1);
StringTokenizer tokenizer = new StringTokenizer(headersString, "&");
while (tokenizer.hasMoreTokens()) {
String headerNameValue = tokenizer.nextToken();
String headerName = headerNameValue.substring(0, headerNameValue.lastIndexOf('='));
String headerValue = headerNameValue.substring(headerNameValue.lastIndexOf('=') + 1);
headers.put(headerName, headerValue);
}
}
timeout = request.timeout();
direction = request.isFromApi() ? OUTBOUND_API : OUTBOUND_DIAL;
webrtc = request.isWebrtc();
// Notify the observers.
external = CallStateChanged.State.QUEUED;
final CallStateChanged event = new CallStateChanged(external);
for (final ActorRef observer : observers) {
observer.tell(event, source);
}
if (recordsDao != null) {
CallDetailRecord cdr = recordsDao.getCallDetailRecord(id);
if (cdr == null) {
final CallDetailRecord.Builder builder = CallDetailRecord.builder();
builder.setSid(id);
builder.setInstanceId(RestcommConfiguration.getInstance().getMain().getInstanceId());
builder.setDateCreated(created);
builder.setAccountSid(accountId);
String toUser = null;
if(to.isSipURI()){
toUser = ((SipURI)to).getUser();
}
else{
toUser = ((TelURL)to).getPhoneNumber();
}
builder.setTo(toUser);
builder.setCallerName(name);
builder.setStartTime(new DateTime());
String fromString = (from.getUser() != null ? from.getUser() : "CALLS REST API");
builder.setFrom(fromString);
// builder.setForwardedFrom(callInfo.forwardedFrom());
// builder.setPhoneNumberSid(phoneId);
builder.setStatus(external.name());
builder.setDirection("outbound-api");
builder.setApiVersion(apiVersion);
builder.setPrice(new BigDecimal("0.00"));
// TODO implement currency property to be read from Configuration
builder.setPriceUnit(Currency.getInstance("USD"));
final StringBuilder buffer = new StringBuilder();
buffer.append("/").append(apiVersion).append("/Accounts/");
buffer.append(accountId.toString()).append("/Calls/");
buffer.append(id.toString());
final URI uri = URI.create(buffer.toString());
builder.setUri(uri);
builder.setCallPath(self().path().toString());
builder.setParentCallSid(parentCallSid);
outgoingCallRecord = builder.build();
recordsDao.addCallDetailRecord(outgoingCallRecord);
} else {
cdr.setStatus(external.name());
}
}
}
}
private final class Dialing extends AbstractAction {
public Dialing(final ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
final MediaServerControllerStateChanged response = (MediaServerControllerStateChanged) message;
final ActorRef self = self();
mediaSessionInfo = response.getMediaSession();
// Create a SIP invite to initiate a new session.
final SipURI uri;
if (!outboundToIms) {
final StringBuilder buffer = new StringBuilder();
buffer.append(((SipURI)to).getHost());
if (((SipURI)to).getPort() > -1) {
buffer.append(":").append(((SipURI)to).getPort());
}
String transport = ((SipURI)to).getTransportParam();
if (transport != null) {
buffer.append(";transport=").append(((SipURI)to).getTransportParam());
}
uri = factory.createSipURI(null, buffer.toString());
} else {
uri = factory.createSipURI(null, imsProxyAddress);
uri.setPort(imsProxyPort);
uri.setLrParam(true);
}
final SipApplicationSession application = factory.createApplicationSession();
application.setAttribute(Call.class.getName(), self);
String callId = null;
String userAgent = null;
if(outboundToIms && !configuration.subset("runtime-settings").subset("ims-authentication").isEmpty()){
final Configuration imsAuthentication = configuration.subset("runtime-settings").subset("ims-authentication");
final String callIdPrefix = imsAuthentication.getString("call-id-prefix");
userAgent = imsAuthentication.getString("user-agent");
callId = callIdPrefix + UUID.randomUUID().toString();
}
if (name != null && !name.isEmpty()) {
// Create the from address using the inital user displayed name
// Example: From: "Alice" <sip:userpart@host:port>
final Address fromAddress = factory.createAddress(from, name);
final Address toAddress = factory.createAddress(to);
invite = ((SipFactoryExt)factory).createRequestWithCallID(application, "INVITE", fromAddress, toAddress, callId);
} else {
invite = ((SipFactoryExt)factory).createRequestWithCallID(application, "INVITE", from, to, callId);
}
invite.pushRoute(uri);
if(userAgent!=null){
invite.setHeader("User-Agent", userAgent);
}
if (headers != null) {
// adding custom headers for SIP Out
// https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out
Set<Map.Entry<String, String>> entrySet = headers.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
invite.addHeader("X-" + entry.getKey(), entry.getValue());
}
}
addCustomHeaders(invite);
// invite.addHeader("X-RestComm-ApiVersion", apiVersion);
// invite.addHeader("X-RestComm-AccountSid", accountId.toString());
// invite.addHeader("X-RestComm-CallSid", id.toString());
final SipSession session = invite.getSession();
session.setHandler("CallManager");
// Issue: https://telestax.atlassian.net/browse/RESTCOMM-608
// If this is a call to Restcomm client or SIP URI bypass LB
if (logger.isInfoEnabled())
logger.info("bypassLoadBalancer is set to: "+RestcommConfiguration.getInstance().getMain().getBypassLbForClients());
if (RestcommConfiguration.getInstance().getMain().getBypassLbForClients()) {
if (type.equals(CreateCall.Type.CLIENT) || type.equals(CreateCall.Type.SIP)) {
((SipSessionExt) session).setBypassLoadBalancer(true);
((SipSessionExt) session).setBypassProxy(true);
}
}
String offer = null;
if (mediaSessionInfo.usesNat()) {
final String externalIp = mediaSessionInfo.getExternalAddress().getHostAddress();
final byte[] sdp = mediaSessionInfo.getLocalSdp().getBytes();
offer = SdpUtils.patch("application/sdp", sdp, externalIp);
} else {
offer = mediaSessionInfo.getLocalSdp();
}
offer = SdpUtils.endWithNewLine(offer);
invite.setContent(offer, "application/sdp");
// Send the invite.
invite.send();
// Set the timeout period.
final UntypedActorContext context = getContext();
context.setReceiveTimeout(Duration.create(timeout, TimeUnit.SECONDS));
executeStatusCallback(CallbackState.INITIATED);
}
}
private final class Ringing extends AbstractAction {
public Ringing(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if (message instanceof SipServletRequest) {
invite = (SipServletRequest) message;