diff --git a/lib/librevox/listener/base.rb b/lib/librevox/listener/base.rb index 9e97d3d..e0a851a 100644 --- a/lib/librevox/listener/base.rb +++ b/lib/librevox/listener/base.rb @@ -59,6 +59,23 @@ def send_message(msg) reply end + # Fire an event into FreeSWITCH, for every ESL listener subscribed to it. + # Returns the Event-UUID FreeSWITCH gives the event, which every listener + # sees. A line break in a header would end the command early and send + # the rest as another command, so one raises ArgumentError. + # @example + # sendevent "CUSTOM", "Event-Subclass" => "my::event", "Some-Header" => "value" + def sendevent(name, headers = {}) + headers = headers.compact + if [name, *headers.flatten].any? { |part| part.to_s.match?(/[\r\n]/) } + raise ArgumentError, "sendevent headers can't contain line breaks" + end + + lines = headers.map { |header, value| "#{header}: #{value}" } + reply = send_message(["sendevent #{name}", *lines].join("\n")) + reply.headers[:reply_text].delete_prefix("+OK ") + end + def execute_app(app, uuid, args = nil, **params) event_uuid = SecureRandom.uuid diff --git a/test/functional/librevox/listener/inbound_test.rb b/test/functional/librevox/listener/inbound_test.rb index 407ce77..ca89bca 100644 --- a/test/functional/librevox/listener/inbound_test.rb +++ b/test/functional/librevox/listener/inbound_test.rb @@ -34,4 +34,24 @@ def test_sends_auth_and_event_subscription assert_equal "event plain ALL", @listener.outgoing_data.shift assert_nil @listener.outgoing_data.shift end + + def test_sendevent_sends_the_event_and_returns_its_event_uuid + @listener.outgoing_data.clear + sending = Async { @listener.sendevent("CUSTOM", "Event-Subclass" => "my::event", "Some-Header" => "value", "Skipped" => nil) } + command_reply "Reply-Text" => "+OK 2488abe2-c494-4d71-a83f-f3ab40c75f44" + + assert_equal "2488abe2-c494-4d71-a83f-f3ab40c75f44", sending.wait + assert_equal "sendevent CUSTOM\nEvent-Subclass: my::event\nSome-Header: value", @listener.outgoing_data.shift + end + + # A line break would end the command early and send the rest as a command + # of its own. + def test_sendevent_refuses_a_line_break_in_a_header + @listener.outgoing_data.clear + + assert_raises(ArgumentError) { @listener.sendevent("CUSTOM", "Some-Header" => "x\n\napi uuid_kill all") } + assert_raises(ArgumentError) { @listener.sendevent("CUSTOM", "Some\r\nHeader" => "x") } + assert_raises(ArgumentError) { @listener.sendevent("CUSTOM\nbgapi status") } + assert_nil @listener.outgoing_data.shift, "nothing was sent" + end end