Class: Slanger::Handler

Inherits:
Object
  • Object
show all
Defined in:
lib/slanger/handler.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(socket, handshake) ⇒ Handler

Returns a new instance of Handler.



15
16
17
18
19
20
21
# File 'lib/slanger/handler.rb', line 15

def initialize(socket, handshake)
  @socket        = socket
  @handshake     = handshake
  @connection    = Connection.new(@socket)
  @subscriptions = {}
  authenticate
end

Instance Attribute Details

#connectionObject

Returns the value of attribute connection.



12
13
14
# File 'lib/slanger/handler.rb', line 12

def connection
  @connection
end

Instance Method Details

#authenticateObject



49
50
51
52
53
54
# File 'lib/slanger/handler.rb', line 49

def authenticate
  return connection.establish if valid_app_key? app_key

  error({ code: 4001, message: "Could not find app by key #{app_key}" })
  @socket.close_websocket
end

#oncloseObject



42
43
44
45
46
47
# File 'lib/slanger/handler.rb', line 42

def onclose
  @subscriptions.select { |k,v| k && v }.
    each do |channel_id, subscription_id|
      Channel.unsubscribe channel_id, subscription_id
    end
end

#onmessage(msg) ⇒ Object

Dispatches message handling to method with same name as the event name



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/slanger/handler.rb', line 25

def onmessage(msg)
  msg   = JSON.parse msg
  event = msg['event'].gsub(/^pusher:/, 'pusher_')

  if event =~ /^client-/
    msg['socket_id'] = connection.socket_id
    Channel.send_client_message msg
  elsif respond_to? event, true
    send event, msg
  end

rescue JSON::ParserError
  error({ code: 5001, message: "Invalid JSON" })
rescue Exception => e
  error({ code: 500, message: "#{e.message}\n #{e.backtrace.join "\n"}" })
end

#pusher_ping(msg) ⇒ Object



56
57
58
# File 'lib/slanger/handler.rb', line 56

def pusher_ping(msg)
  send_payload nil, 'pusher:pong'
end

#pusher_pong(msg) ⇒ Object



60
# File 'lib/slanger/handler.rb', line 60

def pusher_pong msg; end

#pusher_subscribe(msg) ⇒ Object



62
63
64
65
66
67
68
69
70
71
# File 'lib/slanger/handler.rb', line 62

def pusher_subscribe(msg)
  channel_id = msg['data']['channel']
  klass      = subscription_klass channel_id

  if @subscriptions[channel_id]
    error({ code: nil, message: "Existing subscription to #{channel_id}" })
  else
    @subscriptions[channel_id] = klass.new(connection.socket, connection.socket_id, msg).subscribe
  end
end

#pusher_unsubscribe(msg) ⇒ Object



73
74
75
76
77
78
# File 'lib/slanger/handler.rb', line 73

def pusher_unsubscribe(msg)
  channel_id      = msg['data']['channel']
  subscription_id = @subscriptions.delete(channel_id)

  Channel.unsubscribe channel_id, subscription_id
end