Class: Pusher::Client

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Client

Returns a new instance of Client.



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
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/pusher/client.rb', line 27

def initialize(options = {})
  default_options = {
    :scheme => 'http',
    :port => 80,
  }

  if options[:use_tls] || options[:encrypted]
    default_options[:scheme] = "https"
    default_options[:port] = 443
  end

  merged_options = default_options.merge(options)

  if options.has_key?(:host)
    merged_options[:host] = options[:host]
  elsif options.has_key?(:cluster)
    merged_options[:host] = "api-#{options[:cluster]}.pusher.com"
  else
    merged_options[:host] = "api.pusherapp.com"
  end

  # TODO: Change host name when finalized
  merged_options[:notification_host] =
    options.fetch(:notification_host, "nativepush-cluster1.pusher.com")

  merged_options[:notification_scheme] =
    options.fetch(:notification_scheme, "https")

  @scheme, @host, @port, @app_id, @key, @secret, @notification_host, @notification_scheme =
    merged_options.values_at(
      :scheme, :host, :port, :app_id, :key, :secret, :notification_host, :notification_scheme
    )

  if options.has_key?(:encryption_master_key_base64)
    @encryption_master_key =
      Base64.decode64(options[:encryption_master_key_base64])
  end

  @http_proxy = nil
  self.http_proxy = options[:http_proxy] if options[:http_proxy]

  # Default timeouts
  @connect_timeout = 5
  @send_timeout = 5
  @receive_timeout = 5
  @keep_alive_timeout = 30
end

Instance Attribute Details

#app_idObject

Returns the value of attribute app_id.



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

def app_id
  @app_id
end

#connect_timeout=(value) ⇒ Object (writeonly)

Sets the attribute connect_timeout

Parameters:

  • value

    the value to set the attribute connect_timeout to.



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

def connect_timeout=(value)
  @connect_timeout = value
end

#encryption_master_keyObject

Returns the value of attribute encryption_master_key.



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

def encryption_master_key
  @encryption_master_key
end

#hostObject

Returns the value of attribute host.



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

def host
  @host
end

#http_proxyObject

Returns the value of attribute http_proxy.



8
9
10
# File 'lib/pusher/client.rb', line 8

def http_proxy
  @http_proxy
end

#keep_alive_timeout=(value) ⇒ Object (writeonly)

Sets the attribute keep_alive_timeout

Parameters:

  • value

    the value to set the attribute keep_alive_timeout to.



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

def keep_alive_timeout=(value)
  @keep_alive_timeout = value
end

#keyObject

Returns the value of attribute key.



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

def key
  @key
end

#notification_hostObject

Returns the value of attribute notification_host.



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

def notification_host
  @notification_host
end

#notification_schemeObject

Returns the value of attribute notification_scheme.



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

def notification_scheme
  @notification_scheme
end

#portObject

Returns the value of attribute port.



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

def port
  @port
end

#proxyObject (readonly)

Returns the value of attribute proxy.



8
9
10
# File 'lib/pusher/client.rb', line 8

def proxy
  @proxy
end

#receive_timeout=(value) ⇒ Object (writeonly)

Sets the attribute receive_timeout

Parameters:

  • value

    the value to set the attribute receive_timeout to.



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

def receive_timeout=(value)
  @receive_timeout = value
end

#schemeObject

Returns the value of attribute scheme.



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

def scheme
  @scheme
end

#secretObject

Returns the value of attribute secret.



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

def secret
  @secret
end

#send_timeout=(value) ⇒ Object (writeonly)

Sets the attribute send_timeout

Parameters:

  • value

    the value to set the attribute send_timeout to.



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

def send_timeout=(value)
  @send_timeout = value
end

Class Method Details

.from_env(key = 'PUSHER_URL') ⇒ Object

Loads the configuration from an url in the environment



15
16
17
18
# File 'lib/pusher/client.rb', line 15

def self.from_env(key = 'PUSHER_URL')
  url = ENV[key] || raise(ConfigurationError, key)
  from_url(url)
end

.from_url(url) ⇒ Object

Loads the configuration from a url



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

def self.from_url(url)
  client = new
  client.url = url
  client
end

Instance Method Details

#authenticate(channel_name, socket_id, custom_data = nil) ⇒ Hash

Generate the expected response for an authentication endpoint. See pusher.com/docs/authenticating_users for details.

Examples:

Private channels

render :json => Pusher.authenticate('private-my_channel', params[:socket_id])

Presence channels

render :json => Pusher.authenticate('presence-my_channel', params[:socket_id], {
  :user_id => current_user.id, # => required
  :user_info => { # => optional - for example
    :name => current_user.name,
    :email => current_user.email
  }
})

Parameters:

  • socket_id (String)
  • custom_data (Hash) (defaults to: nil)

    used for example by private channels

Returns:

  • (Hash)

Raises:



376
377
378
379
# File 'lib/pusher/client.rb', line 376

def authenticate(channel_name, socket_id, custom_data = nil)
  channel_instance = channel(channel_name)
  channel_instance.authenticate(socket_id, custom_data)
end

#authentication_tokenObject

Raises:



76
77
78
79
80
# File 'lib/pusher/client.rb', line 76

def authentication_token
  raise ConfigurationError, :key unless @key
  raise ConfigurationError, :secret unless @secret
  Pusher::Signature::Token.new(@key, @secret)
end

#channel(channel_name) ⇒ Channel Also known as: []

Return a convenience channel object by name that delegates operations on a channel. No API request is made.

Examples:

Pusher['my-channel']

Returns:

Raises:

  • (Pusher::Error)

    if the channel name is invalid. Channel names should be less than 200 characters, and should not contain anything other than letters, numbers, or the characters “_-=@,.;”



232
233
234
# File 'lib/pusher/client.rb', line 232

def channel(channel_name)
  Channel.new(nil, channel_name, self)
end

#channel_info(channel_name, params = {}) ⇒ Hash

Request info for a specific channel

GET /apps//channels/

Parameters:

  • channel_name (String)

    Channel name (max 200 characters)

  • params (Hash) (defaults to: {})

    Hash of parameters for the API - see REST API docs

Returns:

  • (Hash)

    See Pusher API docs

Raises:

  • (Pusher::Error)

    Unsuccessful response - see the error message

  • (Pusher::HTTPError)

    Error raised inside http client. The original error is wrapped in error.original_error



265
266
267
# File 'lib/pusher/client.rb', line 265

def channel_info(channel_name, params = {})
  get("/channels/#{channel_name}", params)
end

#channel_users(channel_name, params = {}) ⇒ Hash

Request info for users of a presence channel

GET /apps//channels//users

Parameters:

  • channel_name (String)

    Channel name (max 200 characters)

  • params (Hash) (defaults to: {})

    Hash of parameters for the API - see REST API docs

Returns:

  • (Hash)

    See Pusher API docs

Raises:

  • (Pusher::Error)

    Unsuccessful response - see the error message

  • (Pusher::HTTPError)

    Error raised inside http client. The original error is wrapped in error.original_error



281
282
283
# File 'lib/pusher/client.rb', line 281

def channel_users(channel_name, params = {})
  get("/channels/#{channel_name}/users", params)
end

#channels(params = {}) ⇒ Hash

Request a list of occupied channels from the API

GET /apps//channels

Parameters:

  • params (Hash) (defaults to: {})

    Hash of parameters for the API - see REST API docs

Returns:

  • (Hash)

    See Pusher API docs

Raises:

  • (Pusher::Error)

    Unsuccessful response - see the error message

  • (Pusher::HTTPError)

    Error raised inside http client. The original error is wrapped in error.original_error



249
250
251
# File 'lib/pusher/client.rb', line 249

def channels(params = {})
  get('/channels', params)
end

#cluster=(cluster) ⇒ Object



138
139
140
# File 'lib/pusher/client.rb', line 138

def cluster=(cluster)
  @host = "api-#{cluster}.pusher.com"
end

#em_http_client(uri) ⇒ Object



396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/pusher/client.rb', line 396

def em_http_client(uri)
  begin
    unless defined?(EventMachine) && EventMachine.reactor_running?
      raise Error, "In order to use async calling you must be running inside an eventmachine loop"
    end
    require 'em-http' unless defined?(EventMachine::HttpRequest)

    connection_opts = {
      :connect_timeout => @connect_timeout,
      :inactivity_timeout => @receive_timeout,
    }

    if defined?(@proxy)
      proxy_opts = {
        :host => @proxy[:host],
        :port => @proxy[:port]
      }
      if @proxy[:user]
        proxy_opts[:authorization] = [@proxy[:user], @proxy[:password]]
      end
      connection_opts[:proxy] = proxy_opts
    end

    EventMachine::HttpRequest.new(uri, connection_opts)
  end
end

#encrypted=(boolean) ⇒ Object

Configure whether Pusher API calls should be made over SSL (default false)

Examples:

Pusher.encrypted = true


128
129
130
131
132
# File 'lib/pusher/client.rb', line 128

def encrypted=(boolean)
  @scheme = boolean ? 'https' : 'http'
  # Configure port if it hasn't already been configured
  @port = boolean ? 443 : 80
end

#encrypted?Boolean

Returns:

  • (Boolean)


134
135
136
# File 'lib/pusher/client.rb', line 134

def encrypted?
  @scheme == 'https'
end

#encryption_master_key_base64=(s) ⇒ Object

Set an encryption_master_key to use with private-encrypted channels from a base64 encoded string.



150
151
152
# File 'lib/pusher/client.rb', line 150

def encryption_master_key_base64=(s)
  @encryption_master_key = s ? Base64.decode64(s) : nil
end

#get(path, params = {}) ⇒ Hash

GET arbitrary REST API resource using a synchronous http client. All request signing is handled automatically.

Examples:

begin
  Pusher.get('/channels', filter_by_prefix: 'private-')
rescue Pusher::Error => e
  # Handle error
end

Parameters:

  • path (String)

    Path excluding /apps/APP_ID

  • params (Hash) (defaults to: {})

    API params (see pusher.com/docs/rest_api)

Returns:

  • (Hash)

    See Pusher API docs

Raises:

  • (Pusher::Error)

    Unsuccessful response - see the error message

  • (Pusher::HTTPError)

    Error raised inside http client. The original error is wrapped in error.original_error



178
179
180
# File 'lib/pusher/client.rb', line 178

def get(path, params = {})
  resource(path).get(params)
end

#get_async(path, params = {}) ⇒ Object

GET arbitrary REST API resource using an asynchronous http client. All request signing is handled automatically.

When the eventmachine reactor is running, the em-http-request gem is used; otherwise an async request is made using httpclient. See README for details and examples.

Parameters:

  • path (String)

    Path excluding /apps/APP_ID

  • params (Hash) (defaults to: {})

    API params (see pusher.com/docs/rest_api)

Returns:

  • Either an EM::DefaultDeferrable or a HTTPClient::Connection



194
195
196
# File 'lib/pusher/client.rb', line 194

def get_async(path, params = {})
  resource(path).get_async(params)
end

#notification_clientObject



333
334
335
336
# File 'lib/pusher/client.rb', line 333

def notification_client
  @notification_client ||=
    NativeNotification::Client.new(@app_id, @notification_host, @notification_scheme, self)
end

#notify(interests, data = {}) ⇒ Hash

Send a push notification

POST /apps//notifications

Parameters:

  • interests (Array)

    An array of interests

  • message (String)

    Message to send

  • options (Hash)

    Additional platform specific options

Returns:

  • (Hash)


348
349
350
# File 'lib/pusher/client.rb', line 348

def notify(interests, data = {})
  notification_client.notify(interests, data)
end

#post(path, params = {}) ⇒ Object

POST arbitrary REST API resource using a synchronous http client. Works identially to get method, but posts params as JSON in post body.



200
201
202
# File 'lib/pusher/client.rb', line 200

def post(path, params = {})
  resource(path).post(params)
end

#post_async(path, params = {}) ⇒ Object

POST arbitrary REST API resource using an asynchronous http client. Works identially to get_async method, but posts params as JSON in post body.



207
208
209
# File 'lib/pusher/client.rb', line 207

def post_async(path, params = {})
  resource(path).post_async(params)
end

#resource(path) ⇒ Object

INTERACT WITH THE API ##



156
157
158
# File 'lib/pusher/client.rb', line 156

def resource(path)
  Resource.new(self, path)
end

#sync_http_clientObject



382
383
384
385
386
387
388
389
390
391
392
393
# File 'lib/pusher/client.rb', line 382

def sync_http_client
  @client ||= begin
    require 'httpclient'

    HTTPClient.new(@http_proxy).tap do |c|
      c.connect_timeout = @connect_timeout
      c.send_timeout = @send_timeout
      c.receive_timeout = @receive_timeout
      c.keep_alive_timeout = @keep_alive_timeout
    end
  end
end

#timeout=(value) ⇒ Object

Convenience method to set all timeouts to the same value (in seconds). For more control, use the individual writers.



144
145
146
# File 'lib/pusher/client.rb', line 144

def timeout=(value)
  @connect_timeout, @send_timeout, @receive_timeout = value, value, value
end

#trigger(channels, event_name, data, params = {}) ⇒ Hash

Trigger an event on one or more channels

POST /apps//events

Parameters:

  • channels (String or Array)

    1-10 channel names

  • event_name (String)
  • data (Object)

    Event data to be triggered in javascript. Objects other than strings will be converted to JSON

  • params (Hash) (defaults to: {})

    Additional parameters to send to api, e.g socket_id

Returns:

  • (Hash)

    See Pusher API docs

Raises:

  • (Pusher::Error)

    Unsuccessful response - see the error message

  • (Pusher::HTTPError)

    Error raised inside http client. The original error is wrapped in error.original_error



300
301
302
# File 'lib/pusher/client.rb', line 300

def trigger(channels, event_name, data, params = {})
  post('/events', trigger_params(channels, event_name, data, params))
end

#trigger_async(channels, event_name, data, params = {}) ⇒ Object

Trigger an event on one or more channels asynchronously. For parameters see #trigger



322
323
324
# File 'lib/pusher/client.rb', line 322

def trigger_async(channels, event_name, data, params = {})
  post_async('/events', trigger_params(channels, event_name, data, params))
end

#trigger_batch(*events) ⇒ Hash

Trigger multiple events at the same time

POST /apps//batch_events

Parameters:

  • events (Array)

    List of events to publish

Returns:

  • (Hash)

    See Pusher API docs

Raises:

  • (Pusher::Error)

    Unsuccessful response - see the error message

  • (Pusher::HTTPError)

    Error raised inside http client. The original error is wrapped in error.original_error



315
316
317
# File 'lib/pusher/client.rb', line 315

def trigger_batch(*events)
  post('/batch_events', trigger_batch_params(events.flatten))
end

#trigger_batch_async(*events) ⇒ Object

Trigger multiple events asynchronously. For parameters see #trigger_batch



329
330
331
# File 'lib/pusher/client.rb', line 329

def trigger_batch_async(*events)
  post_async('/batch_events', trigger_batch_params(events.flatten))
end

#url(path = nil) ⇒ Object

Raises:



83
84
85
86
87
88
89
90
91
# File 'lib/pusher/client.rb', line 83

def url(path = nil)
  raise ConfigurationError, :app_id unless @app_id
  URI::Generic.build({
    :scheme => @scheme,
    :host => @host,
    :port => @port,
    :path => "/apps/#{@app_id}#{path}"
  })
end

#url=(url) ⇒ Object

Configure Pusher connection by providing a url rather than specifying scheme, key, secret, and app_id separately.

Examples:

Pusher.url = http://KEY:[email protected]/apps/APP_ID


99
100
101
102
103
104
105
106
107
# File 'lib/pusher/client.rb', line 99

def url=(url)
  uri = URI.parse(url)
  @scheme = uri.scheme
  @app_id = uri.path.split('/').last
  @key    = uri.user
  @secret = uri.password
  @host   = uri.host
  @port   = uri.port
end

#webhook(request) ⇒ Object

Convenience method for creating a new WebHook instance for validating and extracting info from a received WebHook

Parameters:

  • request (Rack::Request)

    Either a Rack::Request or a Hash containing :key, :signature, :body, and optionally :content_type.



218
219
220
# File 'lib/pusher/client.rb', line 218

def webhook(request)
  WebHook.new(request, self)
end