-
Notifications
You must be signed in to change notification settings - Fork 214
/
VoiceInterpreter.java
3253 lines (3060 loc) · 158 KB
/
VoiceInterpreter.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.interpreter;
import akka.actor.ActorRef;
import akka.actor.ReceiveTimeout;
import akka.actor.UntypedActorContext;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.pattern.AskTimeoutException;
import akka.util.Timeout;
import org.apache.commons.configuration.Configuration;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.restcomm.connect.asr.AsrResponse;
import org.restcomm.connect.commons.cache.DiskCacheResponse;
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.StopObserving;
import org.restcomm.connect.commons.util.UriUtils;
import org.restcomm.connect.dao.CallDetailRecordsDao;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.NotificationsDao;
import org.restcomm.connect.dao.entities.CallDetailRecord;
import org.restcomm.connect.dao.entities.Notification;
import org.restcomm.connect.email.api.EmailResponse;
import org.restcomm.connect.fax.FaxResponse;
import org.restcomm.connect.http.client.DownloaderResponse;
import org.restcomm.connect.http.client.HttpRequestDescriptor;
import org.restcomm.connect.interpreter.rcml.Attribute;
import org.restcomm.connect.interpreter.rcml.End;
import org.restcomm.connect.interpreter.rcml.GetNextVerb;
import org.restcomm.connect.interpreter.rcml.Nouns;
import org.restcomm.connect.interpreter.rcml.ParserFailed;
import org.restcomm.connect.interpreter.rcml.Tag;
import org.restcomm.connect.interpreter.rcml.Verbs;
import org.restcomm.connect.mscontrol.api.messages.JoinComplete;
import org.restcomm.connect.mscontrol.api.messages.Left;
import org.restcomm.connect.mscontrol.api.messages.MediaGroupResponse;
import org.restcomm.connect.mscontrol.api.messages.Mute;
import org.restcomm.connect.mscontrol.api.messages.Play;
import org.restcomm.connect.mscontrol.api.messages.StartRecording;
import org.restcomm.connect.mscontrol.api.messages.StopMediaGroup;
import org.restcomm.connect.mscontrol.api.messages.Unmute;
import org.restcomm.connect.sms.api.SmsServiceResponse;
import org.restcomm.connect.sms.api.SmsSessionResponse;
import org.restcomm.connect.telephony.api.AddParticipant;
import org.restcomm.connect.telephony.api.Answer;
import org.restcomm.connect.telephony.api.BridgeManagerResponse;
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.CallManagerResponse;
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.ConferenceCenterResponse;
import org.restcomm.connect.telephony.api.ConferenceInfo;
import org.restcomm.connect.telephony.api.ConferenceModeratorPresent;
import org.restcomm.connect.telephony.api.ConferenceResponse;
import org.restcomm.connect.telephony.api.ConferenceStateChanged;
import org.restcomm.connect.telephony.api.CreateBridge;
import org.restcomm.connect.telephony.api.CreateCall;
import org.restcomm.connect.telephony.api.CreateConference;
import org.restcomm.connect.telephony.api.DestroyCall;
import org.restcomm.connect.telephony.api.DestroyConference;
import org.restcomm.connect.telephony.api.Dial;
import org.restcomm.connect.telephony.api.GetCallInfo;
import org.restcomm.connect.telephony.api.GetConferenceInfo;
import org.restcomm.connect.telephony.api.GetRelatedCall;
import org.restcomm.connect.telephony.api.Hangup;
import org.restcomm.connect.telephony.api.JoinCalls;
import org.restcomm.connect.telephony.api.Reject;
import org.restcomm.connect.telephony.api.RemoveParticipant;
import org.restcomm.connect.telephony.api.StartBridge;
import org.restcomm.connect.telephony.api.StopBridge;
import org.restcomm.connect.telephony.api.StopConference;
import org.restcomm.connect.tts.api.SpeechSynthesizerResponse;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;
import javax.servlet.sip.SipServletMessage;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.SipSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Currency;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static akka.pattern.Patterns.ask;
/**
* @author thomas.quintana@telestax.com (Thomas Quintana)
* @author jean.deruelle@telestax.com
* @author gvagenas@telestax.com
* @author amit.bhayani@telestax.com (Amit Bhayani)
* @author pavel.slegr@telestax.com
* @author maria.farooq@telestax.com
*/
public final class VoiceInterpreter extends BaseVoiceInterpreter {
// Logger.
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
// States for the FSM.
private final State startDialing;
private final State processingDialChildren;
private final State acquiringOutboundCallInfo;
private final State forking;
// private final State joiningCalls;
private final State creatingBridge;
private final State initializingBridge;
private final State bridging;
private final State bridged;
private final State finishDialing;
private final State acquiringConferenceInfo;
private final State joiningConference;
private final State conferencing;
private final State finishConferencing;
private final State downloadingRcml;
private final State downloadingFallbackRcml;
private final State initializingCall;
// private final State initializedCall;
private final State ready;
private final State notFound;
private final State rejecting;
private final State finished;
// FSM.
// The conference manager.
private final ActorRef conferenceManager;
// State for outbound calls.
private boolean isForking;
private List<ActorRef> dialBranches;
private List<Tag> dialChildren;
private Map<ActorRef, Tag> dialChildrenWithAttributes;
// The conferencing stuff
private int maxParticipantLimit = 40;
private ActorRef conference;
private Sid conferenceSid;
private ConferenceInfo conferenceInfo;
private ConferenceStateChanged.State conferenceState;
private boolean muteCall;
private boolean startConferenceOnEnter = true;
private boolean endConferenceOnExit = false;
private boolean confModeratorPresent = false;
private ActorRef confSubVoiceInterpreter;
private Attribute dialRecordAttribute;
private boolean dialActionExecuted = false;
private ActorRef sender;
private boolean liveCallModification = false;
private boolean recordingCall = true;
protected boolean isParserFailed = false;
protected boolean playWaitUrlPending = false;
Tag conferenceVerb;
List<URI> conferenceWaitUris;
private boolean playMusicForConference = false;
//Used for system apps, such as when WebRTC client is dialing out.
//The rcml will be used instead of download the RCML
private String rcml;
// Call bridging
private final ActorRef bridgeManager;
private ActorRef bridge;
private boolean beep;
private boolean enable200OkDelay;
// IMS authentication
private boolean asImsUa;
private String imsUaLogin;
private String imsUaPassword;
private String forwardedFrom;
public VoiceInterpreter(final Configuration configuration, final Sid account, final Sid phone, final String version,
final URI url, final String method, final URI fallbackUrl, final String fallbackMethod, final URI viStatusCallback,
final String statusCallbackMethod, final String referTarget, final String transferor, final String transferee,
final String emailAddress, final ActorRef callManager,
final ActorRef conferenceManager, final ActorRef bridgeManager, final ActorRef sms, final DaoManager storage, final ActorRef monitoring, final String rcml,
final boolean asImsUa, final String imsUaLogin, final String imsUaPassword) {
super();
final ActorRef source = self();
downloadingRcml = new State("downloading rcml", new DownloadingRcml(source), null);
downloadingFallbackRcml = new State("downloading fallback rcml", new DownloadingFallbackRcml(source), null);
initializingCall = new State("initializing call", new InitializingCall(source), null);
// initializedCall = new State("initialized call", new InitializedCall(source), new PostInitializedCall(source));
ready = new State("ready", new Ready(source), null);
notFound = new State("notFound", new NotFound(source), null);
rejecting = new State("rejecting", new Rejecting(source), null);
startDialing = new State("start dialing", new StartDialing(source), null);
processingDialChildren = new State("processing dial children", new ProcessingDialChildren(source), null);
acquiringOutboundCallInfo = new State("acquiring outbound call info", new AcquiringOutboundCallInfo(source), null);
forking = new State("forking", new Forking(source), null);
// joiningCalls = new State("joining calls", new JoiningCalls(source), null);
this.creatingBridge = new State("creating bridge", new CreatingBridge(source), null);
this.initializingBridge = new State("initializing bridge", new InitializingBridge(source), null);
this.bridging = new State("bridging", new Bridging(source), null);
bridged = new State("bridged", new Bridged(source), null);
finishDialing = new State("finish dialing", new FinishDialing(source), null);
acquiringConferenceInfo = new State("acquiring conference info", new AcquiringConferenceInfo(source), null);
joiningConference = new State("joining conference", new JoiningConference(source), null);
conferencing = new State("conferencing", new Conferencing(source), null);
finishConferencing = new State("finish conferencing", new FinishConferencing(source), null);
finished = new State("finished", new Finished(source), null);
/*
* dialing = new State("dialing", null, null); bridging = new State("bridging", null, null); conferencing = new
* State("conferencing", null, null);
*/
transitions.add(new Transition(acquiringAsrInfo, finished));
transitions.add(new Transition(acquiringSynthesizerInfo, finished));
transitions.add(new Transition(acquiringCallInfo, initializingCall));
transitions.add(new Transition(acquiringCallInfo, downloadingRcml));
transitions.add(new Transition(acquiringCallInfo, finished));
transitions.add(new Transition(acquiringCallInfo, ready));
transitions.add(new Transition(initializingCall, downloadingRcml));
transitions.add(new Transition(initializingCall, ready));
transitions.add(new Transition(initializingCall, finishDialing));
transitions.add(new Transition(initializingCall, hangingUp));
transitions.add(new Transition(initializingCall, finished));
transitions.add(new Transition(downloadingRcml, ready));
transitions.add(new Transition(downloadingRcml, notFound));
transitions.add(new Transition(downloadingRcml, downloadingFallbackRcml));
transitions.add(new Transition(downloadingRcml, hangingUp));
transitions.add(new Transition(downloadingRcml, finished));
transitions.add(new Transition(downloadingFallbackRcml, ready));
transitions.add(new Transition(downloadingFallbackRcml, hangingUp));
transitions.add(new Transition(downloadingFallbackRcml, finished));
transitions.add(new Transition(downloadingFallbackRcml, notFound));
transitions.add(new Transition(ready, initializingCall));
transitions.add(new Transition(ready, faxing));
transitions.add(new Transition(ready, sendingEmail));
transitions.add(new Transition(ready, pausing));
transitions.add(new Transition(ready, checkingCache));
transitions.add(new Transition(ready, caching));
transitions.add(new Transition(ready, synthesizing));
transitions.add(new Transition(ready, rejecting));
transitions.add(new Transition(ready, redirecting));
transitions.add(new Transition(ready, processingGatherChildren));
transitions.add(new Transition(ready, creatingRecording));
transitions.add(new Transition(ready, creatingSmsSession));
transitions.add(new Transition(ready, startDialing));
transitions.add(new Transition(ready, hangingUp));
transitions.add(new Transition(ready, finished));
transitions.add(new Transition(pausing, ready));
transitions.add(new Transition(pausing, finished));
transitions.add(new Transition(rejecting, finished));
transitions.add(new Transition(faxing, ready));
transitions.add(new Transition(faxing, finished));
transitions.add(new Transition(sendingEmail, ready));
transitions.add(new Transition(sendingEmail, finished));
transitions.add(new Transition(sendingEmail, finishDialing));
transitions.add(new Transition(checkingCache, caching));
transitions.add(new Transition(checkingCache, conferencing));
transitions.add(new Transition(caching, finished));
transitions.add(new Transition(caching, conferencing));
transitions.add(new Transition(caching, finishConferencing));
transitions.add(new Transition(playing, ready));
transitions.add(new Transition(playing, finishConferencing));
transitions.add(new Transition(playing, finished));
transitions.add(new Transition(synthesizing, finished));
transitions.add(new Transition(redirecting, ready));
transitions.add(new Transition(redirecting, finished));
transitions.add(new Transition(creatingRecording, finished));
transitions.add(new Transition(finishRecording, ready));
transitions.add(new Transition(finishRecording, finished));
transitions.add(new Transition(processingGatherChildren, finished));
transitions.add(new Transition(gathering, finished));
transitions.add(new Transition(finishGathering, ready));
transitions.add(new Transition(finishGathering, finishGathering));
transitions.add(new Transition(finishGathering, finished));
transitions.add(new Transition(creatingSmsSession, finished));
transitions.add(new Transition(sendingSms, ready));
transitions.add(new Transition(sendingSms, startDialing));
transitions.add(new Transition(sendingSms, finished));
transitions.add(new Transition(startDialing, processingDialChildren));
transitions.add(new Transition(startDialing, acquiringConferenceInfo));
transitions.add(new Transition(startDialing, faxing));
transitions.add(new Transition(startDialing, sendingEmail));
transitions.add(new Transition(startDialing, pausing));
transitions.add(new Transition(startDialing, checkingCache));
transitions.add(new Transition(startDialing, caching));
transitions.add(new Transition(startDialing, synthesizing));
transitions.add(new Transition(startDialing, redirecting));
transitions.add(new Transition(startDialing, processingGatherChildren));
transitions.add(new Transition(startDialing, creatingRecording));
transitions.add(new Transition(startDialing, creatingSmsSession));
transitions.add(new Transition(startDialing, startDialing));
transitions.add(new Transition(startDialing, hangingUp));
transitions.add(new Transition(startDialing, finished));
transitions.add(new Transition(processingDialChildren, processingDialChildren));
transitions.add(new Transition(processingDialChildren, forking));
transitions.add(new Transition(processingDialChildren, startDialing));
transitions.add(new Transition(processingDialChildren, checkingCache));
transitions.add(new Transition(processingDialChildren, sendingEmail));
transitions.add(new Transition(processingDialChildren, faxing));
transitions.add(new Transition(processingDialChildren, sendingSms));
transitions.add(new Transition(processingDialChildren, playing));
transitions.add(new Transition(processingDialChildren, ready));
transitions.add(new Transition(processingDialChildren, hangingUp));
transitions.add(new Transition(processingDialChildren, finished));
transitions.add(new Transition(forking, acquiringOutboundCallInfo));
transitions.add(new Transition(forking, finishDialing));
transitions.add(new Transition(forking, hangingUp));
transitions.add(new Transition(forking, finished));
transitions.add(new Transition(forking, ready));
transitions.add(new Transition(forking, checkingCache));
transitions.add(new Transition(forking, caching));
// transitions.add(new Transition(acquiringOutboundCallInfo, joiningCalls));
transitions.add(new Transition(acquiringOutboundCallInfo, hangingUp));
transitions.add(new Transition(acquiringOutboundCallInfo, finished));
transitions.add(new Transition(acquiringOutboundCallInfo, creatingBridge));
transitions.add(new Transition(creatingBridge, initializingBridge));
transitions.add(new Transition(creatingBridge, finishDialing));
transitions.add(new Transition(initializingBridge, bridging));
transitions.add(new Transition(initializingBridge, hangingUp));
transitions.add(new Transition(bridging, bridged));
transitions.add(new Transition(bridging, finishDialing));
transitions.add(new Transition(bridged, finishDialing));
transitions.add(new Transition(bridged, finished));
transitions.add(new Transition(finishDialing, ready));
transitions.add(new Transition(finishDialing, faxing));
transitions.add(new Transition(finishDialing, sendingEmail));
transitions.add(new Transition(finishDialing, pausing));
transitions.add(new Transition(finishDialing, checkingCache));
transitions.add(new Transition(finishDialing, caching));
transitions.add(new Transition(finishDialing, synthesizing));
transitions.add(new Transition(finishDialing, redirecting));
transitions.add(new Transition(finishDialing, processingGatherChildren));
transitions.add(new Transition(finishDialing, creatingRecording));
transitions.add(new Transition(finishDialing, creatingSmsSession));
transitions.add(new Transition(finishDialing, startDialing));
transitions.add(new Transition(finishDialing, hangingUp));
transitions.add(new Transition(finishDialing, finished));
transitions.add(new Transition(finishDialing, initializingCall));
transitions.add(new Transition(acquiringConferenceInfo, joiningConference));
transitions.add(new Transition(acquiringConferenceInfo, hangingUp));
transitions.add(new Transition(acquiringConferenceInfo, finished));
transitions.add(new Transition(joiningConference, conferencing));
transitions.add(new Transition(joiningConference, hangingUp));
transitions.add(new Transition(joiningConference, finished));
transitions.add(new Transition(conferencing, finishConferencing));
transitions.add(new Transition(conferencing, hangingUp));
transitions.add(new Transition(conferencing, finished));
transitions.add(new Transition(conferencing, checkingCache));
transitions.add(new Transition(conferencing, caching));
transitions.add(new Transition(conferencing, playing));
transitions.add(new Transition(conferencing, startDialing));
transitions.add(new Transition(conferencing, creatingSmsSession));
transitions.add(new Transition(conferencing, sendingEmail));
transitions.add(new Transition(finishConferencing, ready));
transitions.add(new Transition(finishConferencing, faxing));
transitions.add(new Transition(finishConferencing, sendingEmail));
transitions.add(new Transition(finishConferencing, pausing));
transitions.add(new Transition(finishConferencing, checkingCache));
transitions.add(new Transition(finishConferencing, caching));
transitions.add(new Transition(finishConferencing, synthesizing));
transitions.add(new Transition(finishConferencing, redirecting));
transitions.add(new Transition(finishConferencing, processingGatherChildren));
transitions.add(new Transition(finishConferencing, creatingRecording));
transitions.add(new Transition(finishConferencing, creatingSmsSession));
transitions.add(new Transition(finishConferencing, startDialing));
transitions.add(new Transition(finishConferencing, hangingUp));
transitions.add(new Transition(finishConferencing, finished));
transitions.add(new Transition(hangingUp, finished));
transitions.add(new Transition(hangingUp, finishConferencing));
transitions.add(new Transition(hangingUp, finishDialing));
transitions.add(new Transition(uninitialized, finished));
transitions.add(new Transition(notFound, finished));
// Initialize the FSM.
this.fsm = new FiniteStateMachine(uninitialized, transitions);
// Initialize the runtime stuff.
this.accountId = account;
this.phoneId = phone;
this.version = version;
this.url = url;
this.method = method;
this.fallbackUrl = fallbackUrl;
this.fallbackMethod = fallbackMethod;
this.viStatusCallback = viStatusCallback;
this.viStatusCallbackMethod = statusCallbackMethod;
this.referTarget = referTarget;
this.transferor = transferor;
this.transferee = transferee;
this.emailAddress = emailAddress;
this.configuration = configuration;
this.callManager = callManager;
this.conferenceManager = conferenceManager;
this.bridgeManager = bridgeManager;
this.smsService = sms;
this.smsSessions = new HashMap<Sid, ActorRef>();
this.storage = storage;
final Configuration runtime = configuration.subset("runtime-settings");
playMusicForConference = Boolean.parseBoolean(runtime.getString("play-music-for-conference","false"));
this.enable200OkDelay = this.configuration.subset("runtime-settings").getBoolean("enable-200-ok-delay",false);
this.downloader = downloader();
this.monitoring = monitoring;
this.rcml = rcml;
this.asImsUa = asImsUa;
this.imsUaLogin = imsUaLogin;
this.imsUaPassword = imsUaPassword;
}
private boolean is(State state) {
return this.fsm.state().equals(state);
}
private Notification notification(final int log, final int error, final String message) {
final Notification.Builder builder = Notification.builder();
final Sid sid = Sid.generate(Sid.Type.NOTIFICATION);
builder.setSid(sid);
builder.setAccountSid(accountId);
builder.setCallSid(callInfo.sid());
builder.setApiVersion(version);
builder.setLog(log);
builder.setErrorCode(error);
String base = configuration.subset("runtime-settings").getString("error-dictionary-uri");
try {
base = UriUtils.resolve(new URI(base)).toString();
} catch (URISyntaxException e) {
logger.error("URISyntaxException when trying to resolve Error-Dictionary URI: " + e);
}
StringBuilder buffer = new StringBuilder();
buffer.append(base);
if (!base.endsWith("/")) {
buffer.append("/");
}
buffer.append(error).append(".html");
final URI info = URI.create(buffer.toString());
builder.setMoreInfo(info);
builder.setMessageText(message);
final DateTime now = DateTime.now();
builder.setMessageDate(now);
if (request != null) {
builder.setRequestUrl(request.getUri());
builder.setRequestMethod(request.getMethod());
builder.setRequestVariables(request.getParametersAsString());
}
if (response != null) {
builder.setResponseHeaders(response.getHeadersAsString());
final String type = response.getContentType();
if (type.contains("text/xml") || type.contains("application/xml") || type.contains("text/html")) {
try {
builder.setResponseBody(response.getContentAsString());
} catch (final IOException exception) {
logger.error(
"There was an error while reading the contents of the resource " + "located @ " + url.toString(),
exception);
}
}
}
buffer = new StringBuilder();
buffer.append("/").append(version).append("/Accounts/");
buffer.append(accountId.toString()).append("/Notifications/");
buffer.append(sid.toString());
final URI uri = URI.create(buffer.toString());
builder.setUri(uri);
return builder.build();
}
@SuppressWarnings("unchecked")
@Override
public void onReceive(final Object message) throws Exception {
final Class<?> klass = message.getClass();
final State state = fsm.state();
sender = sender();
ActorRef self = self();
if (logger.isInfoEnabled()) {
logger.info(" ********** VoiceInterpreter's " + self().path() + " Current State: " + state.toString() + "\n"
+ ", Processing Message: " + klass.getName());
}
if (StartInterpreter.class.equals(klass)) {
final StartInterpreter request = (StartInterpreter) message;
call = request.resource();
fsm.transition(message, acquiringAsrInfo);
} else if (AsrResponse.class.equals(klass)) {
onAsrResponse(message);
} else if (SpeechSynthesizerResponse.class.equals(klass)) {
onSpeechSynthesizerResponse(message);
} else if (CallResponse.class.equals(klass)) {
onCallResponse(message, state);
} else if (CallStateChanged.class.equals(klass)) {
onCallStateChanged(message, sender);
} else if (CallManagerResponse.class.equals(klass)) {
onCallManagerResponse(message);
} else if (StartForking.class.equals(klass)) {
fsm.transition(message, processingDialChildren);
} else if (ConferenceCenterResponse.class.equals(klass)) {
onConferenceCenterResponse(message);
} else if (Fork.class.equals(klass)) {
onForkMessage(message);
} else if (ConferenceResponse.class.equals(klass)) {
onConferenceResponse(message);
} else if (ConferenceStateChanged.class.equals(klass)) {
onConferenceStateChanged(message);
} else if (DownloaderResponse.class.equals(klass)) {
onDownloaderResponse(message, state);
} else if (DiskCacheResponse.class.equals(klass)) {
onDiskCacheResponse(message);
} else if (ParserFailed.class.equals(klass)) {
onParserFailed(message);
} else if (Tag.class.equals(klass)) {
onTagMessage(message);
} else if (End.class.equals(klass)) {
onEndMessage(message);
} else if (StartGathering.class.equals(klass)) {
fsm.transition(message, gathering);
} else if (MediaGroupResponse.class.equals(klass)) {
onMediaGroupResponse(message);
} else if (SmsServiceResponse.class.equals(klass)) {
onSmsServiceResponse(message);
} else if (SmsSessionResponse.class.equals(klass)) {
smsResponse(message);
} else if (FaxResponse.class.equals(klass)) {
fsm.transition(message, ready);
} else if (EmailResponse.class.equals(klass)) {
onEmailResponse(message);
} else if (StopInterpreter.class.equals(klass)) {
onStopInterpreter(message);
} else if (message instanceof ReceiveTimeout) {
onReceiveTimeout(message);
} else if (BridgeManagerResponse.class.equals(klass)) {
onBridgeManagerResponse((BridgeManagerResponse) message, self, sender);
} else if (BridgeStateChanged.class.equals(klass)) {
onBridgeStateChanged((BridgeStateChanged) message, self, sender);
} else if (GetRelatedCall.class.equals(klass)) {
onGetRelatedCall((GetRelatedCall) message, self, sender);
} else if (JoinComplete.class.equals(klass)) {
onJoinComplete((JoinComplete)message);
} else if (CallHoldStateChange.class.equals(klass)) {
onCallHoldStateChange((CallHoldStateChange)message, sender);
}
}
private void onJoinComplete(JoinComplete message) throws TransitionNotFoundException, TransitionFailedException, TransitionRollbackException {
if (logger.isInfoEnabled()) {
logger.info("JoinComplete received, sender: " + sender().path() + ", VI state: " + fsm.state());
}
if (is(joiningConference)) {
fsm.transition(message, conferencing);
}
}
private void onAsrResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
if (outstandingAsrRequests > 0) {
asrResponse(message);
} else {
fsm.transition(message, acquiringSynthesizerInfo);
}
}
private void onForkMessage(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
if (is(processingDialChildren)) {
fsm.transition(message, forking);
}
}
private void onConferenceCenterResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
if (is(startDialing)) {
ConferenceCenterResponse ccReponse = (ConferenceCenterResponse)message;
if(ccReponse.succeeded()){
fsm.transition(message, acquiringConferenceInfo);
}else{
fsm.transition(message, hangingUp);
}
}
}
private void onConferenceResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
final ConferenceResponse<ConferenceInfo> response = (ConferenceResponse<ConferenceInfo>) message;
final Class<?> klass = ((ConferenceResponse)message).get().getClass();
if (logger.isDebugEnabled()) {
logger.debug("New ConferenceResponse received with message: "+klass.getName());
}
if (Left.class.equals(klass)) {
Left left = (Left) ((ConferenceResponse)message).get();
ActorRef leftCall = left.get();
if (leftCall.equals(call) && conference != null) {
if(conferenceInfo.globalParticipants() !=0 ){
String path = configuration.subset("runtime-settings").getString("prompts-uri");
if (!path.endsWith("/")) {
path += "/";
}
String exitAudio = configuration.subset("runtime-settings").getString("conference-exit-audio");
path += exitAudio == null || exitAudio.equals("") ? "alert.wav" : exitAudio;
URI uri = null;
try {
uri = UriUtils.resolve(new URI(path));
} catch (final Exception exception) {
final Notification notification = notification(ERROR_NOTIFICATION, 12400, exception.getMessage());
final NotificationsDao notifications = storage.getNotificationsDao();
notifications.addNotification(notification);
sendMail(notification);
final StopInterpreter stop = new StopInterpreter();
self().tell(stop, self());
return;
}
if (logger.isInfoEnabled()) {
logger.info("going to play conference-exit-audio beep");
}
final Play play = new Play(uri, 1);
conference.tell(play, self());
}
if (endConferenceOnExit) {
// Stop the conference if endConferenceOnExit is true
final StopConference stop = new StopConference();
conference.tell(stop, self());
}
Attribute attribute = null;
if (verb != null) {
attribute = verb.attribute("action");
}
if (attribute == null) {
if (logger.isInfoEnabled()) {
logger.info("Attribute is null, will ask for the next verb from parser");
}
final GetNextVerb next = new GetNextVerb();
parser.tell(next, self());
} else {
if (logger.isInfoEnabled()) {
logger.info("Dial Action is set, executing Dial Action");
}
executeDialAction(message, sender);
}
conference.tell(new StopObserving(self()), null);
}
} else if (ConferenceInfo.class.equals(klass)) {
conferenceInfo = response.get();
if (logger.isInfoEnabled()) {
logger.info("VoiceInterpreter received ConferenceResponse from Conference: " + conferenceInfo.name() + ", path: " + sender().path() + ", current confernce size: " + conferenceInfo.globalParticipants() + ", VI state: " + fsm.state());
}
if (is(acquiringConferenceInfo)) {
fsm.transition(message, joiningConference);
}
}
}
private void onConferenceStateChanged(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
final ConferenceStateChanged event = (ConferenceStateChanged) message;
if(logger.isInfoEnabled()) {
logger.info("onConferenceStateChanged: "+event.state());
}
switch (event.state()) {
case RUNNING_MODERATOR_PRESENT:
conferenceState = event.state();
conferenceStateModeratorPresent(message);
break;
case COMPLETED:
conferenceState = event.state();
//Move to finishConferencing only if we are not in Finished state already
//There are cases were we have already finished conferencing, for example when there is
//conference timeout
if (!is(finished))
fsm.transition(message, finishConferencing);
break;
default:
break;
}
// !!IMPORTANT!!
// Do not listen to COMPLETED nor FAILED conference state changes
// When a conference stops it will ask all its calls to Leave
// Then the call state will change and the voice interpreter will take proper action then
}
private void onParserFailed(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
if(logger.isInfoEnabled()) {
logger.info("ParserFailed received. Will stop the call");
}
isParserFailed = true;
fsm.transition(message, hangingUp);
}
private void onStopInterpreter(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
this.liveCallModification = ((StopInterpreter) message).isLiveCallModification();
if (CallStateChanged.State.IN_PROGRESS.equals(callState) && !liveCallModification) {
fsm.transition(message, hangingUp);
} else {
fsm.transition(message, finished);
}
}
private void onReceiveTimeout(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
if (logger.isInfoEnabled()) {
logger.info("Timeout received");
}
if (is(pausing)) {
fsm.transition(message, ready);
} else if (is(conferencing)) {
fsm.transition(message, finishConferencing);
} else if (is(forking)) {
fsm.transition(message, finishDialing);
} else if (is(bridged)) {
fsm.transition(message, finishDialing);
} else if (is(bridging)) {
fsm.transition(message, finishDialing);
} else if (is(playing)) {
fsm.transition(message, finished);
}
}
private void onEmailResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
final EmailResponse response = (EmailResponse) message;
if (!response.succeeded()) {
logger.error(
"There was an error while sending an email :" + response.error(),
response.cause());
return;
}
fsm.transition(message, ready);
}
private void onSmsServiceResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
final SmsServiceResponse<ActorRef> response = (SmsServiceResponse<ActorRef>) message;
if (response.succeeded()) {
if (is(creatingSmsSession)) {
fsm.transition(message, sendingSms);
}
} else {
fsm.transition(message, hangingUp);
}
}
private void onMediaGroupResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
final MediaGroupResponse<String> response = (MediaGroupResponse<String>) message;
if(logger.isInfoEnabled()) {
logger.info("MediaGroupResponse, succeeded: " + response.succeeded() + " " + response.cause());
}
if (response.succeeded()) {
if (is(playingRejectionPrompt)) {
fsm.transition(message, hangingUp);
} else if (is(playing)) {
fsm.transition(message, ready);
} else if (is(creatingRecording)) {
fsm.transition(message, finishRecording);
}
// This is either MMS collected digits or SIP INFO DTMF. If the DTMF is from SIP INFO, then more DTMF might
// come later
else if (is(gathering) || (is(finishGathering) && !super.dtmfReceived)) {
final MediaGroupResponse<String> dtmfResponse = (MediaGroupResponse<String>) message;
if (sender == call) {
// DTMF using SIP INFO, check if all digits collected here
collectedDigits.append(dtmfResponse.get());
// Collected digits == requested num of digits the complete the collect digits
if (numberOfDigits != Short.MAX_VALUE) {
if (collectedDigits.length() == numberOfDigits) {
dtmfReceived = true;
fsm.transition(message, finishGathering);
} else {
dtmfReceived = false;
return;
}
} else {
// If collected digits have finish on key at the end then complete the collect digits
if (collectedDigits.toString().endsWith(finishOnKey)) {
dtmfReceived = true;
fsm.transition(message, finishGathering);
} else {
dtmfReceived = false;
return;
}
}
} else {
collectedDigits.append(dtmfResponse.get());
fsm.transition(message, finishGathering);
}
} else if (is(bridging)) {
// Finally proceed with call bridging
final JoinCalls bridgeCalls = new JoinCalls(call, outboundCall);
bridge.tell(bridgeCalls, self());
} else if (is(forking)){
if(dialBranches == null || dialBranches.size() == 0){
final GetNextVerb next = new GetNextVerb();
parser.tell(next, self());
}
}
} else {
fsm.transition(message, hangingUp);
}
}
private void onEndMessage(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
//Because of RMS issue https://github.com/RestComm/mediaserver/issues/158 we cannot have List<URI> for waitUrl
if (playWaitUrlPending && conferenceWaitUris != null && conferenceWaitUris.size() > 0) {
fsm.transition(conferenceWaitUris, conferencing);
return;
}
if (callState.equals(CallStateChanged.State.COMPLETED) || callState.equals(CallStateChanged.State.CANCELED)) {
fsm.transition(message, finished);
} else {
if (!isParserFailed) {
if(logger.isInfoEnabled()) {
logger.info("End tag received will move to hangup the call, VI state: "+fsm.state());
}
fsm.transition(message, hangingUp);
} else {
if(logger.isInfoEnabled()) {
logger.info("End tag received but parser failed earlier so hangup would have been already sent to the call");
}
}
}
}
private void onTagMessage(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
verb = (Tag) message;
if (logger.isDebugEnabled()) {
logger.debug("Tag received, name: "+verb.name()+", text: "+verb.text());
}
if (playWaitUrlPending) {
if (!(Verbs.play.equals(verb.name()) || Verbs.say.equals(verb.name()))) {
if (logger.isInfoEnabled()) {
logger.info("Tag for waitUrl is neither Play or Say");
}
fsm.transition(message, hangingUp);
}
if (Verbs.say.equals(verb.name())) {
fsm.transition(message, checkingCache);
} else if (Verbs.play.equals(verb.name())) {
fsm.transition(message, caching);
}
return;
}
if (CallStateChanged.State.RINGING == callState) {
if (Verbs.reject.equals(verb.name())) {
fsm.transition(message, rejecting);
} else if (Verbs.pause.equals(verb.name())) {
fsm.transition(message, pausing);
} else {
fsm.transition(message, initializingCall);
}
} else if (Verbs.dial.equals(verb.name())) {
Attribute action = verb.attribute("action");
if (action != null && dialActionExecuted) {
//We have a new Dial verb that contains Dial Action URL again.
//We set dialActionExecuted to false in order to execute Dial Action again
dialActionExecuted = false;
}
dialRecordAttribute = verb.attribute("record");
fsm.transition(message, startDialing);
} else if (Verbs.fax.equals(verb.name())) {
fsm.transition(message, caching);
} else if (Verbs.play.equals(verb.name())) {
fsm.transition(message, caching);
} else if (Verbs.say.equals(verb.name())) {
// fsm.transition(message, synthesizing);
fsm.transition(message, checkingCache);
} else if (Verbs.gather.equals(verb.name())) {
gatherVerb = verb;
fsm.transition(message, processingGatherChildren);
} else if (Verbs.pause.equals(verb.name())) {
fsm.transition(message, pausing);
} else if (Verbs.hangup.equals(verb.name())) {
if (is(finishDialing)) {
fsm.transition(message, finished);
} else {
fsm.transition(message, hangingUp);
}
} else if (Verbs.redirect.equals(verb.name())) {
fsm.transition(message, redirecting);
} else if (Verbs.record.equals(verb.name())) {
fsm.transition(message, creatingRecording);
} else if (Verbs.sms.equals(verb.name())) {
fsm.transition(message, creatingSmsSession);
} else if (Verbs.email.equals(verb.name())) {
fsm.transition(message, sendingEmail);
} else {
invalidVerb(verb);
}
}
private void onDiskCacheResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
final DiskCacheResponse response = (DiskCacheResponse) message;
if (response.succeeded()) {
//Because of RMS issue https://github.com/RestComm/mediaserver/issues/158 we cannot have List<URI> for waitUrl
if (playWaitUrlPending) {
if (conferenceWaitUris == null)
conferenceWaitUris = new ArrayList<URI>();
URI waitUrl = response.get();
conferenceWaitUris.add(waitUrl);
final GetNextVerb next = new GetNextVerb();
parser.tell(next, self());
return;
}
if (is(caching) || is(checkingCache)) {
if (Verbs.play.equals(verb.name()) || Verbs.say.equals(verb.name())) {
fsm.transition(message, playing);
} else if (Verbs.fax.equals(verb.name())) {
fsm.transition(message, faxing);
} else if (Verbs.email.equals(verb.name())) {
fsm.transition(message, sendingEmail);
}
} else if (is(processingGatherChildren)) {
fsm.transition(message, processingGatherChildren);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("DiskCacheResponse is " + response.toString());
}
if (is(checkingCache) || is(processingGatherChildren)) {
fsm.transition(message, synthesizing);
} else {
if(response.cause() != null){
Notification notification = notification(WARNING_NOTIFICATION, 13233, response.cause().getMessage());
final NotificationsDao notifications = storage.getNotificationsDao();
notifications.addNotification(notification);
sendMail(notification);
}
fsm.transition(message, hangingUp);
}
}
}
private void onCallManagerResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
final CallManagerResponse<Object> response = (CallManagerResponse<Object>) message;
if (response.succeeded()) {
if (is(startDialing)) {
fsm.transition(message, processingDialChildren);
} else if (is(processingDialChildren)) {
fsm.transition(message, processingDialChildren);
}
} else {
if (logger.isDebugEnabled()) {
String msg = String.format("CallManager failed to create Call for %s, current state %s, dialChilder.size %s, dialBranches.size %s", response.getCreateCall().to(), fsm.state().toString(), dialChildren.size(), dialBranches.size());
logger.debug(msg);
}
if (dialChildren != null && dialChildren.size() > 0) {
fsm.transition(message, processingDialChildren);
} else {
fsm.transition(message, hangingUp);
}
}
}
private void onSpeechSynthesizerResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException {
if (is(acquiringSynthesizerInfo)) {
fsm.transition(message, acquiringCallInfo);
} else if (is(processingGatherChildren) || processingGather) {
final SpeechSynthesizerResponse<URI> response = (SpeechSynthesizerResponse<URI>) message;
if (response.succeeded()) {
fsm.transition(message, processingGatherChildren);
} else {
fsm.transition(message, hangingUp);
}
} else if (is(synthesizing)) {
final SpeechSynthesizerResponse<URI> response = (SpeechSynthesizerResponse<URI>) message;
if (response.succeeded()) {
fsm.transition(message, caching);
} else {
fsm.transition(message, hangingUp);
}
}
}