Class: Pandapush::Client

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app_id: nil, key: nil, secret: nil, url: 'https://pp-beta.instructure.com') ⇒ Client

Returns a new instance of Client.



9
10
11
# File 'lib/pandapush/client.rb', line 9

def initialize(app_id: nil, key: nil, secret: nil, url: 'https://pp-beta.instructure.com')
  @app_id, @key, @secret, @url = app_id, key, secret, url
end

Instance Attribute Details

#app_idObject

Returns the value of attribute app_id.



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

def app_id
  @app_id
end

#keyObject

Returns the value of attribute key.



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

def key
  @key
end

#secretObject

Returns the value of attribute secret.



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

def secret
  @secret
end

#urlObject

Returns the value of attribute url.



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

def url
  @url
end

Instance Method Details

#generate_token(channel:, channel_type: 'private', pub: true, sub: true, presence: nil) ⇒ Object

generate_token - returns a JWT token for client authentication

channel - The channel name the token works for (required)
channel_type - 'public' or 'private'. Defaults to private
pub - true if this token allows publishing. Defaults to true
sub - true if this token allows subscribing. Defaults to true

Examples:

client.generate_token(channel: 'messages', sub: false)

Raises:



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/pandapush/client.rb', line 35

def generate_token(channel:, channel_type: 'private', pub: true, sub: true, presence: nil)
  raise ConfigurationError, 'Missing client configuration: please check that key, secret and app_id are configured.' unless configured?

  payload = {
    keyId: key,
    channel: channel_uri(channel, channel_type),
    pub: pub,
    sub: sub
  }

  payload[:presence] = presence if presence

  JWT.encode(payload, secret)
end

#publish(channel:, message:, channel_type: 'private') ⇒ Object

publish - sends a message to a Pandapush channel

channel - The name of the channel to push to (required)
message - hash that will be JSON encoded (required)
channel_type - 'public' or 'private'. Defaults to private

Examples:

client.publish(channel: 'messages', message: {user: {id: 1, name: 'Neil Gupta', email: '[email protected]'}})

Raises:



20
21
22
23
24
25
# File 'lib/pandapush/client.rb', line 20

def publish(channel:, message:, channel_type: 'private')
  raise ConfigurationError, 'Missing client configuration: please check that key, secret and app_id are configured.' unless configured?

  RestClient.post channel_uri(channel, channel_type, include_base_url: true), message.to_json,
                  {:content_type => :json, :Authorization => "Token #{generate_token(channel: channel, channel_type: channel_type)}"}
end