Class: WS

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

Instance Method Summary collapse

Constructor Details

#initialize(ringcentral, events, callback, debugMode = false) ⇒ WS

Returns a new instance of WS.



7
8
9
10
11
12
# File 'lib/subscription.rb', line 7

def initialize(ringcentral, events, callback, debugMode = false)
  @rc = ringcentral
  @events = events
  @callback = callback
  @debugMode = debugMode
end

Instance Method Details

#on_ws_closed=(callback) ⇒ Object



14
15
16
# File 'lib/subscription.rb', line 14

def on_ws_closed=(callback)
  @on_ws_closed = callback
end

#revokeObject



63
64
65
# File 'lib/subscription.rb', line 63

def revoke
  @t.kill
end

#subscribeObject



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
57
58
59
60
61
# File 'lib/subscription.rb', line 18

def subscribe
  r = @rc.post('/restapi/oauth/wstoken').body
  @t = Thread.new do
    EM.run {
      @ws = Faye::WebSocket::Client.new(r['uri'] + '?access_token=' + r['ws_access_token'])
      if @debugMode
        class << @ws
          def send(message)
            puts "Sending...\n" + message
            super(message)
          end
        end
      end
      @ws.on :open do
        @ws.send([
          { type: 'ClientRequest', method: 'POST', path: '/restapi/v1.0/subscription', messageId: SecureRandom.uuid },
          { deliveryMode: { transportType: 'WebSocket' }, eventFilters: @events }
        ].to_json())

        # send a heartbeat every 10 minutes
        @task = Concurrent::TimerTask.new(execution_interval: 600) do
          @ws.send([
            { type: 'Heartbeat', messageId: SecureRandom.uuid },
          ].to_json())
        end
        @task.execute
      end
      @ws.on :message do |event|
        if @debugMode
          puts "Receiving...\n" + event.data
        end
        header, body = JSON.parse(event.data)
        if header['type'] == 'ServerNotification'
          @callback.call(body)
        end
      end
      @ws.on :close do |event|
        if @on_ws_closed
          @on_ws_closed.call(event)
        end
      end
    }
  end
end