Class: NetworkExecutive::Viewer

Inherits:
Object
  • Object
show all
Defined in:
app/models/network_executive/viewer.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env) ⇒ Viewer

Returns a new instance of Viewer.



6
7
8
# File 'app/models/network_executive/viewer.rb', line 6

def initialize( env )
  @env = env
end

Instance Attribute Details

#heartbeatObject

Returns the value of attribute heartbeat.



4
5
6
# File 'app/models/network_executive/viewer.rb', line 4

def heartbeat
  @heartbeat
end

#idObject

Returns the value of attribute id.



4
5
6
# File 'app/models/network_executive/viewer.rb', line 4

def id
  @id
end

Class Method Details

.change_channel(env) ⇒ Object



69
70
71
72
73
74
75
76
# File 'app/models/network_executive/viewer.rb', line 69

def change_channel( env )
  viewer = Viewer.new( env )

  viewer.tune_in
  viewer.keep_alive!

  viewer.response
end

Instance Method Details

#channelObject



20
21
22
23
24
# File 'app/models/network_executive/viewer.rb', line 20

def channel
  Channel.find_by_name( channel_name ).tap do |ch|
    raise ChannelNotFoundError unless ch
  end
end

#channel_nameObject



56
57
58
# File 'app/models/network_executive/viewer.rb', line 56

def channel_name
  @env['PATH_INFO'].split('/').last
end

#ipObject



10
11
12
13
14
15
16
17
18
# File 'app/models/network_executive/viewer.rb', line 10

def ip
  @ip ||= begin
    if addr = @env['HTTP_X_FORWARDED_FOR']
      (addr.split(',').grep(/\d\./).first || @env['REMOTE_ADDR']).to_s.strip
    else
      @env['REMOTE_ADDR']
    end
  end
end

#keep_alive!Object



60
61
62
63
64
65
66
# File 'app/models/network_executive/viewer.rb', line 60

def keep_alive!
  self.heartbeat = EM.add_periodic_timer( 30 ) do
    stream.ping

    Rails.logger.debug "Completed PING for #{ip} on the #{channel} channel at #{Time.now}"
  end
end

#responseObject



52
53
54
# File 'app/models/network_executive/viewer.rb', line 52

def response
  stream.rack_response
end

#streamObject



26
27
28
# File 'app/models/network_executive/viewer.rb', line 26

def stream
  @stream ||= Faye::EventSource.new @env
end

#tune_inObject



30
31
32
33
34
35
36
37
38
39
40
# File 'app/models/network_executive/viewer.rb', line 30

def tune_in
  Rails.logger.debug "Tuning in to the #{channel} channel for #{ip} at #{Time.now}"

  self.id = channel.subscribe { |msg| stream.send msg }

  stream.onclose = method(:tune_out).to_proc

  channel.play_whats_on do |msg|
    stream.send msg
  end
end

#tune_out(event) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'app/models/network_executive/viewer.rb', line 42

def tune_out( event )
  Rails.logger.debug "Tuning out of the #{channel} channel for #{ip} at #{Time.now}"

  channel.unsubscribe id

  heartbeat.cancel

  @stream = nil
end