Class: Adash::WaitIndefinitely

Inherits:
Object
  • Object
show all
Defined in:
lib/adash/wait_indefinitely.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(device_model, serial, is_test: false) ⇒ WaitIndefinitely

Returns a new instance of WaitIndefinitely.



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
# File 'lib/adash/wait_indefinitely.rb', line 10

def initialize(device_model, serial, is_test: false)
  require 'webrick'
  @device_model = device_model
  @serial = serial
  @is_test = is_test
  @redirect_uri = "http://localhost:#{Adash::Config.redirect_port}/"
  @code_box = Queue.new
  @code_cv = ConditionVariable.new
  @code_mutex = Mutex.new
  @server = WEBrick::HTTPServer.new({ :BindAddress => '127.0.0.1', :Port => Adash::Config.redirect_port })
  @server.mount_proc('/getting_started', proc { |req, res|
    res.content_type = 'text/html'
    content = %Q`<p>Please go to <a href="#{ERB::Util.html_escape(amazon_authorization_url(@device_model, @serial))}">initial tour</a>.</p>`
    res.body = render(content)
  })
  @server.mount_proc('/', proc { |req, res|
    res.content_type = 'text/html'
    if req.query.include?('code')
      content = '<p>Done. Please close this tab.</p>'
      @code_mutex.synchronize {
        @code_box.push(req.query['code'].to_s)
        @code_cv.signal
      }
    else
      content = "<dl>\n" + req.query.map { |k, v| "<dt>#{k}</dt><dd>#{v}</dd>" }.join("\n") + "\n</dl>"
    end
    res.body = render(content)
  })
end

Instance Attribute Details

#redirect_uriObject (readonly)

Returns the value of attribute redirect_uri.



8
9
10
# File 'lib/adash/wait_indefinitely.rb', line 8

def redirect_uri
  @redirect_uri
end

Instance Method Details

#get_codeObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/adash/wait_indefinitely.rb', line 40

def get_code
  t = Thread.new do
    @code_mutex.synchronize {
      # TODO: wait for WEBrick launch
      Launchy.open("http://localhost:#{Adash::Config.redirect_port}/getting_started")
      while @code_box.size == 0
        @code_cv.wait(@code_mutex)
        sleep 1
        @server.shutdown
      end
    }
  end
  @server.start
  @code_box.pop
end

#shutdownObject



56
57
58
# File 'lib/adash/wait_indefinitely.rb', line 56

def shutdown
  @server.shutdown
end