Class: Mattermost::WebSocketClient

Inherits:
Object
  • Object
show all
Includes:
EventEmitter
Defined in:
lib/mattermost/websocket_client.rb

Instance Method Summary collapse

Constructor Details

#initialize(url, token, option = {}) {|_self| ... } ⇒ WebSocketClient

Returns a new instance of WebSocketClient.

Yields:

  • (_self)

Yield Parameters:



9
10
11
12
13
14
15
16
17
18
# File 'lib/mattermost/websocket_client.rb', line 9

def initialize(url, token, option = {})
  @token = token
  @url = url
  @option = option
  @seq_mutex = Mutex.new
  @connected = false
  yield self if block_given?
  connect
  self
end

Instance Method Details

#closeObject



70
71
72
73
74
75
76
# File 'lib/mattermost/websocket_client.rb', line 70

def close
  @connected = false
  @client.close if @client != nil
  @client = nil
  Thread.kill @em if @em != nil
  @em = nil
end

#connectObject



20
21
22
23
24
25
26
27
28
# File 'lib/mattermost/websocket_client.rb', line 20

def connect
  return self if connected?
  mm_ws = self
  @em = Thread.new do
    EM.run do
      mm_ws.connect_internal
    end
  end
end

#connect_internalObject



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/mattermost/websocket_client.rb', line 78

def connect_internal
  @seq = 0
  mm_ws = self
  @client = Faye::WebSocket::Client.new(@url.gsub(/^http(s?):/, 'ws\1:'), {}, { :headers => {
    'Authorization' => "Bearer #{@token}"
  }})
  @client.on :open do |e|
    mm_ws.on_open e
  end
  @client.on :message do |msg|
    mm_ws.on_message msg.data
  end
  @client.on :close do |e|
    mm_ws.on_close e
  end
  @client.on :error do |e|
    mm_ws.on_error e
  end
end

#connected?Boolean



66
67
68
# File 'lib/mattermost/websocket_client.rb', line 66

def connected?
  @connected && (@client != nil && @client.ready_state == Faye::WebSocket::API::OPEN)
end

#on_close(msg) ⇒ Object



48
49
50
51
# File 'lib/mattermost/websocket_client.rb', line 48

def on_close(msg)
  @connected = false
  emit :close, msg
end

#on_error(err) ⇒ Object



53
54
55
# File 'lib/mattermost/websocket_client.rb', line 53

def on_error(err)
  emit :error, err
end

#on_message(data) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/mattermost/websocket_client.rb', line 34

def on_message(data)
  json = JSON.parse data
  event = json["event"]
  #puts "on_message json:#{json}, event:#{event}"
  seq_up json
  case event
  when "hello"
    @connected = true
  else
    emit event.to_sym, json
  end
  emit :message, json
end

#on_open(e) ⇒ Object



30
31
32
# File 'lib/mattermost/websocket_client.rb', line 30

def on_open(e)
  emit :open, e
end

#send_msg(action, data) ⇒ Object



57
58
59
60
61
62
63
64
# File 'lib/mattermost/websocket_client.rb', line 57

def send_msg(action, data)
  payload = {
    :seq => next_seq,
    :action => action,
    :data => data
  }.to_json
  @client.send payload
end