Module: Waithook::CLI

Extended by:
CLI
Included in:
CLI
Defined in:
lib/waithook/cli.rb

Overview

:nodoc:

Defined Under Namespace

Classes: ArgError

Instance Method Summary collapse

Instance Method Details

#listen(url, options) ⇒ Object



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
# File 'lib/waithook/cli.rb', line 21

def listen(url, options)
  puts "Run with options: #{options}" if options[:verbose]
  unless url.start_with?('ws://', 'wss://')
    url = 'ws://' + url
  end

  unless url =~ /\A#{URI::regexp(['ws', 'wss'])}\z/
    raise ArgError, "#{url.inspect} is not a valid websocket URL"
  end

  uri = URI.parse(url)
  port = uri.scheme == 'wss' ? 443 : uri.port
  path = uri.path.start_with?('/') ? uri.path.sub(/^\//, '') : uri.path
  logger_level = options[:verbose] ? 'trace' : 'warn'

  puts WithColor.green("Connecting to #{url}")
  waithook = Waithook.new(host: uri.host, port: port, path: path, logger_level: logger_level)
  puts WithColor.green("Connected! Waiting to for message...") if waithook.client.wait_connected

  while true
    message = waithook.wait_message
    puts message.pretty_print
    if options[:forward]
      Thread.new do
        begin
          forward_url = if options[:forward].start_with?('http://', 'https://')
            options[:forward]
          else
            "http://#{options[:forward]}"
          end

          puts WithColor.brown("Sending as HTTP to #{forward_url}")
          response = message.send_to(forward_url)
          puts WithColor.brown("Reponse from #{forward_url} -> #{WithColor.bold("#{response.code} #{response.message}")}")
        rescue => error
          puts WithColor.red("#{error.message} (#{error.class})")
          puts WithColor.red(error.backtrace.join("\n"))
        end
      end
    end
  end
end