forked from OpenTelecom/kazoo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecallmgr_call_control.erl
1348 lines (1250 loc) · 59.7 KB
/
ecallmgr_call_control.erl
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
%%%-----------------------------------------------------------------------------
%%% @copyright (C) 2010-2018, 2600Hz
%%% @doc Created when a call hits a fetch_handler in ecallmgr_route.
%%% A Control Queue is created by the lookup_route function in the
%%% fetch_handler. On initialization, besides adding itself as the
%%% consumer for the AMQP messages, Call Control creates an empty queue
%%% object (not to be confused with AMQP queues), sets the current
%%% application running on the switch to the empty binary, and records
%%% the timestamp of when the initialization finishes. The process then
%%% enters its loop to wait.
%%%
%%% When receiving an AMQP message, after decoding the JSON into a proplist,
%%% we check if the application is "queue" or not; if it is "queue", we
%%% extract the default headers out, iterate through the Commands portion,
%%% and append the default headers to the application-specific portions, and
%%% insert these commands into the CmdQ. We then check whether the old CmdQ is
%%% empty AND the new CmdQ is not, and that the current App is the empty
%%% binary. If so, we dequeue the next command, execute it, and loop; otherwise
%%% we loop with the CmdQ.
%%% If just a single application is sent in the message, we check the CmdQ's
%%% size and the current App's status; if both are empty, we fire the command
%%% immediately; otherwise we add the command to the CmdQ and loop.
%%%
%%% When receiving an {execute_complete, CALLID, EvtName} tuple from
%%% the corresponding ecallmgr_call_events process tracking the call,
%%% we convert the CurrApp name from Kazoo parlance to FS, matching
%%% it against what application name we got from FS via the events
%%% process. If CurrApp is empty, we just loop since the completed
%%% execution probably wasn't related to our stuff (perhaps FS internal);
%%% if the converted Kazoo name matches the passed FS name, we know
%%% the CurrApp cmd has finished and can execute the next command in the
%%% queue. If there are no commands in the queue, set CurrApp to 'undefined' and
%%% loop; otherwise take the next command, execute it, and look with it as
%%% the CurrApp. If EvtName and the converted Kazoo name don't match,
%%% something else executed that might have been related to the main
%%% application's execute (think set commands, like playback terminators);
%%% we can note the event happened, and continue looping as we were.
%%%
%%%
%%% @author James Aimonetti <[email protected]>
%%% @author Karl Anderson <[email protected]>
%%% @end
%%%-----------------------------------------------------------------------------
-module(ecallmgr_call_control).
-behaviour(gen_listener).
%% API
-export([start_link/5, stop/1]).
-export([queue_name/1]).
-export([callid/1]).
-export([node/1]).
-export([hostname/1]).
-export([event_execute_complete/3]).
-export([other_legs/1
,update_node/2
,control_procs/1
]).
-export([fs_nodeup/2]).
-export([fs_nodedown/2]).
%% gen_listener callbacks
-export([init/1
,handle_call/3
,handle_cast/2
,handle_info/2
,handle_event/2
,terminate/2
,code_change/3
]).
-include("ecallmgr.hrl").
-define(SERVER, ?MODULE).
-define(KEEP_ALIVE, 2 * ?MILLISECONDS_IN_SECOND).
-type insert_at_options() :: 'now' | 'head' | 'tail' | 'flush'.
-record(state, {node :: atom()
,call_id :: kz_term:ne_binary()
,command_q = queue:new() :: queue:queue()
,current_app :: kz_term:api_binary()
,current_cmd :: kz_term:api_object()
,start_time = os:timestamp() :: kz_time:now()
,is_call_up = 'true' :: boolean()
,is_node_up = 'true' :: boolean()
,keep_alive_ref :: kz_term:api_reference()
,other_legs = [] :: kz_term:ne_binaries()
,last_removed_leg :: kz_term:api_binary()
,sanity_check_tref :: kz_term:api_reference()
,msg_id :: kz_term:api_binary()
,fetch_id :: kz_term:api_binary()
,controller_q :: kz_term:api_ne_binary()
,control_q :: kz_term:api_ne_binary()
,initial_ccvs :: kz_json:object()
,node_down_tref :: kz_term:api_reference()
}).
-type state() :: #state{}.
-define(RESPONDERS, []).
-define(QUEUE_NAME, <<>>).
-define(QUEUE_OPTIONS, []).
-define(CONSUME_OPTIONS, []).
%%%=============================================================================
%%% API
%%%=============================================================================
%%------------------------------------------------------------------------------
%% @doc Starts the server.
%% @end
%%------------------------------------------------------------------------------
-spec start_link(atom(), kz_term:ne_binary(), kz_term:api_ne_binary(), kz_term:api_ne_binary(), kz_json:object()) ->
kz_types:startlink_ret().
start_link(Node, CallId, FetchId, ControllerQ, CCVs) ->
%% We need to become completely decoupled from ecallmgr_call_events
%% because the call_events process might have been spun up with A->B
%% then transferred to A->D, but the route landed in a different
%% ecallmgr. Since our call_events will get a bad session if we
%% try to handlecall more than once on a UUID we had to leave the
%% call_events running on another ecallmgr... fun fun
Bindings = [{'call', [{'callid', CallId}
,{'restrict_to', [<<"usurp_control">>]}
]}
,{'dialplan', []}
,{'self', []}
],
gen_listener:start_link(?SERVER, [{'responders', ?RESPONDERS}
,{'bindings', Bindings}
,{'queue_name', ?QUEUE_NAME}
,{'queue_options', ?QUEUE_OPTIONS}
,{'consume_options', ?CONSUME_OPTIONS}
]
,[Node, CallId, FetchId, ControllerQ, CCVs]
).
-spec stop(pid()) -> 'ok'.
stop(Srv) ->
gen_listener:cast(Srv, 'stop').
-spec callid(pid()) -> kz_term:ne_binary().
callid(Srv) ->
gen_listener:call(Srv, 'callid', ?MILLISECONDS_IN_SECOND).
-spec node(pid()) -> kz_term:ne_binary().
node(Srv) ->
gen_listener:call(Srv, 'node', ?MILLISECONDS_IN_SECOND).
-spec hostname(pid()) -> binary().
hostname(Srv) ->
Node = ?MODULE:node(Srv),
[_, Hostname] = binary:split(kz_term:to_binary(Node), <<"@">>),
Hostname.
-spec queue_name(kz_term:api_pid()) -> kz_term:api_ne_binary().
queue_name('undefined') -> 'undefined';
queue_name(Srv) when is_pid(Srv) -> gen_listener:queue_name(Srv).
-spec other_legs(pid()) -> kz_term:ne_binaries().
other_legs(Srv) ->
gen_listener:call(Srv, 'other_legs', ?MILLISECONDS_IN_SECOND).
-spec event_execute_complete(kz_term:api_pid(), kz_term:ne_binary(), kz_term:ne_binary()) -> 'ok'.
event_execute_complete('undefined', _CallId, _App) -> 'ok';
event_execute_complete(Srv, CallId, App) ->
gen_listener:cast(Srv, {'event_execute_complete', CallId, App, kz_json:new()}).
-spec update_node(atom(), kz_term:ne_binary() | kz_term:pids()) -> 'ok'.
update_node(Node, CallId) when is_binary(CallId) ->
update_node(Node, gproc:lookup_pids({'p', 'l', {'call_control', CallId}}));
update_node(Node, Pids) when is_list(Pids) ->
_ = [gen_listener:cast(Srv, {'update_node', Node}) || Srv <- Pids],
'ok'.
-spec control_procs(kz_term:ne_binary()) -> kz_term:pids().
control_procs(CallId) ->
gproc:lookup_pids({'p', 'l', {'call_control', CallId}}).
-spec fs_nodeup(pid(), atom()) -> 'ok'.
fs_nodeup(Srv, Node) ->
gen_server:cast(Srv, {'fs_nodeup', Node}).
-spec fs_nodedown(pid(), atom()) -> 'ok'.
fs_nodedown(Srv, Node) ->
gen_server:cast(Srv, {'fs_nodedown', Node}).
%%%=============================================================================
%%% gen_listener callbacks
%%%=============================================================================
%%------------------------------------------------------------------------------
%% @doc Initializes the server.
%% @end
%%------------------------------------------------------------------------------
-spec init([atom() | kz_term:ne_binary() | kz_json:object()]) -> {'ok', state()}.
init([Node, CallId, FetchId, ControllerQ, CCVs]) ->
kz_util:put_callid(CallId),
lager:debug("starting call control listener"),
gen_listener:cast(self(), 'init'),
_ = bind_to_events(Node, CallId),
_ = reg_for_call_related_events(CallId),
{'ok', #state{node=Node
,call_id=CallId
,command_q=queue:new()
,start_time=os:timestamp()
,fetch_id=FetchId
,controller_q=ControllerQ
,initial_ccvs=CCVs
}}.
%%------------------------------------------------------------------------------
%% @doc Handling call messages.
%% @end
%%------------------------------------------------------------------------------
-spec handle_call(any(), kz_term:pid_ref(), state()) -> kz_types:handle_call_ret_state(state()).
handle_call('node', _From, #state{node=Node}=State) ->
{'reply', Node, State};
handle_call('callid', _From, #state{call_id=CallId}=State) ->
{'reply', CallId, State};
handle_call('other_legs', _From, #state{other_legs=Legs}=State) ->
{'reply', Legs, State};
handle_call(_Request, _From, State) ->
{'reply', {'error', 'not_implemented'}, State}.
%%------------------------------------------------------------------------------
%% @doc Handling cast messages.
%% @end
%%------------------------------------------------------------------------------
-spec handle_cast(any(), state()) -> kz_types:handle_cast_ret_state(state()).
handle_cast('init', State) ->
TRef = erlang:send_after(?SANITY_CHECK_PERIOD, self(), 'sanity_check'),
{'noreply', State#state{sanity_check_tref=TRef}};
handle_cast('stop', State) ->
{'stop', 'normal', State};
handle_cast({'usurp_control', _}, State) ->
lager:debug("the call has been usurped by an external process"),
{'stop', 'normal', State};
handle_cast({'update_node', Node}, #state{node=OldNode}=State) ->
lager:debug("channel has moved from ~s to ~s", [OldNode, Node]),
{'noreply', State#state{node=Node}};
handle_cast({'dialplan', JObj}, State) ->
{'noreply', handle_dialplan(JObj, State)};
handle_cast({'event_execute_complete', CallId, AppName, JObj}
,#state{call_id=CallId}=State
) ->
{'noreply', handle_execute_complete(AppName, JObj, State)};
handle_cast({'event_execute_complete', _, _, _}, State) ->
{'noreply', State};
handle_cast({'gen_listener', {'created_queue', Q}}, State) ->
{'noreply', State#state{control_q=Q}};
handle_cast({'gen_listener', {'is_consuming', _IsConsuming}}
,#state{controller_q='undefined'}=State
) ->
lager:debug("call control got is_consuming but controller is undefined"),
{'noreply', State};
handle_cast({'gen_listener', {'is_consuming', _IsConsuming}}, State) ->
call_control_ready(State),
{'noreply', State};
handle_cast({'fs_nodedown', Node}, #state{node=Node
,is_node_up='true'
}=State) ->
lager:debug("lost connection to media node ~s", [Node]),
TRef = erlang:send_after(?MAX_TIMEOUT_FOR_NODE_RESTART, self(), 'nodedown_restart_exceeded'),
{'noreply', State#state{is_node_up='false'
,node_down_tref=TRef
}};
handle_cast({'fs_nodeup', Node}, #state{node=Node
,call_id=CallId
,is_node_up='false'
,node_down_tref=TRef
}=State) ->
lager:debug("regained connection to media node ~s", [Node]),
_ = (catch erlang:cancel_timer(TRef)),
_ = timer:sleep(100 + rand:uniform(1400)),
case freeswitch:api(Node, 'uuid_exists', CallId) of
{'ok', <<"true">>} ->
{'noreply', force_queue_advance(State#state{is_node_up='true'})};
_Else ->
{'noreply', handle_channel_destroyed(kz_json:new(), State)}
end;
handle_cast(_, State) ->
{'noreply', State}.
%%------------------------------------------------------------------------------
%% @doc Handling all non call/cast messages.
%% @end
%%------------------------------------------------------------------------------
-spec handle_info(any(), state()) -> kz_types:handle_info_ret_state(state()).
handle_info({'event', [CallId | Props]}, #state{call_id=CallId}=State) ->
handle_event_info(CallId, Props, State);
handle_info({'event', [CallId | Props]}, State) ->
handle_other_event_info(CallId, Props, State);
handle_info({'force_queue_advance', CallId}, #state{call_id=CallId}=State) ->
{'noreply', force_queue_advance(State)};
handle_info({'force_queue_advance', _}, State) ->
{'noreply', State};
handle_info('keep_alive_expired', State) ->
lager:debug("no new commands received after channel destruction, our job here is done"),
{'stop', 'normal', State};
handle_info('sanity_check', #state{call_id=CallId}=State) ->
case ecallmgr_fs_channel:exists(CallId) of
'true' ->
lager:debug("listener passed sanity check, call is still up"),
TRef = erlang:send_after(?SANITY_CHECK_PERIOD, self(), 'sanity_check'),
{'noreply', State#state{sanity_check_tref=TRef}};
'false' ->
lager:debug("call uuid does not exist, executing post-hangup events and terminating"),
{'noreply', handle_channel_destroyed(kz_json:new(), State)}
end;
handle_info(?CHANNEL_MOVE_COMPLETE_MSG(Node, UUID, _Evt), State) ->
lager:debug("channel move complete recv for node ~s:~s", [Node, UUID]),
{'noreply', State};
handle_info('nodedown_restart_exceeded', #state{is_node_up='false'}=State) ->
lager:debug("we have not received a node up in time, assuming down for good for this call", []),
{'noreply', handle_channel_destroyed(kz_json:new(), State)};
handle_info(?LOOPBACK_BOWOUT_MSG(Node, Props), #state{call_id=ResigningUUID
,node=Node
}=State) ->
case {props:get_value(?RESIGNING_UUID, Props)
,props:get_value(?ACQUIRED_UUID, Props)
}
of
{ResigningUUID, ResigningUUID} ->
lager:debug("call id after bowout remains the same"),
{'noreply', State};
{ResigningUUID, AcquiringUUID} ->
lager:debug("replacing ~s with ~s", [ResigningUUID, AcquiringUUID]),
{'noreply', handle_sofia_replaced(AcquiringUUID, State)};
{_UUID, _AcuiringUUID} ->
lager:debug("ignoring bowout for ~s", [_UUID]),
{'noreply', State}
end;
handle_info(_Msg, State) ->
lager:debug("unhandled message: ~p", [_Msg]),
{'noreply', State}.
%%------------------------------------------------------------------------------
%% @doc Allows listener to pass options to handlers.
%% @end
%%------------------------------------------------------------------------------
-spec handle_event(kz_json:object(), state()) -> gen_listener:handle_event_return().
handle_event(JObj, #state{fetch_id=FetchId}) ->
_ = case kz_util:get_event_type(JObj) of
{<<"call">>, <<"command">>} -> handle_call_command(JObj);
{<<"conference">>, <<"command">>} -> handle_conference_command(JObj);
{<<"call_event">>, _} -> handle_call_events(JObj, FetchId)
end,
'ignore'.
-spec handle_call_command(kz_json:object()) -> 'ok'.
handle_call_command(JObj) ->
gen_listener:cast(self(), {'dialplan', JObj}).
-spec handle_conference_command(kz_json:object()) -> 'ok'.
handle_conference_command(JObj) ->
gen_listener:cast(self(), {'dialplan', JObj}).
-spec handle_call_events(kz_json:object(), kz_term:ne_binary()) -> 'ok'.
handle_call_events(JObj, FetchId) ->
kz_util:put_callid(kz_json:get_value(<<"Call-ID">>, JObj)),
case kz_json:get_value(<<"Event-Name">>, JObj) of
<<"usurp_control">> ->
case kz_json:get_value(<<"Fetch-ID">>, JObj) =:= FetchId of
'false' -> gen_listener:cast(self(), {'usurp_control', JObj});
'true' -> 'ok'
end;
_Else -> 'ok'
end.
%%------------------------------------------------------------------------------
%% @doc This function is called by a `gen_listener' when it is about to
%% terminate. It should be the opposite of `Module:init/1' and do any
%% necessary cleaning up. When it returns, the `gen_listener' terminates
%% with Reason. The return value is ignored.
%%
%% @end
%%------------------------------------------------------------------------------
-spec terminate(any(), state()) -> 'ok'.
terminate(_Reason, #state{start_time=StartTime
,sanity_check_tref=SCTRef
,keep_alive_ref=KATRef
}) ->
catch (erlang:cancel_timer(SCTRef)),
catch (erlang:cancel_timer(KATRef)),
lager:debug("control queue was up for ~p microseconds", [timer:now_diff(os:timestamp(), StartTime)]),
'ok'.
%%------------------------------------------------------------------------------
%% @doc Convert process state when code is changed.
%% @end
%%------------------------------------------------------------------------------
-spec code_change(any(), state(), any()) -> {'ok', state()}.
code_change(_OldVsn, State, _Extra) ->
{'ok', State}.
%%%=============================================================================
%%% Internal functions
%%%=============================================================================
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec call_control_ready(state()) -> 'ok'.
call_control_ready(#state{call_id=CallId
,controller_q=ControllerQ
,control_q=Q
,initial_ccvs=CCVs
,fetch_id=FetchId
,node=Node
}) ->
Win = [{<<"Msg-ID">>, CallId}
,{<<"Call-ID">>, CallId}
,{<<"Control-Queue">>, Q}
,{<<"Custom-Channel-Vars">>, CCVs}
| kz_api:default_headers(Q, <<"dialplan">>, <<"route_win">>, ?APP_NAME, ?APP_VERSION)
],
lager:debug("sending route_win to ~s", [ControllerQ]),
kapi_route:publish_win(ControllerQ, Win),
Usurp = [{<<"Call-ID">>, CallId}
,{<<"Fetch-ID">>, FetchId}
,{<<"Reason">>, <<"Route-Win">>}
,{<<"Media-Node">>, kz_term:to_binary(Node)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
],
lager:debug("sending control usurp for ~s", [FetchId]),
kapi_call:publish_usurp_control(CallId, Usurp).
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec handle_channel_destroyed(kz_json:object(), state()) -> state().
handle_channel_destroyed(JObj, State) ->
case kz_json:is_true(<<"Channel-Is-Loopback">>, JObj, 'false') of
'false' -> handle_channel_destroyed(State);
'true' -> handle_loopback_destroyed(JObj, State)
end.
-spec handle_loopback_destroyed(kz_json:object(), state()) -> state().
handle_loopback_destroyed(JObj, State) ->
case {kz_call_event:hangup_cause(JObj)
,kz_json:is_true(<<"Channel-Loopback-Bowout-Execute">>, JObj)
}
of
{<<"NORMAL_UNSPECIFIED">>, 'true'} ->
lager:debug("our loopback has ended but we may not have recv the bowout"),
State;
{_Cause, _Bowout} ->
lager:debug("our loopback has ended with ~s(bowout ~s); treating as done"),
handle_channel_destroyed(State)
end.
-spec handle_channel_destroyed(state()) -> state().
handle_channel_destroyed(#state{sanity_check_tref=SCTRef
,current_app=CurrentApp
,current_cmd=CurrentCmd
,call_id=CallId
}=State
) ->
lager:debug("our channel has been destroyed, executing any post-hangup commands"),
%% if our sanity check timer is running stop it, it will always return false
%% now that the channel is gone
catch (erlang:cancel_timer(SCTRef)),
%% if the current application can not be run without a channel and we have received the
%% channel_destory (the last event we will ever receive from freeswitch for this call)
%% then create an error and force advance. This will happen with dialplan actions that
%% have not been executed on freeswitch but were already queued (for example in xferext).
%% Commonly events like masquerade, noop, etc
_ = case CurrentApp =:= 'undefined'
orelse is_post_hangup_command(CurrentApp)
of
'true' -> 'ok';
'false' ->
maybe_send_error_resp(CallId, CurrentCmd),
self() ! {'force_queue_advance', CallId}
end,
State#state{keep_alive_ref=get_keep_alive_ref(State#state{is_call_up='false'})
,is_call_up='false'
,is_node_up='true'
}.
-spec force_queue_advance(state()) -> state().
force_queue_advance(#state{call_id=CallId
,current_app=CurrApp
,command_q=CmdQ
,is_node_up=INU
,is_call_up=CallUp
}=State) ->
lager:debug("received control queue unconditional advance, skipping wait for command completion of '~s'"
,[CurrApp]
),
case INU
andalso queue:out(CmdQ)
of
'false' ->
%% if the node is down, don't inject the next FS event
lager:debug("not continuing until the media node becomes avaliable"),
State#state{current_app='undefined'};
{'empty', _} ->
lager:debug("no call commands remain queued, hibernating"),
State#state{current_app='undefined'};
{{'value', Cmd}, CmdQ1} ->
AppName = kapi_dialplan:application_name(Cmd),
_ = case CallUp
orelse is_post_hangup_command(AppName)
of
'true' ->
execute_control_request(Cmd, State);
'false' ->
lager:debug("command '~s' is not valid after hangup, skipping", [AppName]),
maybe_send_error_resp(CallId, Cmd),
self() ! {'force_queue_advance', CallId}
end,
MsgId = kz_api:msg_id(Cmd),
State#state{command_q=CmdQ1
,current_app=AppName
,current_cmd=Cmd
,keep_alive_ref=get_keep_alive_ref(State)
,msg_id=MsgId
}
end.
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec handle_execute_complete(kz_term:api_binary(), kz_json:object(), state()) -> state().
handle_execute_complete('undefined', _, State) -> State;
handle_execute_complete(<<"noop">>, JObj, #state{msg_id=CurrMsgId}=State) ->
case kz_json:get_ne_binary_value(<<"Application-Response">>, JObj) of
CurrMsgId ->
lager:debug("noop execution complete for ~s, advancing control queue", [CurrMsgId]),
forward_queue(State);
_NoopId ->
lager:debug("received noop execute complete with incorrect id ~s (expecting ~s)"
,[_NoopId, CurrMsgId]
),
State
end;
handle_execute_complete(<<"playback">> = AppName, JObj, #state{current_app=AppName}=State) ->
handle_playback_complete(AppName, JObj, State);
handle_execute_complete(<<"play">> = AppName, JObj, #state{current_app=AppName}=State) ->
handle_playback_complete(AppName, JObj, State);
handle_execute_complete(<<"tts">> = AppName, JObj, #state{current_app=AppName}=State) ->
handle_playback_complete(AppName, JObj, State);
handle_execute_complete(AppName, _, #state{current_app=AppName}=State) ->
lager:debug("~s execute complete, advancing control queue", [AppName]),
forward_queue(State);
handle_execute_complete(AppName, JObj, #state{current_app=CurrApp}=State) ->
RawAppName = kz_json:get_value(<<"Raw-Application-Name">>, JObj, AppName),
MappedNames = ecallmgr_util:convert_kazoo_app_name(CurrApp),
case lists:member(RawAppName, MappedNames) of
'true' -> handle_execute_complete(CurrApp, JObj, State);
'false' -> State
end.
-spec handle_playback_complete(kz_term:ne_binary(), kz_json:object(), state()) -> state().
handle_playback_complete(AppName, JObj, #state{command_q=CmdQ}=State) ->
lager:debug("~s finished, checking for group-id/DTMF termination", [AppName]),
case kz_json:get_ne_binary_value(<<"DTMF-Digit">>, JObj) of
'undefined' -> handle_playback_looping(State);
_DTMF ->
GroupId = kz_json:get_ne_binary_value(<<"Group-ID">>, JObj),
lager:debug("DTMF ~s terminated playback, flushing all with group id ~s"
,[_DTMF, GroupId]
),
forward_queue(State#state{command_q=flush_group_id(CmdQ, GroupId, AppName)})
end.
-spec handle_playback_looping(state()) -> state().
handle_playback_looping(#state{current_cmd=AppCmd}=State) ->
case kz_json:is_true(<<"Endless-Playback">>, AppCmd, 'false')
orelse kz_json:get_integer_value(<<"Loop-Count">>, AppCmd, 0)
of
'true' ->
lager:debug("media is playing back endlessly, looping"),
_ = execute_control_request(AppCmd, State),
State;
Count when is_integer(Count), Count > 1 ->
lager:debug("media is looped (~p left), looping", [Count-1]),
UpdatedCmd = kz_json:set_value(<<"Loop-Count">>, Count-1, AppCmd),
execute_control_request(UpdatedCmd, State#state{current_cmd=UpdatedCmd}),
State#state{current_cmd=UpdatedCmd};
_Count ->
lager:debug("media finished playing, advancing control queue"),
forward_queue(State)
end.
-spec flush_group_id(queue:queue(), kz_term:api_binary(), kz_term:ne_binary()) -> queue:queue().
flush_group_id(CmdQ, 'undefined', _) -> CmdQ;
flush_group_id(CmdQ, GroupId, AppName) ->
lager:debug("filtering commands ~s for group-id ~s", [AppName, GroupId]),
Filter = kz_json:from_list([{<<"Application-Name">>, AppName}
,{<<"Group-ID">>, GroupId}
,{<<"Fields">>, kz_json:from_list([{<<"Group-ID">>, GroupId}])}
]),
maybe_filter_queue([Filter], CmdQ).
-spec forward_queue(state()) -> state().
forward_queue(#state{call_id = CallId
,is_node_up = INU
,is_call_up = CallUp
,command_q = CmdQ
}=State) ->
case INU
andalso queue:out(CmdQ)
of
'false' ->
%% if the node is down, don't inject the next FS event
lager:debug("not continuing until the media node becomes avaliable"),
State#state{current_app='undefined', msg_id='undefined'};
{'empty', _} ->
lager:debug("no call commands remain queued, hibernating"),
State#state{current_app='undefined', msg_id='undefined'};
{{'value', Cmd}, CmdQ1} ->
AppName = kapi_dialplan:application_name(Cmd),
_ = case CallUp
orelse is_post_hangup_command(AppName)
of
'true' -> execute_control_request(Cmd, State);
'false' ->
lager:debug("command '~s' is not valid after hangup, skipping", [AppName]),
maybe_send_error_resp(CallId, Cmd),
self() ! {'force_queue_advance', CallId}
end,
MsgId = kz_api:msg_id(Cmd),
State#state{command_q = CmdQ1
,current_app = AppName
,current_cmd = Cmd
,msg_id = MsgId
}
end.
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec handle_sofia_replaced(kz_term:ne_binary(), state()) -> state().
handle_sofia_replaced(<<_/binary>> = CallId, #state{call_id=CallId}=State) ->
lager:debug("call id hasn't changed, no replacement necessary"),
State;
handle_sofia_replaced(<<_/binary>> = ReplacedBy, #state{call_id=CallId
,node=Node
,other_legs=Legs
,command_q=CommandQ
}=State) ->
lager:info("updating callid from ~s to ~s", [CallId, ReplacedBy]),
unbind_from_events(Node, CallId),
unreg_for_call_related_events(CallId),
gen_listener:rm_binding(self(), 'call', [{'callid', CallId}]),
kz_util:put_callid(ReplacedBy),
bind_to_events(Node, ReplacedBy),
reg_for_call_related_events(ReplacedBy),
gen_listener:add_binding(self(), 'call', [{'callid', ReplacedBy}]),
lager:info("...call id updated, continuing post-transfer"),
Commands = [kz_json:set_value(<<"Call-ID">>, ReplacedBy, JObj)
|| JObj <- queue:to_list(CommandQ)
],
State#state{call_id=ReplacedBy
,other_legs=lists:delete(ReplacedBy, Legs)
,command_q=queue:from_list(Commands)
}.
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec handle_channel_create(kz_term:proplist(), state()) -> state().
handle_channel_create(Props, #state{call_id=CallId}=State) ->
LegId = props:get_value(<<"Caller-Unique-ID">>, Props),
case ecallmgr_fs_channel:get_other_leg(LegId, Props) of
'undefined' -> State;
CallId -> add_leg(Props, LegId, State);
OtherLeg -> maybe_add_cleg(Props, OtherLeg, LegId, State)
end.
-spec add_leg(kz_term:proplist(), kz_term:ne_binary(), state()) -> state().
add_leg(Props, LegId, #state{other_legs=Legs
,call_id=CallId
,node=Node
}=State) ->
case lists:member(LegId, Legs) of
'true' -> State;
'false' ->
lager:debug("added leg ~s to call", [LegId]),
ConsumerPid = kz_amqp_channel:consumer_pid(),
_ = kz_util:spawn(
fun() ->
kz_util:put_callid(CallId),
kz_amqp_channel:consumer_pid(ConsumerPid),
publish_leg_addition(props:set_value(<<"Other-Leg-Unique-ID">>, CallId, Props))
end),
_ = case ecallmgr_fs_channel:fetch(CallId) of
{'ok', Channel} ->
CDR = kz_json:get_value(<<"interaction_id">>, Channel),
ecallmgr_fs_command:set(Node, LegId, [{<<?CALL_INTERACTION_ID>>, CDR}]);
_ -> 'ok'
end,
State#state{other_legs=[LegId|Legs]}
end.
-spec publish_leg_addition(kz_term:proplist()) -> 'ok'.
publish_leg_addition(Props) ->
Event = ecallmgr_call_events:create_event(<<"LEG_CREATED">>
,'undefined'
,ecallmgr_call_events:swap_call_legs(Props)
),
ecallmgr_call_events:publish_event(Event).
-spec maybe_add_cleg(kz_term:proplist(), kz_term:api_binary(), kz_term:api_binary(), state()) -> state().
maybe_add_cleg(Props, OtherLeg, LegId, #state{other_legs=Legs}=State) ->
case lists:member(OtherLeg, Legs) of
'true' -> add_cleg(Props, OtherLeg, LegId, State);
'false' -> State
end.
-spec add_cleg(kz_term:proplist(), kz_term:api_binary(), kz_term:api_binary(), state()) -> state().
add_cleg(_Props, _OtherLeg, 'undefined', State) -> State;
add_cleg(Props, OtherLeg, LegId, #state{other_legs=Legs
,call_id=CallId
}=State) ->
case lists:member(LegId, Legs) of
'true' -> State;
'false' ->
lager:debug("added cleg ~s to call", [LegId]),
ConsumerPid = kz_amqp_channel:consumer_pid(),
_ = kz_util:spawn(
fun() ->
kz_util:put_callid(CallId),
kz_amqp_channel:consumer_pid(ConsumerPid),
publish_cleg_addition(Props, OtherLeg, CallId)
end),
State#state{other_legs=[LegId|Legs]}
end.
-spec publish_cleg_addition(kz_term:proplist(), kz_term:api_binary(), kz_term:ne_binary()) -> 'ok'.
publish_cleg_addition(Props, OtherLeg, CallId) ->
Event = ecallmgr_call_events:create_event(<<"LEG_CREATED">>
,'undefined'
,ecallmgr_call_events:swap_call_legs(Props)
),
Event1 = replace_call_id(Event, OtherLeg, CallId, []),
ecallmgr_call_events:publish_event(Event1).
-spec replace_call_id(kz_term:proplist(), kz_term:api_binary(), kz_term:ne_binary(), kz_term:proplist()) -> kz_term:proplist().
replace_call_id([], _Call1, _Call2, Swap) -> Swap;
replace_call_id([{Key, Call1}|T], Call1, Call2, Swap) ->
replace_call_id(T, Call1, Call2, [{Key, Call2}|Swap]);
replace_call_id([Prop|T], Call1, Call2, Swap) ->
replace_call_id(T, Call1, Call2, [Prop|Swap]).
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec handle_channel_destroy(kz_term:proplist(), state()) -> state().
handle_channel_destroy(Props, #state{call_id=CallId}=State) ->
LegId = props:get_value(<<"Caller-Unique-ID">>, Props),
case ecallmgr_fs_channel:get_other_leg(LegId, Props) =:= CallId of
'true' -> remove_leg(Props, State);
'false' -> State
end.
-spec remove_leg(kz_term:proplist(), state()) -> state().
remove_leg(Props, #state{other_legs=Legs
,call_id=CallId
}=State) ->
LegId = props:get_value(<<"Caller-Unique-ID">>, Props),
case lists:member(LegId, Legs) of
'false' -> State;
'true' ->
lager:debug("removed leg ~s from call", [LegId]),
ConsumerPid = kz_amqp_channel:consumer_pid(),
_ = kz_util:spawn(
fun() ->
kz_util:put_callid(CallId),
kz_amqp_channel:consumer_pid(ConsumerPid),
publish_leg_removal(Props)
end),
State#state{other_legs=lists:delete(LegId, Legs)
,last_removed_leg=LegId
}
end.
-spec publish_leg_removal(kz_term:proplist()) -> 'ok'.
publish_leg_removal(Props) ->
Event = ecallmgr_call_events:create_event(<<"LEG_DESTROYED">>
,'undefined'
,ecallmgr_call_events:swap_call_legs(Props)),
ecallmgr_call_events:publish_event(Event).
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec handle_dialplan(kz_json:object(), state()) -> state().
handle_dialplan(JObj, #state{call_id=CallId
,is_node_up=INU
,is_call_up=CallUp
,command_q=CmdQ
,current_app=CurrApp
}=State) ->
NewCmdQ = try
insert_command(State, kz_term:to_atom(kz_json:get_value(<<"Insert-At">>, JObj, 'tail')), JObj)
catch _T:_R ->
lager:debug("failed to insert command into control queue: ~p:~p", [_T, _R]),
CmdQ
end,
case INU
andalso (not queue:is_empty(NewCmdQ))
andalso CurrApp =:= 'undefined'
of
'true' ->
{{'value', Cmd}, NewCmdQ1} = queue:out(NewCmdQ),
AppName = kapi_dialplan:application_name(Cmd),
_ = case CallUp
orelse is_post_hangup_command(AppName)
of
'true' -> execute_control_request(Cmd, State);
'false' ->
lager:debug("command '~s' is not valid after hangup, ignoring", [AppName]),
maybe_send_error_resp(CallId, Cmd),
self() ! {'force_queue_advance', CallId}
end,
MsgId = kz_api:msg_id(Cmd),
State#state{command_q=NewCmdQ1
,current_app=AppName
,current_cmd=Cmd
,keep_alive_ref=get_keep_alive_ref(State)
,msg_id=MsgId
};
'false' ->
State#state{command_q=NewCmdQ
,keep_alive_ref=get_keep_alive_ref(State)
}
end.
%% execute all commands in JObj immediately, irregardless of what is running (if anything).
-spec insert_command(state(), insert_at_options(), kz_json:object()) -> queue:queue().
insert_command(#state{node=Node
,call_id=CallId
,command_q=CommandQ
,is_node_up=IsNodeUp
}=State
,'now'
,JObj
) ->
AName = kapi_dialplan:application_name(JObj),
case IsNodeUp
andalso AName
of
'false' ->
lager:debug("node ~s is not avaliable", [Node]),
lager:debug("sending execution error for command ~s", [AName]),
{Mega,Sec,Micro} = os:timestamp(),
Props = [{<<"Event-Name">>, <<"CHANNEL_EXECUTE_ERROR">>}
,{<<"Event-Date-Timestamp">>, ((Mega * 1000000 + Sec) * 1000000 + Micro)}
,{<<"Call-ID">>, CallId}
,{<<"Channel-Call-State">>, <<"ERROR">>}
,{<<"Custom-Channel-Vars">>, JObj}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
,{<<"Request">>, JObj}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
],
kapi_call:publish_event(Props),
CommandQ;
<<"queue">> ->
'true' = kapi_dialplan:queue_v(JObj),
Commands = kz_json:get_list_value(<<"Commands">>, JObj, []),
DefJObj = kz_json:from_list(kz_api:extract_defaults(JObj)),
_ = execute_queue_commands(Commands, DefJObj, State),
CommandQ;
<<"noop">> ->
execute_control_request(JObj, State),
maybe_filter_queue(kz_json:get_value(<<"Filter-Applications">>, JObj), CommandQ);
_ ->
lager:debug("recv and executing ~s now!", [AName]),
execute_control_request(JObj, State),
CommandQ
end;
insert_command(#state{node=Node, call_id=CallId}, 'flush', JObj) ->
lager:debug("received control queue flush command, clearing all waiting commands"),
_ = freeswitch:api(Node, 'uuid_break', <<CallId/binary, " all">>),
self() ! {'force_queue_advance', CallId},
insert_command_into_queue(queue:new(), 'tail', JObj);
insert_command(#state{command_q=CommandQ}, 'head', JObj) ->
insert_command_into_queue(CommandQ, 'head', JObj);
insert_command(#state{command_q=CommandQ}, 'tail', JObj) ->
insert_command_into_queue(CommandQ, 'tail', JObj);
insert_command(Q, Pos, _) ->
lager:debug("received command for an unknown queue position: ~p", [Pos]),
Q.
execute_queue_commands([], _, _) -> 'ok';
execute_queue_commands([Command|Commands], DefJObj, State) ->
case kz_json:is_empty(Command)
orelse 'undefined' =:= kapi_dialplan:application_name(Command)
of
'true' -> execute_queue_commands(Commands, DefJObj, State);
'false' ->
JObj = kz_json:merge_jobjs(Command, DefJObj),
'true' = kapi_dialplan:v(JObj),
_Ugly = insert_command(State, 'now', JObj),
execute_queue_commands(Commands, DefJObj, State)
end.
-spec insert_command_into_queue(queue:queue(), 'tail' | 'head', kz_json:object()) -> queue:queue().
insert_command_into_queue(Q, Position, JObj) ->
InsertFun = queue_insert_fun(Position),
case kapi_dialplan:application_name(JObj) of
<<"queue">> -> %% list of commands that need to be added
insert_queue_command_into_queue(InsertFun, Q, JObj);
_Else -> InsertFun(JObj, Q)
end.
-spec insert_queue_command_into_queue(function(), queue:queue(), kz_json:object()) -> queue:queue().
insert_queue_command_into_queue(InsertFun, CommandQueue, JObj) ->
'true' = kapi_dialplan:queue_v(JObj),
DefJObj = kz_json:from_list(kz_api:extract_defaults(JObj)),
lists:foldr(fun(CmdJObj, TmpQueue) ->
AppCmd = kz_json:merge_jobjs(CmdJObj, DefJObj),
InsertFun(AppCmd, TmpQueue)
end
,CommandQueue
,kz_json:get_list_value(<<"Commands">>, JObj)
).
-spec queue_insert_fun('tail' | 'head') -> function().
queue_insert_fun('tail') ->
fun(JObj, Q) ->
'true' = kapi_dialplan:v(JObj),
case kapi_dialplan:application_name(JObj) of
'undefined' -> Q;
<<"noop">> = AppName ->
MsgId = kz_api:msg_id(JObj),
lager:debug("inserting at the tail of the control queue call command ~s(~s)", [AppName, MsgId]),
queue:in(JObj, Q);
AppName ->
lager:debug("inserting at the tail of the control queue call command ~s", [AppName]),
queue:in(JObj, Q)
end
end;
queue_insert_fun('head') ->
fun(JObj, Q) ->
'true' = kapi_dialplan:v(JObj),
case kapi_dialplan:application_name(JObj) of
'undefined' -> Q;
<<"noop">> = AppName ->
MsgId = kz_api:msg_id(JObj),
lager:debug("inserting at the head of the control queue call command ~s(~s)", [AppName, MsgId]),
queue:in_r(JObj, Q);
AppName ->
lager:debug("inserting at the head of the control queue call command ~s", [AppName]),
queue:in_r(JObj, Q)
end
end.
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
%% See Noop documentation for Filter-Applications to get an idea of this function's purpose
-spec maybe_filter_queue(kz_json:api_objects(), queue:queue()) -> queue:queue().
maybe_filter_queue('undefined', CommandQ) -> CommandQ;
maybe_filter_queue([], CommandQ) -> CommandQ;
maybe_filter_queue([AppName|T]=Apps, CommandQ) when is_binary(AppName) ->
case queue:out(CommandQ) of
{'empty', _} -> CommandQ;
{{'value', NextJObj}, CommandQ1} ->
case AppName =:= kapi_dialplan:application_name(NextJObj) of
'false' -> maybe_filter_queue(T, CommandQ);
'true' ->
lager:debug("app ~s matched next command, popping off", [AppName]),
maybe_filter_queue(Apps, CommandQ1)
end
end;
maybe_filter_queue([AppJObj|T]=Apps, CommandQ) ->
case queue:out(CommandQ) of
{'empty', _} -> CommandQ;
{{'value', NextJObj}, CommandQ1} ->
case (NextAppName = kapi_dialplan:application_name(NextJObj))
=:= (AppName = kapi_dialplan:application_name(AppJObj))
orelse kz_json:get_ne_binary_value(<<"Group-ID">>, NextJObj)
=:= kz_json:get_ne_binary_value(<<"Group-ID">>, AppJObj, <<"nomatch">>)
of
'false' -> maybe_filter_queue(T, CommandQ);
'true' ->
lager:debug("app ~s matched next command ~s, checking fields"
,[AppName, NextAppName]
),
Fields = kz_json:get_json_value(<<"Fields">>, AppJObj, kz_json:new()),