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
# 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
    redis = Redis.new
    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 = redis.blpop(job.id, timeout: 1)
        while data
          response.stream.write data
          redis.publish(job.id, "OK")
          list, data = redis.blpop(job.id, timeout: 1)
        end
      end
    end #timeout  
  end
rescue => e
  p "will continue next time #{e.message}"
ensure
  redis.quit
  response.stream.close
end

#push ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'app/controllers/extface/handler_controller.rb', line 40

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