Class: Extface::HandlerController

Inherits:
ApplicationController show all
Includes:
ActionController::Live
Defined in:
app/controllers/extface/handler_controller.rb

Instance Method Summary collapse

Methods inherited from ApplicationController

#extfaceable, #index

Instance Method Details

#pull ⇒ Object



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
# File 'app/controllers/extface/handler_controller.rb', line 12

def pull
  # request.body.read usable?
  unless device.present?
    render nothing: true, status: :not_found
  else
    response.headers['Content-Type'] = 'text/event-stream'
    # find current job or get new one
    Extface.redis_block do |r|
      Timeout.timeout(2) do
        if job = device.jobs.active.find_by(id: cookies[:extface]) || device.jobs.active.try(:first)
          cookies.permanent[:extface] = job.id
          p "Processing job #{job.id}"
          list, data = r.blpop(job.id, timeout: 1)
          #TODO rescue here will loose data
          while data
            response.stream.write data
            r.publish(job.id, "OK")
            list, data = r.blpop(job.id, timeout: 1)
          end
        end
      end #timeout 
    end #redis block
  end
rescue => e
  if e.instance_of? Timeout::Error
    p "will continue next time #{e.message}"
  else
    render nothing: true, status: :internal_server_error
  end
ensure
  response.stream.close
end

#push ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'app/controllers/extface/handler_controller.rb', line 45

def push
  # get  request.body.read
  # if it is push message, process it
  response.headers['Content-Type'] = 'text/event-stream'
  p request.body.read
  Extface.redis.subscribe(:alabala) do |on|
    on.message do |event, data|
      response.stream.write("event: #{event} data: #{data}\n\n")
      Extface.redis.unsubscribe
    end
  end
  response.stream.write "finish\n"
ensure
  response.stream.write "failed\n"
  response.stream.close
end

#settings ⇒ Object



62
63
64
# File 'app/controllers/extface/handler_controller.rb', line 62

def settings
  render text: 'settings'
end