lib/mattermost/websocket_client.rb in mattermost-api4-ruby-0.0.4 vs lib/mattermost/websocket_client.rb in mattermost-api4-ruby-0.0.5
- old
+ new
@@ -1,39 +1,36 @@
-require 'websocket-client-simple'
+require 'faye/websocket'
require 'event_emitter'
require 'json'
module Mattermost
class WebSocketClient
include EventEmitter
def initialize(url, token, option = {})
@token = token
@url = url
+ @option = option
@seq_mutex = Mutex.new
- @seq = 0
@connected = false
+ yield self if block_given?
+ connect
+ self
+ end
+
+ def connect
+ return self if connected?
mm_ws = self
- @client = WebSocket::Client::Simple.connect(url, option) do |ws|
- ws.on :open do
- mm_ws.on_open
+ @em = Thread.new do
+ EM.run do
+ mm_ws.connect_internal
end
- ws.on :message do |msg|
- mm_ws.on_message msg.data
- end
- ws.on :close do |e|
- mm_ws.on_close e
- end
- ws.on :error do |e|
- mm_ws.on_error e
- end
end
- yield self if block_given?
end
- def on_open
- emit :open
+ def on_open(e)
+ emit :open, e
end
def on_message(data)
json = JSON.parse data
event = json["event"]
@@ -42,12 +39,12 @@
case event
when "hello"
@connected = true
else
emit event.to_sym, json
- emit :message, json
end
+ emit :message, json
end
def on_close(msg)
@connected = false
emit :close, msg
@@ -65,17 +62,41 @@
}.to_json
@client.send payload
end
def connected?
- @connected && @client.connected?
+ @connected && (@client != nil && @client.ready_state == Faye::WebSocket::API::OPEN)
end
def close
- @client.close
+ @connected = false
+ @client.close if @client != nil
+ @client = nil
+ Thread.kill @em if @em != nil
+ @em = nil
end
+ 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
+
private
def seq_up(event)
@seq_mutex.synchronize do
return if !event.key? "seq"
@@ -88,7 +109,8 @@
@seq_mutex.synchronize do
@seq = @seq + 1
@seq
end
end
+
end
end