Class: PubNub

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ringcentral, events, message_callback, status_callback = nil, presence_callback = nil) ⇒ PubNub

Returns a new instance of PubNub.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/subscription.rb', line 9

def initialize(ringcentral, events, message_callback, status_callback = nil, presence_callback = nil)
  @rc = ringcentral
  @events = events
  @callback = Pubnub::SubscribeCallback.new(
    message: lambda { |envelope|
      message = envelope.result[:data][:message]
      cipher = OpenSSL::Cipher::AES.new(128, :ECB)
      cipher.decrypt
      cipher.key = Base64.decode64(@subscription['deliveryMode']['encryptionKey'])
      ciphertext = Base64.decode64(message)
      plaintext = cipher.update(ciphertext) + cipher.final
      message_callback.call(JSON.parse(plaintext))
    },
    presence: lambda { |envelope|
      presence_callback != nil && presence_callback.call(envelope)
    },
    status: lambda { |envelope|
      status_callback != nil && status_callback.call(envelope)
    }
  )
  @subscription = nil
  @timer = nil
  @pubnub = nil
end

Instance Attribute Details

#eventsObject

Returns the value of attribute events.



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

def events
  @events
end

Instance Method Details

#refreshObject



56
57
58
59
60
# File 'lib/subscription.rb', line 56

def refresh
  return if @subscription == nil
  r = @rc.put("/restapi/v1.0/subscription/#{@subscription['id']}", payload: request_body)
  self.subscription = r.body
end

#revokeObject



62
63
64
65
66
67
68
69
# File 'lib/subscription.rb', line 62

def revoke
  return if @subscription == nil
  @pubnub.unsubscribe(channel: @subscription['deliveryMode']['address'])
  @pubnub.remove_listener(name: 'default')
  @pubnub = nil
  @rc.delete("/restapi/v1.0/subscription/#{@subscription['id']}")
  self.subscription = nil
end

#subscribeObject



48
49
50
51
52
53
54
# File 'lib/subscription.rb', line 48

def subscribe
  r = @rc.post('/restapi/v1.0/subscription', payload: request_body)
  self.subscription = r.body
  @pubnub = Pubnub.new(subscribe_key: @subscription['deliveryMode']['subscriberKey'], user_id: @rc.token['owner_id'])
  @pubnub.add_listener(name: 'default', callback: @callback)
  @pubnub.subscribe(channels: @subscription['deliveryMode']['address'])
end

#subscription=(value) ⇒ Object



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

def subscription=(value)
  @subscription = value
  if @timer != nil
    @timer.shutdown
    @timer = nil
  end
  if value != nil
    @timer = Concurrent::TimerTask.new(execution_interval: value['expiresIn'] - 120) do
      self.refresh
    end
    @timer.execute
  end
end