adhearsion-cw 1.0.2.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (118) hide show
  1. data/CHANGELOG +109 -0
  2. data/EVENTS +11 -0
  3. data/Gemfile +3 -0
  4. data/LICENSE +456 -0
  5. data/Rakefile +134 -0
  6. data/adhearsion.gemspec +174 -0
  7. data/app_generators/ahn/USAGE +5 -0
  8. data/app_generators/ahn/ahn_generator.rb +97 -0
  9. data/app_generators/ahn/templates/.ahnrc +34 -0
  10. data/app_generators/ahn/templates/Gemfile +7 -0
  11. data/app_generators/ahn/templates/README +8 -0
  12. data/app_generators/ahn/templates/Rakefile +27 -0
  13. data/app_generators/ahn/templates/components/ami_remote/ami_remote.rb +15 -0
  14. data/app_generators/ahn/templates/components/disabled/HOW_TO_ENABLE +7 -0
  15. data/app_generators/ahn/templates/components/disabled/restful_rpc/README.markdown +11 -0
  16. data/app_generators/ahn/templates/components/disabled/restful_rpc/example-client.rb +48 -0
  17. data/app_generators/ahn/templates/components/disabled/restful_rpc/restful_rpc.rb +91 -0
  18. data/app_generators/ahn/templates/components/disabled/restful_rpc/restful_rpc.yml +34 -0
  19. data/app_generators/ahn/templates/components/disabled/restful_rpc/spec/restful_rpc_spec.rb +251 -0
  20. data/app_generators/ahn/templates/components/disabled/sandbox/sandbox.rb +104 -0
  21. data/app_generators/ahn/templates/components/disabled/sandbox/sandbox.yml +2 -0
  22. data/app_generators/ahn/templates/components/disabled/stomp_gateway/README.markdown +47 -0
  23. data/app_generators/ahn/templates/components/disabled/stomp_gateway/stomp_gateway.rb +34 -0
  24. data/app_generators/ahn/templates/components/disabled/stomp_gateway/stomp_gateway.yml +12 -0
  25. data/app_generators/ahn/templates/components/disabled/xmpp_gateway/README.markdown +3 -0
  26. data/app_generators/ahn/templates/components/disabled/xmpp_gateway/xmpp_gateway.rb +11 -0
  27. data/app_generators/ahn/templates/components/disabled/xmpp_gateway/xmpp_gateway.yml +0 -0
  28. data/app_generators/ahn/templates/components/simon_game/simon_game.rb +56 -0
  29. data/app_generators/ahn/templates/config/startup.rb +74 -0
  30. data/app_generators/ahn/templates/dialplan.rb +3 -0
  31. data/app_generators/ahn/templates/events.rb +32 -0
  32. data/bin/ahn +29 -0
  33. data/bin/ahnctl +68 -0
  34. data/bin/jahn +43 -0
  35. data/examples/asterisk_manager_interface/standalone.rb +51 -0
  36. data/lib/adhearsion/cli.rb +296 -0
  37. data/lib/adhearsion/component_manager/component_tester.rb +53 -0
  38. data/lib/adhearsion/component_manager/spec_framework.rb +18 -0
  39. data/lib/adhearsion/component_manager.rb +272 -0
  40. data/lib/adhearsion/events_support.rb +84 -0
  41. data/lib/adhearsion/foundation/all.rb +15 -0
  42. data/lib/adhearsion/foundation/blank_slate.rb +3 -0
  43. data/lib/adhearsion/foundation/custom_daemonizer.rb +45 -0
  44. data/lib/adhearsion/foundation/event_socket.rb +205 -0
  45. data/lib/adhearsion/foundation/future_resource.rb +36 -0
  46. data/lib/adhearsion/foundation/metaprogramming.rb +17 -0
  47. data/lib/adhearsion/foundation/numeric.rb +13 -0
  48. data/lib/adhearsion/foundation/pseudo_guid.rb +10 -0
  49. data/lib/adhearsion/foundation/relationship_properties.rb +42 -0
  50. data/lib/adhearsion/foundation/string.rb +26 -0
  51. data/lib/adhearsion/foundation/synchronized_hash.rb +96 -0
  52. data/lib/adhearsion/foundation/thread_safety.rb +7 -0
  53. data/lib/adhearsion/host_definitions.rb +67 -0
  54. data/lib/adhearsion/initializer/asterisk.rb +87 -0
  55. data/lib/adhearsion/initializer/configuration.rb +321 -0
  56. data/lib/adhearsion/initializer/database.rb +60 -0
  57. data/lib/adhearsion/initializer/drb.rb +31 -0
  58. data/lib/adhearsion/initializer/freeswitch.rb +22 -0
  59. data/lib/adhearsion/initializer/ldap.rb +57 -0
  60. data/lib/adhearsion/initializer/rails.rb +41 -0
  61. data/lib/adhearsion/initializer/xmpp.rb +42 -0
  62. data/lib/adhearsion/initializer.rb +394 -0
  63. data/lib/adhearsion/logging.rb +92 -0
  64. data/lib/adhearsion/tasks/components.rb +32 -0
  65. data/lib/adhearsion/tasks/database.rb +5 -0
  66. data/lib/adhearsion/tasks/deprecations.rb +59 -0
  67. data/lib/adhearsion/tasks/generating.rb +20 -0
  68. data/lib/adhearsion/tasks/lint.rb +4 -0
  69. data/lib/adhearsion/tasks/testing.rb +37 -0
  70. data/lib/adhearsion/tasks.rb +17 -0
  71. data/lib/adhearsion/version.rb +35 -0
  72. data/lib/adhearsion/voip/asterisk/agi_server.rb +115 -0
  73. data/lib/adhearsion/voip/asterisk/commands.rb +1581 -0
  74. data/lib/adhearsion/voip/asterisk/config_generators/agents.conf.rb +140 -0
  75. data/lib/adhearsion/voip/asterisk/config_generators/config_generator.rb +102 -0
  76. data/lib/adhearsion/voip/asterisk/config_generators/queues.conf.rb +250 -0
  77. data/lib/adhearsion/voip/asterisk/config_generators/voicemail.conf.rb +240 -0
  78. data/lib/adhearsion/voip/asterisk/config_manager.rb +71 -0
  79. data/lib/adhearsion/voip/asterisk/manager_interface/ami_lexer.rb +1681 -0
  80. data/lib/adhearsion/voip/asterisk/manager_interface/ami_lexer.rl.rb +341 -0
  81. data/lib/adhearsion/voip/asterisk/manager_interface/ami_messages.rb +78 -0
  82. data/lib/adhearsion/voip/asterisk/manager_interface/ami_protocol_lexer_machine.rl +87 -0
  83. data/lib/adhearsion/voip/asterisk/manager_interface.rb +705 -0
  84. data/lib/adhearsion/voip/asterisk/special_dial_plan_managers.rb +80 -0
  85. data/lib/adhearsion/voip/asterisk/super_manager.rb +19 -0
  86. data/lib/adhearsion/voip/asterisk.rb +4 -0
  87. data/lib/adhearsion/voip/call.rb +498 -0
  88. data/lib/adhearsion/voip/call_routing.rb +64 -0
  89. data/lib/adhearsion/voip/commands.rb +9 -0
  90. data/lib/adhearsion/voip/constants.rb +39 -0
  91. data/lib/adhearsion/voip/conveniences.rb +18 -0
  92. data/lib/adhearsion/voip/dial_plan.rb +250 -0
  93. data/lib/adhearsion/voip/dsl/dialing_dsl/dialing_dsl_monkey_patches.rb +37 -0
  94. data/lib/adhearsion/voip/dsl/dialing_dsl.rb +151 -0
  95. data/lib/adhearsion/voip/dsl/dialplan/control_passing_exception.rb +27 -0
  96. data/lib/adhearsion/voip/dsl/dialplan/dispatcher.rb +124 -0
  97. data/lib/adhearsion/voip/dsl/dialplan/parser.rb +69 -0
  98. data/lib/adhearsion/voip/dsl/dialplan/thread_mixin.rb +16 -0
  99. data/lib/adhearsion/voip/dsl/numerical_string.rb +128 -0
  100. data/lib/adhearsion/voip/freeswitch/basic_connection_manager.rb +48 -0
  101. data/lib/adhearsion/voip/freeswitch/event_handler.rb +58 -0
  102. data/lib/adhearsion/voip/freeswitch/freeswitch_dialplan_command_factory.rb +129 -0
  103. data/lib/adhearsion/voip/freeswitch/inbound_connection_manager.rb +38 -0
  104. data/lib/adhearsion/voip/freeswitch/oes_server.rb +195 -0
  105. data/lib/adhearsion/voip/menu_state_machine/calculated_match.rb +80 -0
  106. data/lib/adhearsion/voip/menu_state_machine/matchers.rb +123 -0
  107. data/lib/adhearsion/voip/menu_state_machine/menu_builder.rb +57 -0
  108. data/lib/adhearsion/voip/menu_state_machine/menu_class.rb +149 -0
  109. data/lib/adhearsion/xmpp/connection.rb +61 -0
  110. data/lib/adhearsion.rb +46 -0
  111. data/lib/theatre/README.markdown +64 -0
  112. data/lib/theatre/callback_definition_loader.rb +84 -0
  113. data/lib/theatre/guid.rb +23 -0
  114. data/lib/theatre/invocation.rb +121 -0
  115. data/lib/theatre/namespace_manager.rb +153 -0
  116. data/lib/theatre/version.rb +2 -0
  117. data/lib/theatre.rb +151 -0
  118. metadata +323 -0
@@ -0,0 +1,1581 @@
1
+
2
+ require 'adhearsion/voip/menu_state_machine/menu_class'
3
+
4
+ module Adhearsion
5
+ module VoIP
6
+ module Asterisk
7
+ module Commands
8
+
9
+ RESPONSE_PREFIX = "200 result=" unless defined? RESPONSE_PREFIX
10
+
11
+ # These are the status messages that asterisk will issue after a dial command is executed.
12
+ #
13
+ # Here is a current list of dial status messages which are not all necessarily supported by adhearsion:
14
+ #
15
+ # ANSWER: Call is answered. A successful dial. The caller reached the callee.
16
+ # BUSY: Busy signal. The dial command reached its number but the number is busy.
17
+ # NOANSWER: No answer. The dial command reached its number, the number rang for too long, then the dial timed out.
18
+ # CANCEL: Call is cancelled. The dial command reached its number but the caller hung up before the callee picked up.
19
+ # CONGESTION: Congestion. This status is usually a sign that the dialled number is not recognised.
20
+ # CHANUNAVAIL: Channel unavailable. On SIP, peer may not be registered.
21
+ # DONTCALL: Privacy mode, callee rejected the call
22
+ # TORTURE: Privacy mode, callee chose to send caller to torture menu
23
+ # INVALIDARGS: Error parsing Dial command arguments (added for Asterisk 1.4.1, SVN r53135-53136)
24
+ #
25
+ # @see http://www.voip-info.org/wiki/index.php?page=Asterisk+variable+DIALSTATUS Asterisk Variable DIALSTATUS
26
+ DIAL_STATUSES = Hash.new(:unknown).merge(:answer => :answered, #:doc:
27
+ :congestion => :congested,
28
+ :busy => :busy,
29
+ :cancel => :cancelled,
30
+ :noanswer => :unanswered,
31
+ :cancelled => :cancelled,
32
+ :chanunavail => :channel_unavailable) unless defined? DIAL_STATUSES
33
+
34
+ DYNAMIC_FEATURE_EXTENSIONS = {
35
+ :attended_transfer => lambda do |options|
36
+ variable "TRANSFER_CONTEXT" => options[:context] if options && options.has_key?(:context)
37
+ extend_dynamic_features_with "atxfer"
38
+ end,
39
+ :blind_transfer => lambda do |options|
40
+ variable "TRANSFER_CONTEXT" => options[:context] if options && options.has_key?(:context)
41
+ extend_dynamic_features_with 'blindxfer'
42
+ end
43
+ } unless defined? DYNAMIC_FEATURE_EXTENSIONS
44
+
45
+ # Utility method to write to pbx.
46
+ # @param [String] message raw message
47
+ def write(message)
48
+ to_pbx.print(message + "\n")
49
+ end
50
+
51
+ # Utility method to read from pbx. Hangup if nil.
52
+ def read
53
+ from_pbx.gets.tap do |message|
54
+ # AGI has many conditions that might indicate a hangup
55
+ raise Hangup if message.nil?
56
+
57
+ ahn_log.agi.debug "<<< #{message}"
58
+
59
+ code, rest = *message.split(' ', 2)
60
+
61
+ case code.to_i
62
+ when 510
63
+ # This error is non-fatal for the call
64
+ ahn_log.agi.warn "510: Invalid or unknown AGI command"
65
+ when 511
66
+ # 511 Command Not Permitted on a dead channel
67
+ ahn_log.agi.debug "511: Dead channel. Raising Hangup"
68
+ raise Hangup
69
+ when 520
70
+ # This error is non-fatal for the call
71
+ ahn_log.agi.warn "520: Invalid command syntax"
72
+ when (500..599)
73
+ # Assume this error is non-fatal for the call and try to keep running
74
+ ahn_log.agi.warn "#{code}: Unknown AGI protocol error."
75
+ end
76
+
77
+ # If the message starts with HANGUP it's a silly 1.6 OOB message
78
+ case message
79
+ when /^HANGUP/, /^HANGUP\n?$/i, /^HANGUP\s?\d{3}/i
80
+ ahn_log.agi.debug "AGI HANGUP. Raising hangup"
81
+ raise Hangup
82
+ end
83
+ end
84
+ end
85
+
86
+ # The underlying method executed by nearly all the command methods in this module.
87
+ # Used to send the plaintext commands in the proper AGI format over TCP/IP back to an Asterisk server via the
88
+ # FAGI protocol.
89
+ #
90
+ # It is not recommended that you call this method directly unless you plan to write a new command method
91
+ # in which case use this to communicate directly with an Asterisk server via the FAGI protocol.
92
+ #
93
+ # @param [String] message
94
+ #
95
+ # @see http://www.voip-info.org/wiki/view/Asterisk+FastAGI More information about FAGI
96
+ def raw_response(message = nil)
97
+ raise ArgumentError.new("illegal NUL in message #{message.inspect}") if message =~ /\0/
98
+ ahn_log.agi.debug ">>> #{message}"
99
+ write message if message
100
+ read
101
+ end
102
+
103
+ def response(command, *arguments)
104
+ # Arguments surrounded by quotes; quotes backslash-escaped.
105
+ # See parse_args in asterisk/res/res_agi.c (Asterisk 1.4.21.1)
106
+ quote_arg = lambda { |arg|
107
+ '"' + arg.gsub(/["\\]/) { |m| "\\#{m}" } + '"'
108
+ }
109
+ if arguments.empty?
110
+ raw_response("#{command}")
111
+ else
112
+ raw_response("#{command} " + arguments.map{ |arg| quote_arg.call(arg.to_s) }.join(' '))
113
+ end
114
+ end
115
+
116
+ # This must be called first before any other commands can be issued.
117
+ # In typical Adhearsion applications this is called by default as soon as a call is
118
+ # transfered to a valid context in dialplan.rb.
119
+ # If you do not want your Adhearsion application to automatically issue an answer command,
120
+ # then you must edit your startup.rb file and configure this setting.
121
+ # Keep in mind that you should not need to issue another answer command after one has already
122
+ # been issued either explicitly by your code or implicitly by the standard adhearsion configuration.
123
+ def answer
124
+ response "ANSWER"
125
+ true
126
+ end
127
+
128
+ # This asterisk dialplan command allows you to instruct Asterisk to start applications
129
+ # which are typically run from extensions.conf.
130
+ #
131
+ # The most common commands are already made available through the FAGI interface provided
132
+ # by this code base. For commands that do not fall into this category, then exec is what you
133
+ # should use.
134
+ #
135
+ # For example, if there are specific asterisk modules you have loaded that will not be
136
+ # available through the standard commands provided through FAGI - then you can used EXEC.
137
+ #
138
+ # @example Using execute in this way will add a header to an existing SIP call.
139
+ # execute 'SIPAddHeader', '"Call-Info: answer-after=0"
140
+ #
141
+ # @see http://www.voip-info.org/wiki/view/Asterisk+-+documentation+of+application+commands Asterisk Dialplan Commands
142
+ def execute(application, *arguments)
143
+ result = raw_response(%{EXEC %s "%s"} % [ application,
144
+ arguments.join(%{"#{AHN_CONFIG.asterisk.argument_delimiter}"}) ])
145
+ return false if error?(result)
146
+ result
147
+ end
148
+
149
+ # Sends a message to the console via the verbose message system.
150
+ #
151
+ # @param [String] message
152
+ # @param [Integer] level
153
+ #
154
+ # @return the result of the command
155
+ #
156
+ # @example Use this command to inform someone watching the Asterisk console
157
+ # of actions happening within Adhearsion.
158
+ # verbose 'Processing call with Adhearsion' 3
159
+ #
160
+ # @see http://www.voip-info.org/wiki/view/verbose
161
+ def verbose(message, level = nil)
162
+ result = raw_response("VERBOSE \"#{message}\" #{level}")
163
+ return false if error?(result)
164
+ result
165
+ end
166
+
167
+ # Hangs up the current channel. After this command is issued, you will not be able to send any more AGI
168
+ # commands but the dialplan Thread will still continue, allowing you to do any post-call work.
169
+ #
170
+ def hangup
171
+ response 'HANGUP'
172
+ end
173
+
174
+ # Plays the specified sound file names. This method will handle Time/DateTime objects (e.g. Time.now),
175
+ # Fixnums (e.g. 1000), Strings which are valid Fixnums (e.g "123"), and direct sound files. When playing
176
+ # numbers, Adhearsion assumes you're saying the number, not the digits. For example, play("100")
177
+ # is pronounced as "one hundred" instead of "one zero zero". To specify how the Date/Time objects are said
178
+ # pass in as an array with the first parameter as the Date/Time/DateTime object along with a hash with the
179
+ # additional options. See play_time for more information.
180
+ #
181
+ # Note: it is not necessary to supply a sound file extension; Asterisk will try to find a sound
182
+ # file encoded using the current channel's codec, if one exists. If not, it will transcode from
183
+ # the default codec (GSM). Asterisk stores its sound files in /var/lib/asterisk/sounds.
184
+ #
185
+ # @example Play file hello-world.???
186
+ # play 'hello-world'
187
+ # @example Speak current time
188
+ # play Time.now
189
+ # @example Speak today's date
190
+ # play Date.today
191
+ # @example Speak today's date in a specific format
192
+ # play [Date.today, {:format => 'BdY'}]
193
+ # @example Play sound file, speak number, play two more sound files
194
+ # play %w"a-connect-charge-of 22 cents-per-minute will-apply"
195
+ # @example Play two sound files
196
+ # play "you-sound-cute", "what-are-you-wearing"
197
+ #
198
+ def play(*arguments)
199
+ arguments.each do |argument|
200
+ play_time(argument) || play_numeric(argument) || play_string(argument)
201
+ end
202
+ end
203
+
204
+ # Records a sound file with the given name. If no filename is specified a file named by Asterisk
205
+ # will be created and returned. Else the given filename will be returned. If a relative path is
206
+ # given, the file will be saved in the default Asterisk sound directory, /var/lib/spool/asterisk
207
+ # by default.
208
+ #
209
+ # Silence and maxduration is specified in seconds.
210
+ #
211
+ # @example Asterisk generated filename
212
+ # filename = record
213
+ # @example Specified filename
214
+ # record '/path/to/my-file.gsm'
215
+ # @example All options specified
216
+ # record 'my-file.gsm', :silence => 5, :maxduration => 120
217
+ #
218
+ def record(*args)
219
+ options = args.last.kind_of?(Hash) ? args.pop : {}
220
+ filename = args.shift || "/tmp/recording_%d"
221
+
222
+ if filename.index("%d")
223
+ if @call.variables.has_key?(:recording_counter)
224
+ @call.variables[:recording_counter] += 1
225
+ else
226
+ @call.variables[:recording_counter] = 0
227
+ end
228
+ filename = filename % @call.variables[:recording_counter]
229
+ end
230
+
231
+ if (!options.has_key?(:format))
232
+ format = filename.slice!(/\.[^\.]+$/)
233
+ if (format.nil?)
234
+ ahn_log.agi.warn "Format not specified and not detected. Defaulting to \"gsm\""
235
+ format = "gsm"
236
+ end
237
+ format.sub!(/^\./, "")
238
+ else
239
+ format = options.delete(:format)
240
+ end
241
+
242
+ # maxduration must be in milliseconds when using RECORD FILE
243
+ maxduration = options.delete(:maxduration) || -1
244
+ maxduration = maxduration * 1000 if maxduration > 0
245
+
246
+ escapedigits = options.delete(:escapedigits) || "#"
247
+ silence = options.delete(:silence) || 0
248
+
249
+ if (silence > 0)
250
+ response("RECORD FILE", filename, format, escapedigits, maxduration, 0, "BEEP", "s=#{silence}")
251
+ else
252
+ response("RECORD FILE", filename, format, escapedigits, maxduration, 0, "BEEP")
253
+ end
254
+
255
+ # If the user hangs up before the recording is entered, -1 is returned and RECORDED_FILE
256
+ # will not contain the name of the file, even though it IS in fact recorded.
257
+ filename + "." + format
258
+ end
259
+
260
+ # Simulates pressing the specified digits over the current channel. Can be used to
261
+ # traverse a phone menu.
262
+ def dtmf(digits)
263
+ execute "SendDTMF", digits.to_s
264
+ end
265
+
266
+ # The with_next_message method...
267
+ def with_next_message(&block)
268
+ raise LocalJumpError, "Must supply a block" unless block_given?
269
+ block.call(next_message)
270
+ end
271
+
272
+ # This command should be used to advance to the next message in the Asterisk Comedian Voicemail application
273
+ def next_message
274
+ @call.inbox.pop
275
+ end
276
+
277
+ # This command should be used to check if a message is waiting on the Asterisk Comedian Voicemail application.
278
+ def messages_waiting?
279
+ not @call.inbox.empty?
280
+ end
281
+
282
+ # Creates an interactive menu for the caller.
283
+ #
284
+ # The following documentation was derived from a post on Jay Phillips' blog (see below).
285
+ #
286
+ # The menu() command solves the problem of building enormous input-fetching state machines in Ruby without first-class
287
+ # message passing facilities or an external DSL.
288
+ #
289
+ # Here is an example dialplan which uses the menu() command effectively.
290
+ #
291
+ # from_pstn {
292
+ # menu 'welcome', 'for-spanish-press-8', 'main-ivr',
293
+ # :timeout => 8.seconds, :tries => 3 do |link|
294
+ # link.shipment_status 1
295
+ # link.ordering 2
296
+ # link.representative 4
297
+ # link.spanish 8
298
+ # link.employee 900..999
299
+ #
300
+ # link.on_invalid { play 'invalid' }
301
+ #
302
+ # link.on_premature_timeout do |str|
303
+ # play 'sorry'
304
+ # end
305
+ #
306
+ # link.on_failure do
307
+ # play 'goodbye'
308
+ # hangup
309
+ # end
310
+ # end
311
+ # }
312
+ #
313
+ # shipment_status {
314
+ # # Fetch a tracking number and pass it to a web service.
315
+ # }
316
+ #
317
+ # ordering {
318
+ # # Enter another menu that lets them enter credit card
319
+ # # information and place their order over the phone.
320
+ # }
321
+ #
322
+ # representative {
323
+ # # Place the caller into a queue
324
+ # }
325
+ #
326
+ # spanish {
327
+ # # Special options for the spanish menu.
328
+ # }
329
+ #
330
+ # employee {
331
+ # dial "SIP/#{extension}" # Overly simplistic
332
+ # }
333
+ #
334
+ # The main detail to note is the declarations within the menu() command’s block. Each line seems to refer to a link object
335
+ # executing a seemingly arbitrary method with an argument that’s either a number or a Range of numbers. The +link+ object
336
+ # collects these arbitrary method invocations and assembles a set of rules. The seemingly arbitrary method name is the name
337
+ # of the context to which the menu should jump in case its argument (the pattern) is found to be a match.
338
+ #
339
+ # With these context names and patterns defined, the +menu()+ command plays in sequence the sound files you supply as
340
+ # arguments, stopping playback abruptly if the user enters a digit. If no digits were pressed when the files finish playing,
341
+ # it waits +:timeout+ seconds. If no digits are pressed after the timeout, it executes the +on_premature_timeout+ hook you
342
+ # define (if any) and then tries again a maximum of +:tries+ times. If digits are pressed that result in no possible match,
343
+ # it executes the +on_invalid+ hook. When/if all tries are exhausted with no positive match, it executes the +on_failure+
344
+ # hook after the other hook (e.g. +on_invalid+, then +on_failure+).
345
+ #
346
+ # When the +menu()+ state machine runs through the defined rules, it must distinguish between exact and potential matches.
347
+ # It's important to understand the differences between these and how they affect the overall outcome:
348
+ #
349
+ # |---------------|-------------------|------------------------------------------------------|
350
+ # | exact matches | potential matches | result |
351
+ # |---------------|-------------------|------------------------------------------------------|
352
+ # | 0 | 0 | Fail and start over |
353
+ # | 1 | 0 | Match found! |
354
+ # | 0 | >0 | Get another digit |
355
+ # | >1 | 0 | Go with the first exact match |
356
+ # | 1 | >0 | Get another digit. If timeout, use exact match |
357
+ # | >1 | >0 | Get another digit. If timeout, use first exact match |
358
+ # |---------------|-------------------|------------------------------------------------------|
359
+ #
360
+ # == Database integration
361
+ #
362
+ # To do database integration, I recommend programatically executing methods on the link object within the block. For example:
363
+ #
364
+ # menu do |link|
365
+ # for employee in Employee.find(:all)
366
+ # link.internal employee.extension
367
+ # end
368
+ # end
369
+ #
370
+ # or this more efficient and Rubyish way
371
+ #
372
+ # menu do |link|
373
+ # link.internal *Employee.find(:all).map(&:extension)
374
+ # end
375
+ #
376
+ # If this second example seems like too much Ruby magic, let me explain — +Employee.find(:all)+ effectively does a “SELECT *
377
+ # FROM employees” on the database with ActiveRecord, returning (what you’d think is) an Array. The +map(&:extension)+ is
378
+ # fanciness that means “replace every instance in this Array with the result of calling extension on that object”. Now we
379
+ # have an Array of every extension in the database. The splat operator (*) before the argument changes the argument from
380
+ # being one argument (an Array) into a sequence of n arguments, where n is the number of items in the Array it’s “splatting”.
381
+ # Lastly, these arguments are passed to the internal method, the name of a context which will handle dialing this user if one
382
+ # of the supplied patterns matches.
383
+ #
384
+ # == Handling a successful pattern match
385
+ #
386
+ # Which brings me to another important note. Let’s say that the user’s input successfully matched one of the patterns
387
+ # returned by that Employe.find... magic. When it jumps to the internal context, that context can access the variable entered
388
+ # through the extension variable. This was a tricky design decision that I think, overall, works great. It makes the +menu()+
389
+ # command feel much more first-class in the Adhearsion dialplan grammar and decouples the receiving context from the menu
390
+ # that caused the jump. After all, the context doesn’t necessary need to be the endpoint from a menu; it can be its own entry
391
+ # point, making menu() effectively a pipeline of re-creating the call.
392
+ #
393
+ # @see http://jicksta.com/articles/2008/02/11/menu-command Original Blog Post
394
+ def menu(*args, &block)
395
+ options = args.last.kind_of?(Hash) ? args.pop : {}
396
+ sound_files = args.flatten
397
+
398
+ menu_instance = Menu.new(options, &block)
399
+
400
+ initial_digit_prompt = sound_files.any?
401
+
402
+ # This method is basically one big begin/rescue block. When we start the Menu state machine by continue()ing, the state
403
+ # machine will pass messages back to this method in the form of Exceptions. This decoupling allows the menu system to
404
+ # work on, say, Freeswitch and Asterisk both.
405
+ begin
406
+ if menu_instance.should_continue?
407
+ menu_instance.continue
408
+ else
409
+ menu_instance.execute_failure_hook
410
+ return :failed
411
+ end
412
+ rescue Menu::MenuResult => result_of_menu
413
+ case result_of_menu
414
+ when Menu::MenuResultInvalid
415
+ menu_instance.execute_invalid_hook
416
+ menu_instance.restart!
417
+ when Menu::MenuGetAnotherDigit
418
+
419
+ next_digit = play_sound_files_for_menu(menu_instance, sound_files)
420
+ if next_digit
421
+ menu_instance << next_digit
422
+ else
423
+ # The user timed out entering another digit!
424
+ case result_of_menu
425
+ when Menu::MenuGetAnotherDigitOrFinish
426
+ # This raises a ControlPassingException
427
+ jump_to result_of_menu.match_payload, :extension => result_of_menu.new_extension
428
+ when Menu::MenuGetAnotherDigitOrTimeout
429
+ # This should execute premature_timeout AND reset if the number of retries
430
+ # has not been exhausted.
431
+ menu_instance.execute_timeout_hook
432
+ menu_instance.restart!
433
+ end
434
+ end
435
+ when Menu::MenuResultFound
436
+ jump_to result_of_menu.match_payload, :extension => result_of_menu.new_extension
437
+ else
438
+ raise "Unrecognized MenuResult! This may be a bug!"
439
+ end
440
+
441
+ # Retry will re-execute the begin block, preserving our changes to the menu_instance object.
442
+ retry
443
+
444
+ end
445
+ end
446
+
447
+ # Used to receive keypad input from the user. Digits are collected
448
+ # via DTMF (keypad) input until one of three things happens:
449
+ #
450
+ # 1. The number of digits you specify as the first argument is collected
451
+ # 2. The timeout you specify with the :timeout option elapses.
452
+ # 3. The "#" key (or the key you specify with :accept_key) is pressed
453
+ #
454
+ # Usage examples
455
+ #
456
+ # input # Receives digits until the caller presses the "#" key
457
+ # input 3 # Receives three digits. Can be 0-9, * or #
458
+ # input 5, :accept_key => "*" # Receive at most 5 digits, stopping if '*' is pressed
459
+ # input 1, :timeout => 1.minute # Receive a single digit, returning an empty
460
+ # string if the timeout is encountered
461
+ # input 9, :timeout => 7, :accept_key => "0" # Receives nine digits, returning
462
+ # # when the timeout is encountered
463
+ # # or when the "0" key is pressed.
464
+ # input 3, :play => "you-sound-cute"
465
+ # input :play => ["if-this-is-correct-press", 1, "otherwise-press", 2]
466
+ #
467
+ # When specifying files to play, the playback of the sequence of files will stop
468
+ # immediately when the user presses the first digit.
469
+ #
470
+ # The :timeout option works like a digit timeout, therefore each digit pressed
471
+ # causes the timer to reset. This is a much more user-friendly approach than an
472
+ # absolute timeout.
473
+ #
474
+ # Note that when the digit limit is not specified the :accept_key becomes "#".
475
+ # Otherwise there would be no way to end the collection of digits. You can
476
+ # obviously override this by passing in a new key with :accept_key.
477
+ def input(*args)
478
+ options = args.last.kind_of?(Hash) ? args.pop : {}
479
+ number_of_digits = args.shift
480
+
481
+ sound_files = Array options.delete(:play)
482
+ timeout = options.delete(:timeout)
483
+ terminating_key = options.delete(:accept_key)
484
+ terminating_key = if terminating_key
485
+ terminating_key.to_s
486
+ elsif number_of_digits.nil? && !terminating_key.equal?(false)
487
+ '#'
488
+ end
489
+
490
+ if number_of_digits && number_of_digits < 0
491
+ ahn_log.agi.warn "Giving -1 to input() is now deprecated. Don't specify a first " +
492
+ "argument to simulate unlimited digits." if number_of_digits == -1
493
+ raise ArgumentError, "The number of digits must be positive!"
494
+ end
495
+
496
+ buffer = ''
497
+ key = sound_files.any? ? interruptible_play(*sound_files) || '' : wait_for_digit(timeout || -1)
498
+ loop do
499
+ return buffer if key.nil?
500
+ if terminating_key
501
+ if key == terminating_key
502
+ return buffer
503
+ else
504
+ buffer << key
505
+ return buffer if number_of_digits && number_of_digits == buffer.length
506
+ end
507
+ else
508
+ buffer << key
509
+ return buffer if number_of_digits && number_of_digits == buffer.length
510
+ end
511
+ key = wait_for_digit(timeout || -1)
512
+ end
513
+ end
514
+
515
+ # Jumps to a context. An alternative to DialplanContextProc#+@. When jumping to a context, it will *not* resume executing
516
+ # the former context when the jumped-to context has finished executing. Make sure you don't have any
517
+ # +ensure+ closures which you expect to execute when the call has finished, as they will run when
518
+ # this method is called.
519
+ #
520
+ # You can optionally override certain dialplan variables when jumping to the context. A popular use of
521
+ # this is to redefine +extension+ (which this method automatically boxes with a PhoneNumber object) so
522
+ # you can effectively "restart" a call (from the perspective of the jumped-to context). When you override
523
+ # variables here, you're effectively blowing away the old variables. If you need them for some reason,
524
+ # you should assign the important ones to an instance variable first before calling this method.
525
+ def jump_to(context, overrides={})
526
+ context = lookup_context_with_name(context) if context.kind_of?(Symbol) || (context.kind_of?(String) && context =~ /^[\w_]+$/)
527
+
528
+ # JRuby has a bug that prevents us from correctly determining the class name.
529
+ # See: http://jira.codehaus.org/browse/JRUBY-5026
530
+ if !(context.kind_of?(Adhearsion::DialPlan::DialplanContextProc) || context.kind_of?(Proc))
531
+ raise Adhearsion::VoIP::DSL::Dialplan::ContextNotFoundException
532
+ end
533
+
534
+ if overrides.any?
535
+ overrides = overrides.symbolize_keys
536
+ if overrides.has_key?(:extension) && !overrides[:extension].kind_of?(Adhearsion::VoIP::DSL::PhoneNumber)
537
+ overrides[:extension] = Adhearsion::VoIP::DSL::PhoneNumber.new overrides[:extension]
538
+ end
539
+
540
+ overrides.each_pair do |key, value|
541
+ meta_def(key) { value }
542
+ end
543
+ end
544
+
545
+ raise Adhearsion::VoIP::DSL::Dialplan::ControlPassingException.new(context)
546
+ end
547
+
548
+ # Place a call in a queue to be answered by a registered agent. You must then call join!()
549
+ #
550
+ # @param [String] queue_name the queue name to place the caller in
551
+ # @return [Adhearsion::VoIP::Asterisk::Commands::QueueProxy] a queue proxy object
552
+ #
553
+ # @see http://www.voip-info.org/wiki-Asterisk+cmd+Queue Full information on the Asterisk Queue
554
+ # @see Adhearsion::VoIP::Asterisk::Commands::QueueProxy#join! join!() for further details
555
+ def queue(queue_name)
556
+ queue_name = queue_name.to_s
557
+
558
+ @queue_proxy_hash_lock = Mutex.new unless defined? @queue_proxy_hash_lock
559
+ @queue_proxy_hash_lock.synchronize do
560
+ @queue_proxy_hash ||= {}
561
+ if @queue_proxy_hash.has_key? queue_name
562
+ return @queue_proxy_hash[queue_name]
563
+ else
564
+ proxy = @queue_proxy_hash[queue_name] = QueueProxy.new(queue_name, self)
565
+ return proxy
566
+ end
567
+ end
568
+ end
569
+
570
+ # Get the status of the last dial(). Possible dial statuses include :answer,
571
+ # :busy, :no_answer, :cancelled, :congested, and :channel_unavailable.
572
+ # If :cancel is returned, the caller hung up before the callee picked up.
573
+ # If :congestion is returned, the dialed extension probably doesn't exist.
574
+ # If :channel_unavailable, the callee phone may not be registered.
575
+ def last_dial_status
576
+ DIAL_STATUSES[get_dial_status]
577
+ end
578
+
579
+ # @return [Boolean] true if your last call to dial() finished with the ANSWER state,
580
+ # as reported by Asterisk. false otherwise
581
+ def last_dial_successful?
582
+ last_dial_status == :answered
583
+ end
584
+
585
+ # Opposite of last_dial_successful?()
586
+ def last_dial_unsuccessful?
587
+ not last_dial_successful?
588
+ end
589
+
590
+ # This feature is presently experimental! Do not use it!
591
+ def speak(text, engine=:none)
592
+ engine = AHN_CONFIG.asterisk.speech_engine || engine
593
+ execute SpeechEngines.send(engine, text)
594
+ end
595
+
596
+ # A high-level way of enabling features you create/uncomment from features.conf.
597
+ #
598
+ # Certain Symbol features you enable (as defined in DYNAMIC_FEATURE_EXTENSIONS) have optional
599
+ # arguments that you can also specify here. The usage examples show how to do this.
600
+ #
601
+ # Usage examples:
602
+ #
603
+ # enable_feature :attended_transfer # Enables "atxfer"
604
+ #
605
+ # enable_feature :attended_transfer, :context => "my_dial" # Enables "atxfer" and then
606
+ # # sets "TRANSFER_CONTEXT" to :context's value
607
+ #
608
+ # enable_feature :blind_transfer, :context => 'my_dial' # Enables 'blindxfer' and sets TRANSFER_CONTEXT
609
+ #
610
+ # enable_feature "foobar" # Enables "foobar"
611
+ #
612
+ # enable_feature("dup"); enable_feature("dup") # Enables "dup" only once.
613
+ def enable_feature(feature_name, optional_options=nil)
614
+ if DYNAMIC_FEATURE_EXTENSIONS.has_key? feature_name
615
+ instance_exec(optional_options, &DYNAMIC_FEATURE_EXTENSIONS[feature_name])
616
+ else
617
+ raise ArgumentError, "You cannot supply optional options when the feature name is " +
618
+ "not internally recognized!" if optional_options
619
+ extend_dynamic_features_with feature_name
620
+ end
621
+ end
622
+
623
+ # Disables a feature name specified in features.conf. If you're disabling it, it was probably
624
+ # set by enable_feature().
625
+ #
626
+ # @param [String] feature_name
627
+ def disable_feature(feature_name)
628
+ enabled_features_variable = variable 'DYNAMIC_FEATURES'
629
+ enabled_features = enabled_features_variable.split('#')
630
+ if enabled_features.include? feature_name
631
+ enabled_features.delete feature_name
632
+ variable 'DYNAMIC_FEATURES' => enabled_features.join('#')
633
+ end
634
+ end
635
+
636
+ # Used to join a particular conference with the MeetMe application. To use MeetMe, be sure you
637
+ # have a proper timing device configured on your Asterisk box. MeetMe is Asterisk's built-in
638
+ # conferencing program.
639
+ #
640
+ # @param [String] conference_id
641
+ # @param [Hash] options
642
+ #
643
+ # @see http://www.voip-info.org/wiki-Asterisk+cmd+MeetMe Asterisk Meetme Application Information
644
+ def join(conference_id, options={})
645
+ conference_id = conference_id.to_s.scan(/\w/).join
646
+ command_flags = options[:options].to_s # This is a passthrough string straight to Asterisk
647
+ pin = options[:pin]
648
+ raise ArgumentError, "A conference PIN number must be numerical!" if pin && pin.to_s !~ /^\d+$/
649
+
650
+ # To disable dynamic conference creation set :use_static_conf => true
651
+ use_static_conf = options.has_key?(:use_static_conf) ? options[:use_static_conf] : false
652
+
653
+ # The 'd' option of MeetMe creates conferences dynamically.
654
+ command_flags += 'd' unless (command_flags.include?('d') or use_static_conf)
655
+
656
+ execute "MeetMe", conference_id, command_flags, options[:pin]
657
+ end
658
+
659
+ # Issue this command to access a channel variable that exists in the asterisk dialplan (i.e. extensions.conf)
660
+ # Use get_variable to pass information from other modules or high level configurations from the asterisk dialplan
661
+ # to the adhearsion dialplan.
662
+ #
663
+ # @param [String] variable_name
664
+ #
665
+ # @see: http://www.voip-info.org/wiki/view/get+variable Asterisk Get Variable
666
+ def get_variable(variable_name)
667
+ result = response("GET VARIABLE", variable_name)
668
+ case result
669
+ when "200 result=0"
670
+ return nil
671
+ when /^200 result=1 \((.*)\)$/
672
+ return $LAST_PAREN_MATCH
673
+ end
674
+ end
675
+
676
+ # Pass information back to the asterisk dial plan.
677
+ #
678
+ # Keep in mind that the variables are not global variables. These variables only exist for the channel
679
+ # related to the call that is being serviced by the particular instance of your adhearsion application.
680
+ # You will not be able to pass information back to the asterisk dialplan for other instances of your adhearsion
681
+ # application to share. Once the channel is "hungup" then the variables are cleared and their information is gone.
682
+ #
683
+ # @param [String] variable_name
684
+ # @param [String] value
685
+ #
686
+ # @see http://www.voip-info.org/wiki/view/set+variable Asterisk Set Variable
687
+ def set_variable(variable_name, value)
688
+ response("SET VARIABLE", variable_name, value) == "200 result=1"
689
+ end
690
+
691
+ # Issue the command to add a custom SIP header to the current call channel
692
+ # example use: sip_add_header("x-ahn-test", "rubyrox")
693
+ #
694
+ # @param[String] the name of the SIP header
695
+ # @param[String] the value of the SIP header
696
+ #
697
+ # @return [String] the Asterisk response
698
+ #
699
+ # @see http://www.voip-info.org/wiki/index.php?page=Asterisk+cmd+SIPAddHeader Asterisk SIPAddHeader
700
+ def sip_add_header(header, value)
701
+ execute("SIPAddHeader", "#{header}: #{value}") == "200 result=1"
702
+ end
703
+
704
+ # Issue the command to fetch a SIP header from the current call channel
705
+ # example use: sip_get_header("x-ahn-test")
706
+ #
707
+ # @param[String] the name of the SIP header to get
708
+ #
709
+ # @return [String] the Asterisk response
710
+ #
711
+ # @see http://www.voip-info.org/wiki/index.php?page=Asterisk+cmd+SIPGetHeader Asterisk SIPGetHeader
712
+ def sip_get_header(header)
713
+ get_variable("SIP_HEADER(#{header})")
714
+ end
715
+ alias :sip_header :sip_get_header
716
+
717
+ # Allows you to either set or get a channel variable from Asterisk.
718
+ # The method takes a hash key/value pair if you would like to set a variable
719
+ # Or a single string with the variable to get from Asterisk
720
+ def variable(*args)
721
+ if args.last.kind_of? Hash
722
+ assignments = args.pop
723
+ raise ArgumentError, "Can't mix variable setting and fetching!" if args.any?
724
+ assignments.each_pair do |key, value|
725
+ set_variable(key, value)
726
+ end
727
+ else
728
+ if args.size == 1
729
+ get_variable args.first
730
+ else
731
+ args.map { |var| get_variable(var) }
732
+ end
733
+ end
734
+ end
735
+
736
+ # Send a caller to a voicemail box to leave a message.
737
+ #
738
+ # The method takes the mailbox_number of the user to leave a message for and a
739
+ # greeting_option that will determine which message gets played to the caller.
740
+ #
741
+ # @see http://www.voip-info.org/tiki-index.php?page=Asterisk+cmd+VoiceMail Asterisk Voicemail
742
+ def voicemail(*args)
743
+ options_hash = args.last.kind_of?(Hash) ? args.pop : {}
744
+ mailbox_number = args.shift
745
+ greeting_option = options_hash.delete(:greeting)
746
+ skip_option = options_hash.delete(:skip)
747
+ raise ArgumentError, 'You supplied too many arguments!' if mailbox_number && options_hash.any?
748
+ greeting_option = case greeting_option
749
+ when :busy then 'b'
750
+ when :unavailable then 'u'
751
+ when nil then nil
752
+ else raise ArgumentError, "Unrecognized greeting #{greeting_option}"
753
+ end
754
+ skip_option &&= 's'
755
+ options = "#{greeting_option}#{skip_option}"
756
+
757
+ raise ArgumentError, "Mailbox cannot be blank!" if !mailbox_number.nil? && mailbox_number.blank?
758
+ number_with_context = if mailbox_number then mailbox_number else
759
+ raise ArgumentError, "You must supply ONE context name!" if options_hash.size != 1
760
+ context_name, mailboxes = options_hash.to_a.first
761
+ Array(mailboxes).map do |mailbox|
762
+ raise ArgumentError, "Mailbox numbers must be numerical!" unless mailbox.to_s =~ /^\d+$/
763
+ "#{mailbox}@#{context_name}"
764
+ end.join('&')
765
+ end
766
+ execute('voicemail', number_with_context, options)
767
+ case variable('VMSTATUS')
768
+ when 'SUCCESS' then true
769
+ when 'USEREXIT' then false
770
+ else nil
771
+ end
772
+ end
773
+
774
+ # The voicemail_main method puts a caller into the voicemail system to fetch their voicemail
775
+ # or set options for their voicemail box.
776
+ #
777
+ # @param [Hash] options
778
+ #
779
+ # @see http://www.voip-info.org/wiki-Asterisk+cmd+VoiceMailMain Asterisk VoiceMailMain Command
780
+ def voicemail_main(options={})
781
+ mailbox, context, folder = options.values_at :mailbox, :context, :folder
782
+ authenticate = options.has_key?(:authenticate) ? options[:authenticate] : true
783
+
784
+ folder = if folder
785
+ if folder.to_s =~ /^[\w_]+$/
786
+ "a(#{folder})"
787
+ else
788
+ raise ArgumentError, "Voicemail folder must be alphanumerical/underscore characters only!"
789
+ end
790
+ elsif folder == ''
791
+ raise "Folder name cannot be an empty String!"
792
+ else
793
+ nil
794
+ end
795
+
796
+ real_mailbox = ""
797
+ real_mailbox << "#{mailbox}" unless mailbox.blank?
798
+ real_mailbox << "@#{context}" unless context.blank?
799
+
800
+ real_options = ""
801
+ real_options << "s" if !authenticate
802
+ real_options << folder unless folder.blank?
803
+
804
+ command_args = [real_mailbox]
805
+ command_args << real_options unless real_options.blank?
806
+ command_args.clear if command_args == [""]
807
+
808
+ execute 'VoiceMailMain', *command_args
809
+ end
810
+
811
+ def check_voicemail
812
+ ahn_log.agi.warn "THE check_voicemail() DIALPLAN METHOD WILL SOON BE DEPRECATED! CHANGE THIS TO voicemail_main() INSTEAD"
813
+ voicemail_main
814
+ end
815
+
816
+ # Dial an extension or "phone number" in asterisk.
817
+ # Maps to the Asterisk DIAL command in the asterisk dialplan.
818
+ #
819
+ # @param [String] number represents the extension or "number" that asterisk should dial.
820
+ # Be careful to not just specify a number like 5001, 9095551001
821
+ # You must specify a properly formatted string as Asterisk would expect to use in order to understand
822
+ # whether the call should be dialed using SIP, IAX, or some other means.
823
+ #
824
+ # @param [Hash] options
825
+ #
826
+ # +:caller_id+ - the caller id number to be used when the call is placed. It is advised you properly adhere to the
827
+ # policy of VoIP termination providers with respect to caller id values.
828
+ #
829
+ # +:name+ - this is the name which should be passed with the caller ID information
830
+ # if :name=>"John Doe" and :caller_id => "444-333-1000" then the compelete CID and name would be "John Doe" <4443331000>
831
+ # support for caller id information varies from country to country and from one VoIP termination provider to another.
832
+ #
833
+ # +:for+ - this option can be thought of best as a timeout. i.e. timeout after :for if no one answers the call
834
+ # For example, dial("SIP/jay-desk-650&SIP/jay-desk-601&SIP/jay-desk-601-2", :for => 15.seconds, :caller_id => callerid)
835
+ # this call will timeout after 15 seconds if 1 of the 3 extensions being dialed do not pick prior to the 15 second time limit
836
+ #
837
+ # +:options+ - This is a string of options like "Tr" which are supported by the asterisk DIAL application.
838
+ # for a complete list of these options and their usage please check the link below.
839
+ #
840
+ # +:confirm+ - ?
841
+ #
842
+ # @example Make a call to the PSTN using my SIP provider for VoIP termination
843
+ # dial("SIP/19095551001@my.sip.voip.terminator.us")
844
+ #
845
+ # @example Make 3 Simulataneous calls to the SIP extensions separated by & symbols, try for 15 seconds and use the callerid
846
+ # for this call specified by the variable my_callerid
847
+ # dial "SIP/jay-desk-650&SIP/jay-desk-601&SIP/jay-desk-601-2", :for => 15.seconds, :caller_id => my_callerid
848
+ #
849
+ # @example Make a call using the IAX provider to the PSTN
850
+ # dial("IAX2/my.id@voipjet/19095551234", :name=>"John Doe", :caller_id=>"9095551234")
851
+ #
852
+ # @see http://www.voip-info.org/wiki-Asterisk+cmd+Dial Asterisk Dial Command
853
+ def dial(number, options={})
854
+ *recognized_options = :caller_id, :name, :for, :options, :confirm
855
+
856
+ unrecognized_options = options.keys - recognized_options
857
+ raise ArgumentError, "Unknown dial options: #{unrecognized_options.to_sentence}" if unrecognized_options.any?
858
+ set_caller_id_name options[:name]
859
+ set_caller_id_number options[:caller_id]
860
+ confirm_option = dial_macro_option_compiler options[:confirm]
861
+ all_options = options[:options]
862
+ all_options = all_options ? all_options + confirm_option : confirm_option
863
+ execute "Dial", number, options[:for], all_options
864
+ end
865
+
866
+
867
+ # This implementation of dial() uses the experimental call routing DSL.
868
+ #
869
+ # def dial(number, options={})
870
+ # rules = callable_routes_for number
871
+ # return :no_route if rules.empty?
872
+ # call_attempt_status = nil
873
+ # rules.each do |provider|
874
+ #
875
+ # response = execute "Dial",
876
+ # provider.format_number_for_platform(number),
877
+ # timeout_from_dial_options(options),
878
+ # asterisk_options_from_dial_options(options)
879
+ #
880
+ # call_attempt_status = last_dial_status
881
+ # break if call_attempt_status == :answered
882
+ # end
883
+ # call_attempt_status
884
+ # end
885
+
886
+
887
+ # Speaks the digits given as an argument. For example, "123" is spoken as "one two three".
888
+ #
889
+ # @param [String] digits
890
+ def say_digits(digits)
891
+ execute "saydigits", validate_digits(digits)
892
+ end
893
+
894
+ # Get the number of seconds the given block takes to execute. This
895
+ # is particularly useful in dialplans for tracking billable time. Note that
896
+ # if the call is hung up during the block, you will need to rescue the
897
+ # exception if you have some mission-critical logic after it with which
898
+ # you're recording this return-value.
899
+ #
900
+ # @return [Float] number of seconds taken for block to execute
901
+ def duration_of
902
+ start_time = Time.now
903
+ yield
904
+ Time.now - start_time
905
+ end
906
+
907
+ #
908
+ # Play a sequence of files, stopping the playback if a digit is pressed.
909
+ #
910
+ # @return [String, nil] digit pressed, or nil if none
911
+ #
912
+ def interruptible_play(*files)
913
+ files.flatten.each do |file|
914
+ result = result_digit_from response("STREAM FILE", file, "1234567890*#")
915
+ return result if result != 0.chr
916
+ end
917
+ nil
918
+ end
919
+
920
+ ##
921
+ # Executes the SayPhonetic command. This command will read the text passed in
922
+ # out load using the NATO phonetic alphabet.
923
+ #
924
+ # @param [String] Passed in as the text to read aloud
925
+ #
926
+ # @see http://www.voip-info.org/wiki/view/Asterisk+cmd+SayPhonetic Asterisk SayPhonetic Command
927
+ def say_phonetic(text)
928
+ execute "sayphonetic", text
929
+ end
930
+
931
+ ##
932
+ # Executes the SayAlpha command. This command will read the text passed in
933
+ # out loud, character-by-character.
934
+ #
935
+ # @param [String] Passed in as the text to read aloud
936
+ #
937
+ # @example Say "one a two dot pound"
938
+ # say_chars "1a2.#"
939
+ #
940
+ # @see http://www.voip-info.org/wiki/view/Asterisk+cmd+SayAlpha Asterisk SayPhonetic Command
941
+ def say_chars(text)
942
+ execute "sayalpha", text
943
+ end
944
+
945
+ # Plays the given Date, Time, or Integer (seconds since epoch)
946
+ # using the given timezone and format.
947
+ #
948
+ # @param [Date|Time|DateTime] Time to be said.
949
+ # @param [Hash] Additional options to specify how exactly to say time specified.
950
+ #
951
+ # +:timezone+ - Sends a timezone to asterisk. See /usr/share/zoneinfo for a list. Defaults to the machine timezone.
952
+ # +:format+ - This is the format the time is to be said in. Defaults to "ABdY 'digits/at' IMp"
953
+ #
954
+ # @see http://www.voip-info.org/wiki/view/Asterisk+cmd+SayUnixTime
955
+ def play_time(*args)
956
+ argument, options = args.flatten
957
+ options ||= {}
958
+
959
+ timezone = options.delete(:timezone) || ''
960
+ format = options.delete(:format) || ''
961
+ epoch = case argument.class.to_s
962
+ when 'Time' then argument.to_i
963
+ when 'DateTime' then argument.to_i
964
+ when 'Date'
965
+ format = 'BdY' unless format.present?
966
+ argument.to_time.to_i
967
+ else
968
+ nil
969
+ end
970
+
971
+ return false if epoch.nil?
972
+
973
+ execute(:sayunixtime, epoch, timezone, format)
974
+ end
975
+
976
+ protected
977
+
978
+ # wait_for_digits waits for the input of digits based on the number of milliseconds
979
+ def wait_for_digit(timeout=-1)
980
+ timeout *= 1_000 if timeout != -1
981
+ result = result_digit_from response("WAIT FOR DIGIT", timeout.to_i)
982
+ (result == 0.chr) ? nil : result
983
+ end
984
+
985
+ ##
986
+ # Deprecated name of interruptible_play(). This is a misspelling!
987
+ #
988
+ def interruptable_play(*files)
989
+ ahn_log.deprecation.warn 'Please change your code to use interruptible_play() instead. "interruptable" is a misspelling! interruptable_play() will work for now but will be deprecated in the future!'
990
+ interruptible_play(*files)
991
+ end
992
+
993
+ # allows setting of the callerid number of the call
994
+ def set_caller_id_number(caller_id_num)
995
+ return unless caller_id_num
996
+ raise ArgumentError, "Caller ID must be numeric" if caller_id_num.to_s !~ /^\d+$/
997
+ variable "CALLERID(num)" => caller_id_num
998
+ end
999
+
1000
+ # allows the setting of the callerid name of the call
1001
+ def set_caller_id_name(caller_id_name)
1002
+ return unless caller_id_name
1003
+ variable "CALLERID(name)" => caller_id_name
1004
+ end
1005
+
1006
+ def timeout_from_dial_options(options)
1007
+ options[:for] || options[:timeout]
1008
+ end
1009
+
1010
+ def asterisk_options_from_dial_options(options)
1011
+ # TODO: Will become much more sophisticated soon to handle callerid, etc
1012
+ options[:options]
1013
+ end
1014
+
1015
+ def dial_macro_option_compiler(confirm_argument_value)
1016
+ defaults = { :macro => 'ahn_dial_confirmer',
1017
+ :timeout => 20.seconds,
1018
+ :play => "beep",
1019
+ :key => '#' }
1020
+
1021
+ case confirm_argument_value
1022
+ when true
1023
+ DialPlan::ConfirmationManager.encode_hash_for_dial_macro_argument(defaults)
1024
+ when false, nil
1025
+ ''
1026
+ when Proc
1027
+ raise NotImplementedError, "Coming in the future, you can do :confirm => my_context."
1028
+
1029
+ when Hash
1030
+ options = defaults.merge confirm_argument_value
1031
+ if((confirm_argument_value.keys - defaults.keys).any?)
1032
+ raise ArgumentError, "Known options: #{defaults.keys.to_sentence}"
1033
+ end
1034
+ raise ArgumentError, "Bad macro name!" unless options[:macro].to_s =~ /^[\w_]+$/
1035
+ options[:timeout] = case options[:timeout]
1036
+ when Fixnum, ActiveSupport::Duration
1037
+ options[:timeout]
1038
+ when String
1039
+ raise ArgumentError, "Timeout must be numerical!" unless options[:timeout] =~ /^\d+$/
1040
+ options[:timeout].to_i
1041
+ when :none
1042
+ 0
1043
+ else
1044
+ raise ArgumentError, "Unrecognized :timeout! #{options[:timeout].inspect}"
1045
+ end
1046
+ raise ArgumentError, "Unrecognized DTMF key: #{options[:key]}" unless options[:key].to_s =~ /^[\d#*]$/
1047
+ options[:play] = Array(options[:play]).join('++')
1048
+ DialPlan::ConfirmationManager.encode_hash_for_dial_macro_argument options
1049
+
1050
+ else
1051
+ raise ArgumentError, "Unrecognized :confirm option: #{confirm_argument_value.inspect}!"
1052
+ end
1053
+ end
1054
+
1055
+ def result_digit_from(response_string)
1056
+ raise ArgumentError, "Can't coerce nil into AGI response! This could be a bug!" unless response_string
1057
+ digit = response_string[/^#{response_prefix}(-?\d+(\.\d+)?)/,1]
1058
+ digit.to_i.chr if digit && digit.to_s != "-1"
1059
+ end
1060
+
1061
+ def extract_input_from(result)
1062
+ return false if error?(result)
1063
+ # return false if input_timed_out?(result)
1064
+
1065
+ # This regexp doesn't match if there was a timeout with no
1066
+ # inputted digits, therefore returning nil.
1067
+
1068
+ result[/^#{response_prefix}([\d*]+)/, 1]
1069
+ end
1070
+
1071
+ def extract_variable_from(result)
1072
+ return false if error?(result)
1073
+ result[/^#{response_prefix}1 \((.+)\)/, 1]
1074
+ end
1075
+
1076
+ def get_dial_status
1077
+ dial_status = variable('DIALSTATUS')
1078
+ dial_status ? dial_status.downcase.to_sym : :cancelled
1079
+ end
1080
+
1081
+
1082
+ def play_numeric(argument)
1083
+ if argument.kind_of?(Numeric) || argument =~ /^\d+$/
1084
+ execute(:saynumber, argument)
1085
+ end
1086
+ end
1087
+
1088
+ def play_string(argument)
1089
+ execute(:playback, argument)
1090
+ end
1091
+
1092
+ def play_sound_files_for_menu(menu_instance, sound_files)
1093
+ digit = nil
1094
+ if sound_files.any? && menu_instance.digit_buffer_empty?
1095
+ digit = interruptible_play(*sound_files)
1096
+ end
1097
+ digit || wait_for_digit(menu_instance.timeout)
1098
+ end
1099
+
1100
+ def extend_dynamic_features_with(feature_name)
1101
+ current_variable = variable("DYNAMIC_FEATURES") || ''
1102
+ enabled_features = current_variable.split '#'
1103
+ unless enabled_features.include? feature_name
1104
+ enabled_features << feature_name
1105
+ variable "DYNAMIC_FEATURES" => enabled_features.join('#')
1106
+ end
1107
+ end
1108
+
1109
+ def jump_to_context_with_name(context_name)
1110
+ context_lambda = lookup_context_with_name context_name
1111
+ raise Adhearsion::VoIP::DSL::Dialplan::ControlPassingException.new(context_lambda)
1112
+ end
1113
+
1114
+ def lookup_context_with_name(context_name)
1115
+ begin
1116
+ send context_name
1117
+ rescue NameError
1118
+ raise Adhearsion::VoIP::DSL::Dialplan::ContextNotFoundException
1119
+ end
1120
+ end
1121
+
1122
+ def redefine_extension_to_be(new_extension)
1123
+ new_extension = Adhearsion::VoIP::DSL::PhoneNumber.new new_extension
1124
+ meta_def(:extension) { new_extension }
1125
+ end
1126
+
1127
+ def to_pbx
1128
+ io
1129
+ end
1130
+
1131
+ def from_pbx
1132
+ io
1133
+ end
1134
+
1135
+ def validate_digits(digits)
1136
+ digits.to_s.tap do |digits_as_string|
1137
+ raise ArgumentError, "Can only be called with valid digits!" unless digits_as_string =~ /^[0-9*#-]+$/
1138
+ end
1139
+ end
1140
+
1141
+ def error?(result)
1142
+ result.to_s[/^#{response_prefix}(?:-\d+)/]
1143
+ end
1144
+
1145
+ # timeout with pressed digits: 200 result=<digits> (timeout)
1146
+ # timeout without pressed digits: 200 result= (timeout)
1147
+ # @see http://www.voip-info.org/wiki/view/get+data AGI Get Data
1148
+ def input_timed_out?(result)
1149
+ result.starts_with?(response_prefix) && result.ends_with?('(timeout)')
1150
+ end
1151
+
1152
+ def io
1153
+ call.io
1154
+ end
1155
+
1156
+ def response_prefix
1157
+ RESPONSE_PREFIX
1158
+ end
1159
+
1160
+ class QueueProxy
1161
+
1162
+ class << self
1163
+
1164
+ def format_join_hash_key_arguments(options)
1165
+
1166
+ bad_argument = lambda do |(key, value)|
1167
+ raise ArgumentError, "Unrecognize value for #{key.inspect} -- #{value.inspect}"
1168
+ end
1169
+
1170
+ # Direct Queue() arguments:
1171
+ timeout = options.delete :timeout
1172
+ announcement = options.delete :announce
1173
+
1174
+ # Terse single-character options
1175
+ ring_style = options.delete :play
1176
+ allow_hangup = options.delete :allow_hangup
1177
+ allow_transfer = options.delete :allow_transfer
1178
+ agi = options.delete :agi
1179
+
1180
+ raise ArgumentError, "Unrecognized args to join!: #{options.inspect}" if options.any?
1181
+
1182
+ ring_style = case ring_style
1183
+ when :ringing then 'r'
1184
+ when :music then ''
1185
+ when nil
1186
+ else bad_argument[:play => ring_style]
1187
+ end.to_s
1188
+
1189
+ allow_hangup = case allow_hangup
1190
+ when :caller then 'H'
1191
+ when :agent then 'h'
1192
+ when :everyone then 'Hh'
1193
+ when nil
1194
+ else bad_argument[:allow_hangup => allow_hangup]
1195
+ end.to_s
1196
+
1197
+ allow_transfer = case allow_transfer
1198
+ when :caller then 'T'
1199
+ when :agent then 't'
1200
+ when :everyone then 'Tt'
1201
+ when nil
1202
+ else bad_argument[:allow_transfer => allow_transfer]
1203
+ end.to_s
1204
+
1205
+ terse_character_options = ring_style + allow_transfer + allow_hangup
1206
+
1207
+ [terse_character_options, '', announcement, timeout, agi].map(&:to_s)
1208
+ end
1209
+
1210
+ end
1211
+
1212
+ attr_reader :name, :environment
1213
+ def initialize(name, environment)
1214
+ @name, @environment = name, environment
1215
+ end
1216
+
1217
+ # Makes the current channel join the queue.
1218
+ #
1219
+ # @param [Hash] options
1220
+ #
1221
+ # :timeout - The number of seconds to wait for an agent to answer
1222
+ # :play - Can be :ringing or :music.
1223
+ # :announce - A sound file to play instead of the normal queue announcement.
1224
+ # :allow_transfer - Can be :caller, :agent, or :everyone. Allow someone to transfer the call.
1225
+ # :allow_hangup - Can be :caller, :agent, or :everyone. Allow someone to hangup with the * key.
1226
+ # :agi - An AGI script to be called on the calling parties channel just before being connected.
1227
+ #
1228
+ # @example
1229
+ # queue('sales').join!
1230
+ # @example
1231
+ # queue('sales').join! :timeout => 1.minute
1232
+ # @example
1233
+ # queue('sales').join! :play => :music
1234
+ # @example
1235
+ # queue('sales').join! :play => :ringing
1236
+ # @example
1237
+ # queue('sales').join! :announce => "custom/special-queue-announcement"
1238
+ # @example
1239
+ # queue('sales').join! :allow_transfer => :caller
1240
+ # @example
1241
+ # queue('sales').join! :allow_transfer => :agent
1242
+ # @example
1243
+ # queue('sales').join! :allow_hangup => :caller
1244
+ # @example
1245
+ # queue('sales').join! :allow_hangup => :agent
1246
+ # @example
1247
+ # queue('sales').join! :allow_hangup => :everyone
1248
+ # @example
1249
+ # queue('sales').join! :agi => 'agi://localhost/sales_queue_callback'
1250
+ # @example
1251
+ # queue('sales').join! :allow_transfer => :agent, :timeout => 30.seconds,
1252
+ def join!(options={})
1253
+ environment.execute("queue", name, *self.class.format_join_hash_key_arguments(options))
1254
+ normalize_queue_status_variable environment.variable("QUEUESTATUS")
1255
+ end
1256
+
1257
+ # Get the agents associated with a queue
1258
+ #
1259
+ # @param [Hash] options
1260
+ # @return [QueueAgentsListProxy]
1261
+ def agents(options={})
1262
+ cached = options.has_key?(:cache) ? options.delete(:cache) : true
1263
+ raise ArgumentError, "Unrecognized arguments to agents(): #{options.inspect}" if options.keys.any?
1264
+ if cached
1265
+ @cached_proxy ||= QueueAgentsListProxy.new(self, true)
1266
+ else
1267
+ @uncached_proxy ||= QueueAgentsListProxy.new(self, false)
1268
+ end
1269
+ end
1270
+
1271
+ # Check how many channels are waiting in the queue
1272
+ # @return [Integer]
1273
+ # @raise QueueDoesNotExistError
1274
+ def waiting_count
1275
+ raise QueueDoesNotExistError.new(name) unless exists?
1276
+ environment.variable("QUEUE_WAITING_COUNT(#{name})").to_i
1277
+ end
1278
+
1279
+ # Check whether the waiting count is zero
1280
+ # @return [Boolean]
1281
+ def empty?
1282
+ waiting_count == 0
1283
+ end
1284
+
1285
+ # Check whether any calls are waiting in the queue
1286
+ # @return [Boolean]
1287
+ def any?
1288
+ waiting_count > 0
1289
+ end
1290
+
1291
+ # Check whether a queue exists/is defined in Asterisk
1292
+ # @return [Boolean]
1293
+ def exists?
1294
+ environment.execute('RemoveQueueMember', name, 'SIP/AdhearsionQueueExistenceCheck')
1295
+ environment.variable("RQMSTATUS") != 'NOSUCHQUEUE'
1296
+ end
1297
+
1298
+ private
1299
+
1300
+ # Ensure the queue exists by interpreting the QUEUESTATUS variable
1301
+ #
1302
+ # According to http://www.voip-info.org/wiki/view/Asterisk+cmd+Queue
1303
+ # possible values are:
1304
+ #
1305
+ # TIMEOUT => :timeout
1306
+ # FULL => :full
1307
+ # JOINEMPTY => :joinempty
1308
+ # LEAVEEMPTY => :leaveempty
1309
+ # JOINUNAVAIL => :joinunavail
1310
+ # LEAVEUNAVAIL => :leaveunavail
1311
+ # CONTINUE => :continue
1312
+ #
1313
+ # If the QUEUESTATUS variable is not set the call was successfully connected,
1314
+ # and Adhearsion will return :completed.
1315
+ #
1316
+ # @param [String] QUEUESTATUS variable from Asterisk
1317
+ # @return [Symbol] Symbolized version of QUEUESTATUS
1318
+ # @raise QueueDoesNotExistError
1319
+ def normalize_queue_status_variable(variable)
1320
+ variable = "COMPLETED" if variable.nil?
1321
+ variable.downcase.to_sym
1322
+ end
1323
+
1324
+ class QueueAgentsListProxy
1325
+
1326
+ include Enumerable
1327
+
1328
+ attr_reader :proxy, :agents
1329
+ def initialize(proxy, cached=false)
1330
+ @proxy = proxy
1331
+ @cached = cached
1332
+ end
1333
+
1334
+ def count
1335
+ if cached? && @cached_count
1336
+ @cached_count
1337
+ else
1338
+ @cached_count = proxy.environment.variable("QUEUE_MEMBER_COUNT(#{proxy.name})").to_i
1339
+ end
1340
+ end
1341
+ alias size count
1342
+ alias length count
1343
+
1344
+ # @param [Hash] args
1345
+ # :name value will be viewable in the queue_log
1346
+ # :penalty is the penalty assigned to this agent for answering calls on this queue
1347
+ def new(*args)
1348
+
1349
+ options = args.last.kind_of?(Hash) ? args.pop : {}
1350
+ interface = args.shift
1351
+
1352
+ raise ArgumentError, "You must specify an interface to add." if interface.nil?
1353
+ raise ArgumentError, "You may only supply an interface and a Hash argument!" if args.any?
1354
+
1355
+ penalty = options.delete(:penalty) || ''
1356
+ name = options.delete(:name) || ''
1357
+ state_interface = options.delete(:state_interface) || ''
1358
+
1359
+ raise ArgumentError, "Unrecognized argument(s): #{options.inspect}" if options.any?
1360
+
1361
+ proxy.environment.execute("AddQueueMember", proxy.name, interface, penalty, '', name, state_interface)
1362
+
1363
+ added = case proxy.environment.variable("AQMSTATUS")
1364
+ when "ADDED" then true
1365
+ when "MEMBERALREADY" then false
1366
+ when "NOSUCHQUEUE" then raise QueueDoesNotExistError.new(proxy.name)
1367
+ else
1368
+ raise "UNRECOGNIZED AQMSTATUS VALUE!"
1369
+ end
1370
+
1371
+ if added
1372
+ check_agent_cache!
1373
+ AgentProxy.new(interface, proxy).tap do |agent_proxy|
1374
+ @agents << agent_proxy
1375
+ end
1376
+ else
1377
+ false
1378
+ end
1379
+ end
1380
+
1381
+ # Logs a pre-defined agent into this queue and waits for calls. Pass in :silent => true to stop
1382
+ # the message which says "Agent logged in".
1383
+ def login!(*args)
1384
+ options = args.last.kind_of?(Hash) ? args.pop : {}
1385
+
1386
+ silent = options.delete(:silent).equal?(false) ? '' : 's'
1387
+ id = args.shift
1388
+ id &&= AgentProxy.id_from_agent_channel(id)
1389
+ raise ArgumentError, "Unrecognized Hash options to login(): #{options.inspect}" if options.any?
1390
+ raise ArgumentError, "Unrecognized argument to login(): #{args.inspect}" if args.any?
1391
+
1392
+ proxy.environment.execute('AgentLogin', id, silent)
1393
+ end
1394
+
1395
+ # Removes the current channel from this queue
1396
+ def logout!
1397
+ # TODO: DRY this up. Repeated in the AgentProxy...
1398
+ proxy.environment.execute 'RemoveQueueMember', proxy.name
1399
+ case proxy.environment.variable("RQMSTATUS")
1400
+ when "REMOVED" then true
1401
+ when "NOTINQUEUE" then false
1402
+ when "NOSUCHQUEUE"
1403
+ raise QueueDoesNotExistError.new(proxy.name)
1404
+ else
1405
+ raise "Unrecognized RQMSTATUS variable!"
1406
+ end
1407
+ end
1408
+
1409
+ def each(&block)
1410
+ check_agent_cache!
1411
+ agents.each(&block)
1412
+ end
1413
+
1414
+ def first
1415
+ check_agent_cache!
1416
+ agents.first
1417
+ end
1418
+
1419
+ def last
1420
+ check_agent_cache!
1421
+ agents.last
1422
+ end
1423
+
1424
+ def cached?
1425
+ @cached
1426
+ end
1427
+
1428
+ def to_a
1429
+ check_agent_cache!
1430
+ @agents
1431
+ end
1432
+
1433
+ private
1434
+
1435
+ def check_agent_cache!
1436
+ if cached?
1437
+ load_agents! unless agents
1438
+ else
1439
+ load_agents!
1440
+ end
1441
+ end
1442
+
1443
+ def load_agents!
1444
+ raw_data = proxy.environment.variable "QUEUE_MEMBER_LIST(#{proxy.name})"
1445
+ @agents = raw_data.split(',').map(&:strip).reject(&:empty?).map do |agent|
1446
+ AgentProxy.new(agent, proxy)
1447
+ end
1448
+ @cached_count = @agents.size
1449
+ end
1450
+
1451
+ end
1452
+
1453
+ class AgentProxy
1454
+
1455
+ SUPPORTED_METADATA_NAMES = %w[status password name mohclass exten channel] unless defined? SUPPORTED_METADATA_NAMES
1456
+
1457
+ class << self
1458
+ def id_from_agent_channel(id)
1459
+ id = id.to_s
1460
+ id.starts_with?('Agent/') ? id[%r[^Agent/(.+)$],1] : id
1461
+ end
1462
+ end
1463
+
1464
+ attr_reader :interface, :proxy, :queue_name, :id
1465
+ def initialize(interface, proxy)
1466
+ @interface = interface
1467
+ @id = self.class.id_from_agent_channel interface
1468
+ @proxy = proxy
1469
+ @queue_name = proxy.name
1470
+ end
1471
+
1472
+ def remove!
1473
+ proxy.environment.execute 'RemoveQueueMember', queue_name, interface
1474
+ case proxy.environment.variable("RQMSTATUS")
1475
+ when "REMOVED" then true
1476
+ when "NOTINQUEUE" then false
1477
+ when "NOSUCHQUEUE"
1478
+ raise QueueDoesNotExistError.new(queue_name)
1479
+ else
1480
+ raise "Unrecognized RQMSTATUS variable!"
1481
+ end
1482
+ end
1483
+
1484
+ # Pauses the given agent for this queue only. If you wish to pause this agent
1485
+ # for all queues, pass in :everywhere => true. Returns true if the agent was
1486
+ # successfully paused and false if the agent was not found.
1487
+ def pause!(options={})
1488
+ everywhere = options.delete(:everywhere)
1489
+ args = [(everywhere ? nil : queue_name), interface]
1490
+ proxy.environment.execute('PauseQueueMember', *args)
1491
+ case proxy.environment.variable("PQMSTATUS")
1492
+ when "PAUSED" then true
1493
+ when "NOTFOUND" then false
1494
+ else
1495
+ raise "Unrecognized PQMSTATUS value!"
1496
+ end
1497
+ end
1498
+
1499
+ # Pauses the given agent for this queue only. If you wish to pause this agent
1500
+ # for all queues, pass in :everywhere => true. Returns true if the agent was
1501
+ # successfully paused and false if the agent was not found.
1502
+ def unpause!(options={})
1503
+ everywhere = options.delete(:everywhere)
1504
+ args = [(everywhere ? nil : queue_name), interface]
1505
+ proxy.environment.execute('UnpauseQueueMember', *args)
1506
+ case proxy.environment.variable("UPQMSTATUS")
1507
+ when "UNPAUSED" then true
1508
+ when "NOTFOUND" then false
1509
+ else
1510
+ raise "Unrecognized UPQMSTATUS value!"
1511
+ end
1512
+ end
1513
+
1514
+ # Returns true/false depending on whether this agent is logged in.
1515
+ def logged_in?
1516
+ status == 'LOGGEDIN'
1517
+ end
1518
+
1519
+ private
1520
+
1521
+ def status
1522
+ agent_metadata 'status'
1523
+ end
1524
+
1525
+ def agent_metadata(data_name)
1526
+ data_name = data_name.to_s.downcase
1527
+ raise ArgumentError, "unrecognized agent metadata name #{data_name}" unless SUPPORTED_METADATA_NAMES.include? data_name
1528
+ proxy.environment.variable "AGENT(#{id}:#{data_name})"
1529
+ end
1530
+
1531
+ end
1532
+
1533
+ class QueueDoesNotExistError < StandardError
1534
+ def initialize(queue_name)
1535
+ super "Queue #{queue_name} does not exist!"
1536
+ end
1537
+ end
1538
+
1539
+ end
1540
+
1541
+ module MenuDigitResponse
1542
+ def timed_out?
1543
+ eql? 0.chr
1544
+ end
1545
+ end
1546
+
1547
+ module SpeechEngines
1548
+
1549
+ class InvalidSpeechEngine < StandardError; end
1550
+
1551
+ class << self
1552
+ def cepstral(text)
1553
+ puts "in ceptral"
1554
+ puts escape(text)
1555
+ end
1556
+
1557
+ def festival(text)
1558
+ raise NotImplementedError
1559
+ end
1560
+
1561
+ def none(text)
1562
+ raise InvalidSpeechEngine, "No speech engine selected. You must specify one in your Adhearsion config file."
1563
+ end
1564
+
1565
+ def method_missing(engine_name, text)
1566
+ raise InvalidSpeechEngine, "Unsupported speech engine #{engine_name} for speaking '#{text}'"
1567
+ end
1568
+
1569
+ private
1570
+
1571
+ def escape(text)
1572
+ "%p" % text
1573
+ end
1574
+
1575
+ end
1576
+ end
1577
+
1578
+ end
1579
+ end
1580
+ end
1581
+ end