/
gen_media.erl
3997 lines (3778 loc) · 160 KB
/
gen_media.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
%% The contents of this file are subject to the Common Public Attribution
%% License Version 1.0 (the “License”); you may not use this file except
%% in compliance with the License. You may obtain a copy of the License at
%% http://opensource.org/licenses/cpal_1.0. The License is based on the
%% Mozilla Public License Version 1.1 but Sections 14 and 15 have been
%% added to cover use of software over a computer network and provide for
%% limited attribution for the Original Developer. In addition, Exhibit A
%% has been modified to be consistent with Exhibit B.
%%
%% Software distributed under the License is distributed on an “AS IS”
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
%% License for the specific language governing rights and limitations
%% under the License.
%%
%% The Original Code is OpenACD.
%%
%% The Initial Developers of the Original Code is
%% Andrew Thompson and Micah Warren.
%%
%% All portions of the code written by the Initial Developers are Copyright
%% (c) 2008-2009 SpiceCSM.
%% All Rights Reserved.
%%
%% Contributor(s):
%%
%% Andrew Thompson <andrew at hijacked dot us>
%% Micah Warren <micahw at lordnull dot com>
%%
%% @doc Behaviour module for media types. Gen_media uses gen_fsm as the
%% underlying framework for what it does. It exposes a gen_server-esque
%% behavior for it's callback modules, however. Any time gen_media
%% recieves an event it cannot handle wholly intnerally, it will call a
%% specific funciton of the callback module.
%%
%% Replies from handle_call, handle_cast, and handle_info are extended to
%% allow for specific events only media would need.
%%
%% Callback functions:
%%
%% The callback functions follow a general pattern for thier arguments
%% (aside from init). It is:
%% [Arg1, Arg2, Arg3, ..., ArgN, StateName, Call, InternalState, State]
%%
%% Arg1 ... ArgN are arbitrary terms defined in the documenation for
%% each callback.
%%
%% StateName is the current state of the gen_media fsm. The states most
%% commonly used are inivr, inqueue, inqueue_ringing, oncall,
%% oncall_ringing, and wrapup.
%%
%% Call is the most recently #call{}.
%%
%% InternalState is the internal state record of the gen_media fsm with
%% the most pertinant data. These are defined in gen_media.hrl.
%%
%% State is the state the callback module last returned from a callback
%% function. It is used for implementation specific data for medias.
%%
%% <b>init(Args) -> {ok, {State, Route_hint}}</b>
%% types: Args = any()
%% State = any()
%% Route_hint = {Queue, #call{}} | undefined | #call{}
%% Queue = string()
%%
%% When gen_media starts, this function is called. It should
%% initialize all required data.
%%
%% Some media may not be able to provide a call record on start-up,
%% thus allowing the media to finish prepping and then queue later.
%%
%% <b>urlpop_getvars(State) -> UrlOptions</b>
%% types: State = any()
%% UrlOptions = [{string(), string()}]
%%
%% When a call rings to an agent, if a pop url is configured, get
%% variables are appended to the end. If this is set,
%% get_url_getvars/1 will call it and merge the results to what will
%% be used when ringing an agent. Options set via set_url_getvars/2
%% super-ceede those returned by the callback module.
%%
%% At the time of this doc, the agent web interface prompts the agent
%% to adjust the url pop options when doing a queue transfer.
%%
%% <b>prepare_endpoint(Agent, Data) -> Result</b>
%% types: Agent = #agent{}
%% Data = 'inband' | any()
%% Result = {ok, NewData} | {error, Error}
%% NewData = any()
%% Error = any()
%%
%% When an agent is given a new endpoint for the callback module, this
%% function is called. If the callback module returns {error, Error}
%% The agent does not store the given endpoint data. If {ok, NewData}
%% is returned, NewData is stored for the endpoint.
%%
%% The atom 'inband' indicates an agent will go ringing despite the
%% presense or absence of a ring pid. If this behavior is not desired,
%% Module:prepare_endpoint/2 should return {error, any()}, preserving
%% any settings in place already. If there were no settings, the
%% endpoint is no longer used, and any media requiring it will fail
%% to ring to the agent.
%%
%% <b>handle_ring(RingData, Agent, Call, State) -> Result</b>
%% types: RingData = any()
%% Agent = pid()
%% Call = #call{}
%% State = any()
%% Result = {ok, NewState} | {ok, UrlOptions, NewState} |
%% {invalid, NewState}
%% UrlOptions = [{string(), string()}]
%% NewState = any()
%%
%% When a call must ring to an agent (either due to out of queue or
%% the start of a transfer), this is called.
%%
%% RingData is the data the ring channel returned when confirming it is
%% able to function. Gen media does not alter or cache it.
%%
%% Agent is the pid of the agent that will be set to ringing if
%% Result is {ok, NewState} or {ok, UrlOptions, NewState}.
%%
%% Call is the #call{} maintained by the gen_media and passed in for
%% Reference.
%%
%% State is the internal state of the gen_media callbacks.
%%
%% If Result is {ok, NewState} or {ok, UrlOptions, NewState}, Agent
%% is set to ringing, and execution continues with NewState. A
%% url_pop is sent to the agent is the client for the media is set to
%% have one. In the case of {ok, UrlOptions, NewState}, the
%% UrlOptions are appened to the url as a query (get) string.
%%
%% Note that UrlOptions can be set by the agent before a queue
%% transfer occurs. In this case, before the transfer is made,
%% urlpop_getvars/1 should be used to present the agent with a chance
%% to adjust the url pop.
%%
%% If Result is {invalid, NewState}, Agent is set to idle, and
%% execution continues with NewState.
%%
%% <b>handle_ring_stop(StateName, Call, Internal, State) -> Result</b>
%% types: StateName = state_name()
%% Call = #call{}
%% Internal = internal_state()
%% State = any()
%% Result = {ok, NewState}
%% NewState = any()
%%
%% When an agent should no longer be ringing, such as due to ringout,
%% this function is called.
%%
%% State is the internal state of the gen_media callbacks.
%%
%% Execution will continue with NewState.
%%
%% <b>handle_answer({Agent, Apid}, StateName, Call, Internal, State) ->
%% Result</b>
%% types: Agent = string()
%% Apid = pid()
%% StateName = state_name()
%% Call = #call{}
%% Internal = internal_state()
%% State = any()
%% Result = {ok, NewState} | {error, Error, NewState}
%% Error = NewState = any()
%%
%% When an agent should be placed on call after ringing, this function
%% is called.
%%
%% Agent is the agent that will be set oncall if Result is
%% {ok, NewState}.
%%
%% Call is the #call{} the agent will be answering.
%%
%% State is the internal state of the gen_media callbacks.
%%
%% If Result is {ok, NewState} and the callpath is inband, it is
%% assumed the agent has already set themselves oncall. If it is out
%% of band, the agent is set to oncall. The callback module can
%% always safely assume the agent is oncall. Execution then
%% continues with NewState.
%%
%% If Result is {error, Error, NewState}, the agent's state is not
%% changed and execution continues with NewState.
%%
%% <b>handle_voicemail(StateName, Call, Internal, State) -> Result</b>
%% types: StateName = state_name()
%% Call = #call{}
%% Internal = internal_state()
%% State = any()
%% Result = {ok, NewState} | {invalid, NewState}
%%
%% This is an optional callback.
%%
%% When a media should be removed from queue and moved to voicemail,
%% this is called.
%%
%% State is the internal state of the gen_media callbacks.
%%
%% If Result is {ok, NewState}, the call is removed from queue and
%% execution continues with NewState.
%%
%% If Result is {invalid, NewState} execution continues with NewState.
%%
%% <b>handle_annouce(Announce, StateName, Call, Internal, State) ->
%% {ok, NewState}</b>
%% types: Announce = any()
%% StateName = state_name()
%% Call = any()
%% Internal = internal_state()
%% State = NewState = any()
%%
%% This is an optional callback.
%%
%% When a recipe calls for a call in queue to play an announcement, if
%% this function is defined, it is called. Execution then continues
%% with NewState.
%%
%% <b>handle_agent_transfer(Agent, Timeout, StateName, Call, Internal,
%% State) -> Result</b>
%% types: Agent = pid()
%% Timeout = pos_integer()
%% StateName = state_name()
%% Call = #call{}
%% Internal = internal_state()
%% State = any()
%% Result = {ok, NewState} | {error, Error, NewState}
%% NewState = State = any()
%% Error = any()
%%
%% When a media should be transfered to another agent, this is the
%% first step. The target agent is set to prering, then this
%% callback is used to verify that. If the callback returns
%% {ok, NewState}, execution continues with NewState, and gen_media
%% handles with oncall or a ringout.
%%
%% In the case of an outband ring, that process will send a takeover
%% message to gen_media.
%%
%% <b>handle_queue_transfer({Queue, Qpid}, StateName, Call, Internal,
%% State) -> {ok, NewState}</b>
%% types: Queue = string()
%% Qpid = pid
%% StateName = state_name()
%% Call = #call{}
%% Internal = internal_state()
%% State = NewState = any()
%%
%% When a media is placed back into queue from an agent, this is
%% called to allow the media to do any required clean up or
%% unbridging. The Call is requeued at the priority it was initially
%% queued at. Execution then continues with NewState.
%%
%% Queue is the name of the queue the media will be placed in; Qpid is
%% the pid of said queue.
%%
%% <b>handle_wrapup(From, StateName, Call, Internal, State) -> {Finality,
%% NewState}</b>
%% types: From = {pid(), reference()}
%% StateName = state_name()
%% Call = #call{}
%% Internal = internal_state()
%% State = NewState = any()
%% Finality = ok | hangup
%%
%% This callback is only used if the call record's media path is inband.
%% When an agent goes to wrapup, this gives the callback a chance to
%% do any clean-up needed.
%%
%% If the media determines this is a hang-up (ie, no more
%% can be done with the media), it can return {hangup, NewState}. The
%% gen_media then terminates with state NewState.
%%
%% If {ok, NewState} is returned, execution continues with state
%% NewState.
%%
%% <b>handle_spy(Spy, StateName, Call, Internal, State) -> {ok, NewState}
%% | {invalid, NewState} | {error, Error, NewState}</b>
%% types: Spy = {Spypid, AgentRec}
%% Spypid = pid() | any()
%% AgentRec = 'undefined' | #agent{}
%% StateName = state_name()
%% Call = #call{}
%% Internal = internal_state()
%% State = NewState = any()
%%
%% This callback is optional.
%%
%% Spy can be a pid of an agent acting as a spy, or a generic term to
%% be used by the media to allow spying. When spy is an active, agent,
%% They must be released.
%%
%% This signals the callback that a supervisor is attempting to observe
%% the agent that is oncall. The other callbacks should take into
%% account the possibility of a spy if 'ok' is returned.
%%
%% Be aware that when calling this, gen_media does not have a
%% reliable method to determine an agent's security level. The agent
%% connections, however, do.
%%
%% <b>Extended gen_server Callbacks</b>
%%
%% In addition to the usual replies gen_server expects from it's callback
%% of handle_call/3, handle_cast/2, and handle_info/2, gen_media will
%% take some action based on the following Returns.
%%
%% {queue, Queue, Callrec, NewState}
%% types: Queue = string()
%% Callrec = #call{}
%% NewState = any()
%%
%% This result is only valid if the callbacks init/1 returned
%% undefined for the call record. This sets the call record and
%% queues the call. Execution then continues on with NewState. If
%% this is replied to a call, ok is set as the reply.
%%
%% {outbound, Agent, NewState}
%% {outbound, Agent, Call, NewState}
%% types: Agent = pid()
%% Call = #call{}
%% NewState = any()
%%
%% This result is valid only if the call is not queued. The second
%% form is only valid if init/1 retuned an undefined call. This also
%% assumes the agent at pid() is already in precall state. If The
%% agent can be set to outgoing, it will be. Execution continues on
%% with NewState.
%%
%% {voicemail, NewState}
%% types: NewState = any()
%%
%% This result is valid only if the call is queued. Removes the media
%% from queue and stops ringing to an agent it is. Assumes the media
%% has already done what it needs to for a voicemail. If done in a
%% handle_call, the reply is 'ok'.
%%
%% {Agentaction, NewState}
%% {Agentaction, Reply, NewState}
%% types: Agentaction = stop_ring | {stop_ring, Data} | wrapup | hangup |
%% {hangup, Data} | {mediapush, Data, Mode}
%% Reply = any()
%% NewState = any()
%% Data = any()
%% Mode = replace | append
%%
%% This result is only valid if an agent has been associated with this
%% media by ringing. The second form is only valid if the request
%% came in as a gen_media:call. This attempts to take the specified
%% action on the agent, then continues execution with NewState.
%%
%% {stop_ring, Data} is used to stop the gen_media from handling a
%% ringout. It does not change the agent's state. Execution will
%% continue with NewState. This is useful if there is an error
%% ringing to an agent that only becomes apparent at a later time. A
%% return of `stop_ring' is Equivalent to {stop_ring, undefined}.
%%
%% wrapup is only valid if there is an agent associated with a media,
%% and that agent is oncall or outgoing. This sets the agent to
%% wrapup and continues execution with NewState.
%%
%% {hangup, Data} is valid at any time. This will unqueue the media,
%% and set the appropriate state for any agents. The cdr record will
%% record Data as who hung up the call. A return of hangup is
%% equivalent to {hangup, undefined}. Execution then coninues with
%% NewState.
%%
%% mediapush is only valid if there is an agent oncall with the media,
%% and the media is inband. The given Data is casted to the
%% associaed agent as a media push.
%%
%% {stop, hangup, NewState}
%% {stop, {hangup, Data}, NewState}
%% types: NewState = any()
%% Data = any()
%%
%% This causes the media to take any action it would from an
%% Agentaction return tuple of hangup, then stop.
% TODO Less agent oriented and more agent channel oriented.
-module(gen_media).
-author(micahw).
-behaviour(gen_fsm).
-include("log.hrl").
-include("call.hrl").
-include("agent.hrl").
-include("gen_media.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
%% API
-export([
behaviour_info/1,
start_link/2,
start/2
]).
%% gen_fsm callbacks
-export([
init/1, terminate/3, code_change/4,
handle_event/3, handle_sync_event/4, handle_info/3,
inivr/2, inivr/3,
inqueue/2, inqueue/3,
inqueue_ringing/2, inqueue_ringing/3,
oncall/2, oncall/3,
oncall_ringing/2, oncall_ringing/3,
wrapup/2, wrapup/3
]).
%% gen_media api
-export([
ring/4,
ring/3,
takeover_ring/2,
get_call/1,
voicemail/1,
announce/2,
%% TODO added for testing only (implemented with focus on real Calls - no other media)
end_call/1,
stop_ringing/1,
oncall/1,
agent_transfer/3,
queue/2,
call/2,
call/3,
cast/2,
wrapup/1,
spy/3,
set_cook/2,
set_queue/2,
set_url_getvars/2,
get_url_getvars/1,
add_skills/2
]).
% TODO - add these to a global .hrl, cpx perhaps?
-type(proplist_item() :: atom() | {any(), any()}).
-type(proplist() :: [proplist_item()]).
%% gen_media states
-define(states, [
inivr, inqueue, inqueue_ringing, oncall, oncall_ringing, wrapup
]).
%% state changes
%% init -> inivr, inqueue, oncall (in case of outbound)
%% inivr -> inqueue
%% inqueue -> inqueue_ringing
%% inqueue_ringing -> inqueue, oncall
%% oncall -> oncall_ringing, wrapup, warm_transfer_hold, inqueue
%% oncall_ringing -> oncall (same state), oncall (new agent)
%% wrapup -> *
%% warm_transfer_hold -> warm_transfer_3rd_party, oncall, wrapup
%% warm_transfer_3rd_party -> warm_transfer_merged, warm_transfer_hold
%% warm_transfer_merged -> oncall, wrapup
-record(base_state, {
callback :: atom(),
substate :: any(),
callrec :: 'undefined' | #call{},
queue_failover,
url_pop_get_vars = []
}).
-spec(behaviour_info/1 ::
(Info :: 'callbacks' | any()) -> [{atom(), non_neg_integer()}] | 'undefined').
behaviour_info(callbacks) ->
[
{prepare_endpoint, 2},
{init, 1},
{handle_ring, 4},
{handle_ring_stop, 4},
{handle_answer, 5},
%{handle_voicemail, 4},
%{handle_announce, 5},
{handle_agent_transfer, 4},
{handle_queue_transfer, 5},
{handle_wrapup, 5},
{handle_call, 6},
{handle_cast, 5},
{handle_info, 5},
{terminate, 5},
{code_change, 4}
];
behaviour_info(_Other) ->
undefined.
%% @doc Make the `pid() Genmedia' ring to `pid() Agent' based off of
%% `#queued_call{} Qcall' with a ringout of `pos_integer() Timeout'
%% miliseconds.
%% @deprecated Use ring/3 instead as timout is ignored. The ringout is
%% determined by the client option "ringout", the default value being
%% 60000.
-spec(ring/4 :: (Genmedia :: pid(), Agent :: pid() | string() | {string(), pid()}, Qcall :: #queued_call{}, Timeout :: pos_integer()) -> 'ok' | 'invalid' | 'deferred').
ring(Genmedia, {_Agent, Apid} = A, Qcall, Timeout) when is_pid(Apid) ->
?INFO("Ring invoked to: ~p from ~p", [_Agent, self()]),
gen_fsm:sync_send_event(Genmedia, {{'$gen_media', ring}, {A, Qcall, Timeout}}, infinity);
ring(Genmedia, Apid, Qcall, Timeout) when is_pid(Apid) ->
case agent_manager:find_by_pid(Apid) of
notfound ->
invalid;
Agent ->
ring(Genmedia, {Agent, Apid}, Qcall, Timeout)
end;
ring(Genmedia, Agent, Qcall, Timeout) ->
case agent_manager:query_agent(Agent) of
{true, Apid} ->
ring(Genmedia, {Agent, Apid}, Qcall, Timeout);
false ->
invalid
end.
%% @doc Have the given gen_media ring the given agent based on the given
%% queued call.
-spec ring(Genmedia :: pid(),
Agent :: pid() | string() | {string(), pid()},
Qcall :: #queued_call{}) -> 'ok' | 'invalid' | 'deferred'.
ring(Genmedia, {_Agent, _Apid}=A, Qcall) ->
gen_fsm:sync_send_event(Genmedia, {{'$gen_media', ring}, {A, Qcall, undefined}}, infinity);
ring(Genmedia, Apid, Qcall) when is_pid(Apid) ->
case agent_manager:find_by_pid(Apid) of
notfound ->
invalid;
Agent ->
ring(Genmedia, {Agent, Apid}, Qcall)
end;
ring(Genmedia, Agent, Qcall) ->
case agent_manager:query_agent(Agent) of
{true, Apid} ->
ring(Genmedia, {Agent, Apid}, Qcall);
false ->
invalid
end.
-spec(takeover_ring/2 :: (Genmedia :: pid(), Agent :: pid() | string() | {string(), pid()}) -> 'ok' | 'invalid').
takeover_ring(Genmedia, {_, Apid} = Agent) when is_pid(Apid) ->
Self = self(),
gen_fsm:send_event(Genmedia, {{'$gen_media', takeover_ring}, {Agent, Self}});
takeover_ring(Genmedia, Apid) when is_pid(Apid) ->
case agent_manager:find_by_pid(Apid) of
notfound -> invalid;
Agent -> takeover_ring(Genmedia, {Agent, Apid})
end;
takeover_ring(Genmedia, Agent) ->
case agent_manager:query_agent(Agent) of
{true, Apid} -> takeover_ring(Genmedia, {Agent, Apid});
false -> invalid
end.
%% @doc Get the call record associated with `pid() Genmedia'.
-spec(get_call/1 :: (Genmedia :: pid()) -> #call{}).
get_call(Genmedia) ->
gen_fsm:sync_send_all_state_event(Genmedia, {{'$gen_media', get_call}, undefined}, infinity).
%% @doc Send the passed `pid() Genmedia' to voicemail.
-spec(voicemail/1 :: (Genmedia :: pid()) -> 'ok' | 'invalid').
voicemail(Genmedia) ->
gen_fsm:sync_send_event(Genmedia, {{'$gen_media', voicemail}, undefined}).
%% @doc Pass `any() Annouce' message to `pid() Genmedia'.
-spec(announce/2 :: (Genmedia :: pid(), Annouce :: any()) -> 'ok').
announce(Genmedia, Annouce) ->
gen_fsm:sync_send_event(Genmedia, {{'$gen_media', announce}, Annouce}).
%% TODO added for testing only (implemented with focus on real Calls - no other media)
%% @doc End the Call for `pid() Genmedia'.
-spec(end_call/1 :: (Genmedia :: pid()) -> 'ok').
end_call(Genmedia) ->
gen_server:call(Genmedia, '$gen_media_end_call').
%% @doc Sends the oncall agent associated with the call to wrapup; or, if it's
%% the oncall agent making the request, gives the callback module a chance to
%% handle it.
-spec(wrapup/1 :: (Genmedia :: pid()) -> 'ok' | 'invalid').
wrapup(Genmedia) ->
gen_fsm:sync_send_event(Genmedia, {{'$gen_media', wrapup}, undefined}).
%% @doc Send a stop ringing message to `pid() Genmedia'.
-spec(stop_ringing/1 :: (Genmedia :: pid()) -> 'ok').
stop_ringing(Genmedia) ->
stop_ringing(Genmedia, undefined).
%% @doc Send a stop ringing message to `pid() Genmedia' with reason.
-spec(stop_ringing/2 :: (Genmedia :: pid(), Reason :: atom()) -> 'ok').
stop_ringing(Genmedia, Reason) ->
gen_fsm:send_event(Genmedia, {{'$gen_media', stop_ringing}, Reason}).
%% @doc Set the agent associated with `pid() Genmedia' to oncall.
-spec(oncall/1 :: (Genmedia :: pid()) -> 'ok' | 'invalid').
oncall(Genmedia) ->
gen_fsm:sync_send_event(Genmedia, {{'$gen_media', agent_oncall}, undefined}, infinity).
%% @doc Transfer the call from the agent it is associated with to a new agent.
-spec(agent_transfer/3 :: (Genmedia :: pid(), Apid :: pid() | string() | {string(), pid()}, Timeout :: pos_integer()) -> 'ok' | 'invalid').
agent_transfer(Genmedia, {_Login, Apid} = Agent, Timeout) when is_pid(Apid) ->
gen_fsm:sync_send_event(Genmedia, {{'$gen_media', agent_transfer}, {Agent, Timeout}});
agent_transfer(Genmedia, Apid, Timeout) when is_pid(Apid) ->
case agent_manager:find_by_pid(Apid) of
notfound ->
invalid;
Agent ->
agent_transfer(Genmedia, {Agent, Apid}, Timeout)
end;
agent_transfer(Genmedia, Agent, Timeout) ->
case agent_manager:query_agent(Agent) of
false ->
invalid;
{true, Apid} ->
agent_transfer(Genmedia, {Agent, Apid}, Timeout)
end.
%% @doc Transfer the passed media into the given queue.
-spec(queue/2 :: (Genmedia :: pid(), Queue :: string()) -> 'ok' | 'invalid').
queue(Genmedia, Queue) ->
gen_fsm:sync_send_event(Genmedia, {'$gen_media', queue, Queue}).
%% @doc Attempt to spy on the agent oncall with the given media. `Spy' is
%% the pid to send media events/load data to, and `AgentRec' is an
%% `#agent{}' used to hold the end point data.
-spec(spy/3 :: (Genmedia :: pid(), Spy :: pid(), AgentRec :: #agent{}) -> 'ok' | 'invalid' | {'error', any()}).
spy(Genmedia, Spy, AgentRec) ->
gen_fsm:sync_send_event(Genmedia, {{'$gen_media', spy}, {Spy, AgentRec}}).
-spec(set_cook/2 :: (Genmedia :: pid(), CookPid :: pid()) -> 'ok').
set_cook(Genmedia, CookPid) ->
gen_fsm:send_event(Genmedia, {{'$gen_media', set_cook}, CookPid}).
-spec(set_queue/2 :: (Genmedia :: pid(), Qpid :: pid()) -> 'ok').
set_queue(Genmedia, Qpid) ->
gen_fsm:sync_send_event(Genmedia, {{'$gen_media', set_queue}, Qpid}).
-spec(set_url_getvars/2 :: (Genmedia :: pid(), Vars :: [{string(), string()}]) -> 'ok').
set_url_getvars(Genmedia, Vars) ->
gen_fsm:sync_send_all_state_event(Genmedia, {{'$gen_media', set_url_getvars}, Vars}).
-spec(get_url_getvars/1 :: (Genmedia :: pid()) -> {'ok', [{string(), string()}]}).
get_url_getvars(Genmedia) ->
gen_fsm:sync_send_all_state_event(Genmedia, {{'$gen_media', get_url_vars}, undefined}).
-spec(add_skills/2 :: (Genmedia :: pid(), Skills :: [atom() | {atom(), any()}]) -> 'ok').
add_skills(Genmedia, Skills) ->
gen_fsm:send_all_state_event(Genmedia, {{'$gen_media', add_skills}, Skills}).
%% @doc Do the equivalent of a `gen_server:call/2'.
-spec(call/2 :: (Genmedia :: pid(), Request :: any()) -> any()).
call(Genmedia, Request) ->
gen_fsm:sync_send_all_state_event(Genmedia, Request).
%% @doc Do the equivalent of `gen_server:call/3'.
-spec(call/3 :: (Genmedia :: pid(), Request :: any(), Timeout :: pos_integer()) -> any()).
call(Genmedia, Request, Timeout) ->
gen_fsm:sync_send_all_state_event(Genmedia, Request, Timeout).
%% @doc Do the equivalent of `gen_server:cast/2'.
-spec(cast/2 :: (Genmedia :: pid(), Request:: any()) -> 'ok').
cast(Genmedia, Request) ->
gen_fsm:send_all_state_event(Genmedia, Request).
%%====================================================================
%% API
%%====================================================================
%% @doc Start a gen_media linked to the calling process.
-spec(start_link/2 :: (Callback :: atom(), Args :: any()) -> {'ok', pid()} | 'ignore' | {'error', any()}).
start_link(Callback, Args) ->
gen_fsm:start_link(?MODULE, [Callback, Args], []).
-spec(start/2 :: (Callback :: atom(), Args :: any()) -> {'ok', pid()} | 'ignore' | {'error', any()}).
start(Callback, Args) ->
gen_fsm:start(?MODULE, [Callback, Args], []).
%%====================================================================
%% init callbacks
%%====================================================================
%% @private
init([Callback, Args]) ->
case Callback:init(Args) of
{ok, {Substate, undefined}} ->
BaseState = #base_state{
callback = Callback,
substate = Substate,
callrec = undefined
},
{ok, inivr, {BaseState, #inivr_state{}}};
{ok, {Substate, {Queue, PCallrec}}} when is_record(PCallrec, call) ->
Callrec = correct_client(PCallrec),
cdr:cdrinit(Callrec),
cpx_monitor:set({media, Callrec#call.id}, [], self()),
BaseState = #base_state{
callback = Callback,
substate = Substate,
callrec = Callrec
},
{_Qnom, Qpid} = case priv_queue(Queue, Callrec, true) of
{default, Pid} ->
set_cpx_mon({#base_state{callrec = Callrec}, #inqueue_state{queue_pid = {"default_queue", Pid}}}, [{queue, "default_queue"}]),
cdr:inqueue(Callrec, "default_queue"),
{"default_queue", Pid};
Else when is_pid(Else) ->
cdr:inqueue(Callrec, Queue),
Qmon = erlang:monitor(process, Else),
set_cpx_mon({#base_state{callrec = Callrec}, #inqueue_state{queue_mon = Qmon, queue_pid = {Queue, Else}}}, [{queue, Queue}]),
{Queue, Else}
end,
InqState = #inqueue_state{
queue_pid = {Queue, Qpid},
queue_mon = erlang:monitor(process, Qpid)
},
{ok, inqueue, {BaseState, InqState}};
{ok, {Substate, PCallrec, {CDRState, CDRArgs}}} when is_record(PCallrec, call) ->
Callrec = correct_client(PCallrec),
cdr:cdrinit(Callrec),
apply(cdr, CDRState, [Callrec | CDRArgs]),
BaseState = #base_state{
callback = Callback,
substate = Substate,
callrec = Callrec
},
set_cpx_mon({BaseState, #inivr_state{}}, [], self()),
{ok, inivr, {BaseState, #inivr_state{}}};
{ok, {Substate, PCallrec}} when is_record(PCallrec, call) ->
Callrec = correct_client(PCallrec),
cdr:cdrinit(Callrec),
set_cpx_mon({#base_state{callrec = Callrec}, #inivr_state{}}, [], self()),
BaseState = #base_state{
callback = Callback,
substate = Substate,
callrec = Callrec
},
{ok, inivr, {BaseState, #inivr_state{}}};
{stop, Reason} = O ->
?WARNING("init aborted due to ~p", [Reason]),
O;
ignore ->
?WARNING("init told to ignore", []),
ignore
end.
%%--------------------------------------------------------------------
%% inivr -> inqueue
%%--------------------------------------------------------------------
inivr({{'$gen_media', Command}, _Args}, _From, State) ->
?DEBUG("Invalid sync event ~s while inivr", [Command]),
{reply, invalid, inivr, State};
inivr(Msg, From, {#base_state{callback = Callback} = BaseState, _} = State) ->
Return = Callback:handle_call(Msg, From, inivr, BaseState#base_state.callrec, #inivr_state{}, BaseState#base_state.substate),
handle_custom_return(Return, inivr, reply, State).
inivr(Msg, {#base_state{ callback = Callback, callrec = Call} = BaseState,
_} = State) ->
Return = Callback:handle_cast(Msg, inivr, Call, #inivr_state{}, BaseState#base_state.substate),
handle_custom_return(Return, inivr, noreply, State).
%%--------------------------------------------------------------------
%% inqueue -> inqueue_ringing
%%--------------------------------------------------------------------
inqueue({{'$gen_media', ring}, {{Agent, Apid}, #queued_call{
cook = Requester}, _Timeout}}, {Requester, _Tag}, {
#base_state{callrec = Call} = BaseState,
Internal}) ->
ClientOpts = Call#call.client#client.options,
TimeoutSec = proplists:get_value("ringout", ClientOpts, 60),
Timeout = TimeoutSec * 1000,
?INFO("Trying to ring ~p with ~p with timeout ~p", [Agent, Call#call.id, Timeout]),
try agent:prering(Apid, Call) of
{ok, RPid} ->
Rmon = erlang:monitor(process, RPid),
Tref = gen_fsm:send_event_after(Timeout, {{'$gen_media', ringout}, undefined}),
#inqueue_state{ queue_pid = Qpid, queue_mon = Qmon,
cook_mon = CookMon} = Internal,
NewInternal = #inqueue_ringing_state{
queue_pid = Qpid, queue_mon = Qmon, ring_pid = {Agent, RPid},
ring_mon = Rmon, cook = Requester, cook_mon = CookMon,
ringout = Tref
},
{reply, ok, inqueue_ringing, {BaseState, NewInternal}};
RingErr ->
?INFO("Agent ~p prering response: ~p for ~p", [Agent, RingErr, Call#call.id]),
{reply, invalid, inqueue, {BaseState, Internal}}
catch
exit:{noproc, {gen_fsm, sync_send_event, _TheArgs}} ->
?WARNING("Agent ~p is a dead pid", [Apid]),
{reply, invalid, inqueue, {BaseState, Internal}};
exit:{max_ringouts, {gen_fsm, sync_send_event, _TheArgs}} ->
?DEBUG("Max ringouts reached for agent ~p", [Apid]),
{reply, invalid, inqueue, {BaseState, Internal}}
end;
inqueue({{'$gen_media', ring}, {{_Agent, Apid}, QCall, _Timeout}}, _From, State) ->
gen_server:cast(QCall#queued_call.cook, {ring_to, Apid, QCall}),
{reply, deferred, inqueue, State};
inqueue({{'$gen_media', announce}, Announce}, _From, {#base_state{
callback = Callback, substate = InSubstate, callrec = Call} =
BaseState, Internal}) ->
?INFO("Doing announce for ~p", [Call#call.id]),
Substate = case erlang:function_exported(Callback, handle_announce, 5) of
true ->
{ok, N} = Callback:handle_announce(Announce, inqueue, Call, Internal, InSubstate),
N;
false ->
InSubstate
end,
{reply, ok, inqueue, {BaseState#base_state{substate = Substate}, Internal}};
inqueue({{'$gen_media', voicemail}, undefined}, _From, {BaseState, Internal}) ->
#base_state{callback = Callback, callrec = Call} = BaseState,
?INFO("trying to send media ~p to voicemail", [Call#call.id]),
case erlang:function_exported(Callback, handle_voicemail, 4) of
false ->
{reply, invalid, inqueue, {BaseState, Internal}};
true ->
case Callback:handle_voicemail(inqueue, Call, Internal, BaseState#base_state.substate) of
{ok, Substate} ->
priv_voicemail({BaseState, Internal}),
{reply, ok, inqueue, {BaseState#base_state{substate = Substate}, Internal}};
{invalid, Substate} ->
{reply, invalid, inqueue, {BaseState#base_state{substate = Substate}, Internal}}
end
end;
inqueue({{'$gen_media', end_call}, _}, {Cook, _}, {#base_state{
callrec = #call{cook = Cook}} = BaseState, InqueueState}) ->
#base_state{callback = Callback, substate = InSubstate,
callrec = Call} = BaseState,
case erlang:function_exported(Callback, handle_end_call, 4) of
true ->
case Callback:handle_end_call(inqueue, Call, InqueueState, InSubstate) of
{ok, Substate} ->
% stop agent ringing, kill self
?INFO("Ending Call for ~p", [Call#call.id]),
NewState0 = BaseState#base_state{substate = Substate},
{Out, NewState} = handle_stop(hangup, inqueue, NewState0, InqueueState),
{stop, Out, ok, NewState};
{deferred, Substate} ->
?INFO("Ending Call deferred for ~p", [Call#call.id]),
% up to the media to kill self.
NewBase = BaseState#base_state{substate = Substate},
{reply, ok, {NewBase, InqueueState}};
{error, Err, Substate} ->
?INFO("Ending Call for ~p errored: ~p", [Call#call.id, Err]),
NewBase = BaseState#base_state{substate = Substate},
{reply, invalid, {NewBase, InqueueState}}
end;
false ->
{reply, invalid, {BaseState, InqueueState}}
end;
inqueue({{'$gen_media', set_queue}, Qpid}, _From, {BaseState,
#inqueue_state{queue_pid = {Queue, _}} = Internal}) ->
#base_state{callrec = Call} = BaseState,
?NOTICE("Updating queue pid for ~p to ~p", [Call#call.id, Qpid]),
case Internal#inqueue_state.queue_mon of
undefined ->
ok;
M ->
erlang:demonitor(M)
end,
Newmon = erlang:monitor(process, Qpid),
NewInternal = Internal#inqueue_state{
queue_mon = Newmon,
queue_pid = {Queue, Qpid}
},
{reply, ok, inqueue, {BaseState, NewInternal}};
inqueue({{'$gen_media', get_url_vars}, undefined}, _From, {BaseState, Internal}) ->
#base_state{url_pop_get_vars = GenPopopts, substate = Substate,
callback = Callback} = BaseState,
Cbopts = case erlang:function_exported(Callback, urlpop_getvars, 1) of
true ->
Callback:urlpop_getvars(Substate);
false ->
[]
end,
Out = lists:ukeymerge(1, lists:ukeysort(1, GenPopopts), lists:ukeysort(1, Cbopts)),
{reply, {ok, Out}, inqueue, {BaseState, Internal}};
inqueue({{'$gen_media', Command}, _Args}, _From, State) ->
?DEBUG("Invalid sync event ~s while inqueue", [Command]),
{reply, invalid, inqueue, State};
inqueue(Msg, From, {#base_state{callback = Callback, callrec = Call} = BaseState, InQueueState} = State) ->
Return = Callback:handle_call(Msg, From, inqueue, Call, InQueueState, BaseState#base_state.substate),
handle_custom_return(Return, inqueue, reply, State).
inqueue({{'$gen_media', set_outband_ring_pid}, Pid}, {BaseState, Internal}) ->
NewInternal = Internal#inqueue_state{outband_ring_pid = Pid},
{next_state, inqueue, {BaseState, NewInternal}};
inqueue({{'$gen_media', set_cook}, CookPid}, {BaseState, Internal}) ->
#base_state{callrec = Call} = BaseState,
?NOTICE("Updating cook pid for ~p to ~p", [Call#call.id, CookPid]),
case Internal#inqueue_state.cook_mon of
undefined ->
ok;
M ->
erlang:demonitor(M)
end,
Newmon = erlang:monitor(process, CookPid),
NewCall = Call#call{cook = CookPid},
NewInternal = Internal#inqueue_state{cook_mon = Newmon, cook = CookPid},
NewBase = BaseState#base_state{callrec = NewCall},
{next_state, inqueue, {NewBase, NewInternal}};
inqueue({{'$gen_media', Command}, _}, State) ->
?DEBUG("Invalid event ~s while inqueue", [Command]),
{next_state, inqueue, State};
inqueue(Msg, {#base_state{callback = Callback, callrec = Call} = BaseState,
InQueueState} = State) ->
Return = Callback:handle_cast(Msg, inqueue, Call, InQueueState, BaseState#base_state.substate),
handle_custom_return(Return, inqueue, noreply, State).
%%--------------------------------------------------------------------
%% inqueue_ringing -> inqueue, oncall
%%--------------------------------------------------------------------
inqueue_ringing({{'$gen_media', announce}, Announce}, _From, {BaseState, Internal}) ->
#base_state{callback = Callback, substate = InSubstate,
callrec = Call} = BaseState,
?INFO("Doing announce for ~p", [Call#call.id]),
Substate = case erlang:function_exported(Callback, handle_announce, 5) of
true ->
{ok, N} = Callback:handle_announce(Announce, inqueue_ringing, Call, Internal, InSubstate),
N;
false ->
InSubstate
end,
{reply, ok, inqueue_ringing, {BaseState#base_state{substate = Substate}, Internal}};
inqueue_ringing({{'$gen_media', voicemail}, undefined}, _From, {BaseState, Internal}) ->
#base_state{callback = Callback, callrec = Call} = BaseState,
?INFO("trying to send media ~p to voicemail", [Call#call.id]),
case erlang:function_exported(Callback, handle_voicemail, 4) of
false ->
{reply, invalid, inqueue_ringing, {BaseState, Internal}};
true ->
case Callback:handle_voicemail(inqueue_ringing, Call, Internal, BaseState#base_state.substate) of
{ok, Substate} ->
priv_voicemail({BaseState, Internal}),
NewInternal = #inqueue_state{
queue_mon = Internal#inqueue_ringing_state.queue_mon,
queue_pid = Internal#inqueue_ringing_state.queue_pid,
cook = Internal#inqueue_ringing_state.cook,
cook_mon = Internal#inqueue_ringing_state.cook_mon
},
NewBase = BaseState#base_state{substate = Substate},
{reply, ok, inqueue, {NewBase, NewInternal}};
{invalid, Substate} ->
{reply, invalid, inqueue_ringing, {BaseState#base_state{substate = Substate}, Internal}}
end
end;
inqueue_ringing({{'$gen_media', agent_oncall}, undefined}, {Apid, _Tag},
{#base_state{callrec = #call{ring_path = outband} = Call} = BaseState,
#inqueue_ringing_state{ring_pid = {_, Apid}} = Internal}) ->
?INFO("Cannot accept on call requests from agent (~p) unless ring_path is inband for ~p", [Apid, Call#call.id]),
{reply, invalid, inqueue_ringing, {BaseState, Internal}};
inqueue_ringing({{'$gen_media', agent_oncall}, undefined}, {Apid, _Tag},
{#base_state{callrec = #call{ring_path = inband} = Call} = BaseState,
#inqueue_ringing_state{ring_pid = {Agent, Apid}} = Internal}) ->
#base_state{callback = Callback} = BaseState,
?INFO("oncall request from agent ~p for ~p", [Apid, Call#call.id]),
case Callback:handle_answer(Apid, inqueue_ringing, Call, Internal, BaseState#base_state.substate) of
{ok, NewState} ->
kill_outband_ring({BaseState, Internal}),
case Internal#inqueue_ringing_state.ringout of
undefined -> ok;
TimerRef -> gen_fsm:cancel_timer(TimerRef)
end,
unqueue(Internal#inqueue_ringing_state.queue_pid, self()),
cdr:oncall(Call, Agent),
NewBase = BaseState#base_state{substate = NewState},
NewInternal = #oncall_state{
oncall_pid = {Agent, Apid},
oncall_mon = Internal#inqueue_ringing_state.ring_mon
},
set_cpx_mon({NewBase, NewInternal}, [{agent, Agent}]),
erlang:demonitor(Internal#inqueue_ringing_state.queue_mon),
{reply, ok, oncall, {NewBase, NewInternal}};
{error, Reason, NewState} ->
?ERROR("Could not set ~p on call due to ~p for ~p", [Apid, Reason, Call#call.id]),
NewBase = BaseState#base_state{substate = NewState},
{reply, invalid, inqueue_ringing, {NewBase, Internal}}
end;