Class: Viaduct::WebPush::WebSocket::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/viaduct/web_push/web_socket/connection.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
  :authenticate => true,
  :autoconnect => true
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Connection

Returns a new instance of Connection.



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
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/viaduct/web_push/web_socket/connection.rb', line 13

def initialize(options={})
  @options = DEFAULT_OPTIONS.merge(options)

  @connected = false
  @authenticated = false
  @session_id = nil
  @channels = {}
  @logger = WebSocket.logger

  # Set up global vwp events
  @global_channel = subscribe(nil)

  # On connect, store data from the payload, send vwp:subscribe events
  # for each channel that's already been addded
  @global_channel.bind 'vwp:connected' do |data|
    @logger.info "Connected to vwp"

    @global_channel.subscribed = true
    @session_id = data["session_id"]
    @connected = true

    register_subscriptions
  end

  # If we're sending messages we need to authenticate after we've connected to vwp
  if @options[:authenticate]
    @global_channel.bind 'vwp:connected' do
      authenticate
    end
    @global_channel.bind 'vwp:authenticated' do 
      @logger.info "Authenticated with vwp"
      @authenticated = true
    end
  end

  # When we've successfully subscribed to a channel set the subscribed bit to true on the channel
  @global_channel.bind 'vwp:subscribed' do |data|
    channel_id = data['channel']
    @channels[channel_id].subscribed = true
    @logger.info "Subscribed to vwp #{data['channel_name']}"
  end

  connect if @options[:autoconnect]
end

Instance Attribute Details

#authenticatedObject (readonly)

Returns the value of attribute authenticated.



6
7
8
# File 'lib/viaduct/web_push/web_socket/connection.rb', line 6

def authenticated
  @authenticated
end

#channelsObject (readonly)

Returns the value of attribute channels.



6
7
8
# File 'lib/viaduct/web_push/web_socket/connection.rb', line 6

def channels
  @channels
end

#connectedObject (readonly)

Returns the value of attribute connected.



6
7
8
# File 'lib/viaduct/web_push/web_socket/connection.rb', line 6

def connected
  @connected
end

#session_idObject (readonly)

Returns the value of attribute session_id.



6
7
8
# File 'lib/viaduct/web_push/web_socket/connection.rb', line 6

def session_id
  @session_id
end

Instance Method Details

#[](channel_name) ⇒ Object



58
59
60
# File 'lib/viaduct/web_push/web_socket/connection.rb', line 58

def [](channel_name)
  @channels[channel_name]
end

#connectObject

Create a new thread and connect to vwp in it. Create an event loop for the thread which will dispatch incoming messages



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/viaduct/web_push/web_socket/connection.rb', line 76

def connect
  return if @websocket
  @logger.debug "Connecting..."

  Thread.abort_on_exception = true
  @websocket_thread = Thread.new do
    @websocket = RawSocket.new
    loop do
      @websocket.receive.each do |message|
        data = JSON.parse(message)
        @logger.debug data
        dispatch(data)
      end
    end
  end

  self
end

#disconnectObject

Disconnect the websocket server and reset all variables, set all channels as unsubscribed



99
100
101
102
103
104
105
106
107
108
# File 'lib/viaduct/web_push/web_socket/connection.rb', line 99

def disconnect
  @websocket.disconnect
  @websocket = nil
  @websocket_thread.kill
  @websocket_thread = nil
  @connected = false
  @session_id = nil
  @channels.each {|name, chan| chan.subscribed = false }
  @logger.info "Disconnected from vwp"
end

#inspectObject



141
142
143
144
145
146
147
148
149
# File 'lib/viaduct/web_push/web_socket/connection.rb', line 141

def inspect
  String.new.tap do |s|
    s << "#<#{self.class.name}:#{self.object_id} "
    s << [:connected, :session_id, :channels].map do |attrib|
      "#{attrib}: #{self.send(attrib).inspect}"
    end.join(', ')
    s << ">"
  end
end

#register_subscription(channel_name, signature) ⇒ Object

Send a vwp:subscribe message via the websocket. The socket name and signature are calculated by the Channel



133
134
135
136
137
138
139
# File 'lib/viaduct/web_push/web_socket/connection.rb', line 133

def register_subscription(channel_name, signature)
  payload = JSON.generate({"event" => "vwp:subscribe", "data" => {
    "channel" => channel_name,
    "signature" => signature
  }})
  @websocket.send_data(payload)
end

#subscribe(channel_name) ⇒ Object

Create a new channel object and send a vwp:subscribe event if we’re already connected to vwp



66
67
68
69
70
# File 'lib/viaduct/web_push/web_socket/connection.rb', line 66

def subscribe(channel_name)
  @channels[channel_name] ||= Channel.new(channel_name, self)
  @channels[channel_name].register if @connected 
  @channels[channel_name]
end

#trigger(channel_name, event, data) ⇒ Object

Build a vwp message and send it via the websocket



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/viaduct/web_push/web_socket/connection.rb', line 113

def trigger(channel_name, event, data)
  return false unless @authenticated

  payload = JSON.generate({
    "event" => "vwp:send",
    "data" => {
      "channel" => channel_name,
      "event" => event,
      "data" => data
    }
  })

  @websocket.send_data(payload)
  true
end