Permalink
Browse files

Merge branch 'generic_interface'

  • Loading branch information...
2 parents 7584407 + 15417b8 commit 78ccd6cec0c7a1c40b288ce15d9fa57b7f18a232 @mloughran mloughran committed Nov 13, 2012
Showing with 629 additions and 396 deletions.
  1. +106 −39 README.md
  2. +7 −19 lib/pusher.rb
  3. +17 −29 lib/pusher/channel.rb
  4. +172 −31 lib/pusher/client.rb
  5. +47 −0 lib/pusher/query_encoder.rb
  6. +28 −95 lib/pusher/request.rb
  7. +36 −0 lib/pusher/resource.rb
  8. +13 −167 spec/channel_spec.rb
  9. +195 −15 spec/client_spec.rb
  10. +8 −1 spec/spec_helper.rb
View
@@ -3,84 +3,151 @@ Pusher gem
[![Build Status](https://secure.travis-ci.org/pusher/pusher-gem.png?branch=master)](http://travis-ci.org/pusher/pusher-gem)
-Getting started
----------------
+## Configuration
-After registering at <http://pusher.com> configure your app with the security credentials
+After registering at <http://pusher.com> configure your app with the security credentials.
+
+### Global
+
+The most standard way of configuring Pusher is to do it globally on the Pusher class.
Pusher.app_id = 'your-pusher-app-id'
Pusher.key = 'your-pusher-key'
Pusher.secret = 'your-pusher-secret'
-If you need to request over HTTP proxy, then you can configure the {Pusher#http_proxy}.
+Global configuration will automatically be set from the `PUSHER_URL` environment variable if it exists. This should be in the form `http://KEY:SECRET@api.pusherapp.com/apps/APP_ID`. On Heroku this environment variable will already be set.
+
+If you need to make requests via a HTTP proxy then it can be configured
Pusher.http_proxy = 'http://(user):(password)@(host):(port)'
-Trigger an event with {Pusher::Channel#trigger!}
+By default API requests are made over HTTP. HTTPS can be used by setting
+
+ Pusher.encrypted = true
+
+### Instantiating a Pusher client
+
+Sometimes you may have multiple sets of API keys, or want different configuration in different parts of your application. In these scenarios, a pusher `client` may be configured:
+
+ pusher_client = Pusher.new({
+ app_id: 'your-pusher-app-id',
+ key: 'your-pusher-key',
+ secret: 'your-pusher-secret'
+ })
+
+This `client` will have all the functionality listed on the main Pusher class (which proxies to a client internally).
+
- Pusher['a_channel'].trigger!('an_event', {:some => 'data'})
-Handle errors by rescuing `Pusher::Error` (all Pusher errors are descendants of this error)
+## Interacting with the Pusher service
+
+The Pusher gem contains a number of helpers for interacting with the service. As a general rule, the library adheres to a set of conventions that we have aimed to make universal.
+
+### Handling errors
+
+Handle errors by rescuing `Pusher::Error` (all errors are descendants of this error)
begin
- Pusher['a_channel'].trigger!('an_event', {:some => 'data'})
+ Pusher.trigger('a_channel', 'an_event', {:some => 'data'})
rescue Pusher::Error => e
# (Pusher::AuthenticationError, Pusher::HTTPError, or Pusher::Error)
end
-Optionally a socket id may be provided. This will exclude the event from being triggered on this socket id (see <http://pusher.com/docs/publisher_api_guide/publisher_excluding_recipients> for more info).
+### Logging
- Pusher['a_channel'].trigger!('an_event', {:some => 'data'}, socket_id)
+Errors are logged to `Pusher.logger`. It will by default log at info level to STDOUT using `Logger` from the standard library, however you can assign any logger:
+
+ Pusher.logger = Rails.logger
+
+### Publishing events
+
+An event can be sent to Pusher in in the following ways:
+
+ # on the Pusher class
+ Pusher.trigger('channel_name', 'event_name', {some: 'data'})
+ Pusher.trigger(['channel_1', 'channel_2'], 'event_name', {some: 'data'})
+
+ # or on a pusher_client
+ pusher_client.trigger(['your_channels'], 'your_event_name', {some: 'data'})
-If you don't need to handle failure cases, then you can simply use the {Pusher::Channel#trigger} method, which will rescue and log any errors for you
+Note: the first `channels` argument can contain multiple channels you'd like your event and data payload to go to. There is a limit of 100 on the number of channels this can contain.
+
+An optional fourth argument of this method can specify a `socket_id` that will be excluded from receiving the event (generally the user where the event originated -- see <http://pusher.com/docs/publisher_api_guide/publisher_excluding_recipients> for more info).
+
+#### Original publisher API
+
+Most examples and documentation will refer to the following syntax for triggering an event:
Pusher['a_channel'].trigger('an_event', {:some => 'data'})
-Logging
--------
+This will continue to work, but will be replaced as the canonical version by `Pusher.trigger` which supports multiple channels.
-Errors are logged to `Pusher.logger`. It will by default use `Logger` from stdlib, however you can assign any logger:
+### Generic requests to the Pusher REST API
- Pusher.logger = Rails.logger
+Aside from triggering events, the REST API also supports a number of operations for querying the state of the system. A reference of the available methods is available at <http://pusher.com/docs/rest_api>.
-Asynchronous triggering
------------------------
+All requests must be signed by using your secret key, which is handled automatically using these methods:
-To avoid blocking in a typical web application, you may wish to use the {Pusher::Channel#trigger_async} method which makes asynchronous API requests. `trigger_async` returns a deferrable which you can optionally bind to with success and failure callbacks.
+ # using the Pusher class
+ Pusher.get('url_without_app_id', params)
+
+ # using a client
+ pusher_client.post('url_without_app_id', params)
+
+Note that you don't need to specify your app_id in the URL, as this is inferred from your credentials. As with the trigger method above, `_async` can be suffixed to the method name to return a deferrable.
+
+### Asynchronous requests
+
+If you are running your application in an evented environment, you may want to use the asynchronous versions of the Pusher API methods to avoid blocking. The convention for this is to add the suffix `_async` to the method, e.g. `trigger_async` or `post_async`.
You need to be running eventmachine to make use of this functionality. This is already the case if, for example, you're deploying to Heroku or using the Thin web server. You will also need to add `em-http-request` to your Gemfile.
- $ gem install em-http-request
+When using an asynchronous version of a method, it will return a deferrable.
- deferrable = Pusher['a_channel'].trigger_async('an_event', {
+ Pusher.trigger_async(['a_channel'], 'an_event', {
:some => 'data'
- }, socket_id)
- deferrable.callback {
+ }, socket_id).callback {
# Do something on success
- }
- deferrable.errback { |error|
+ }.errback { |error|
# error is a instance of Pusher::Error
}
-Private channels
-----------------
-The Pusher Gem also deals with signing requests for authenticated private channels. A quick Rails controller example:
- reponse = Pusher['private-my_channel'].authenticate(params[:socket_id])
- render :json => response
-
-Read more about private channels in [the docs](http://pusher.com/docs/client_api_guide/client_channels#subscribe-private-channels) and under {Pusher::Channel#authenticate}.
+## Authenticating subscription requests
+
+It's possible to use the gem to authenticate subscription requests to private or presence channels. The `authenticate` method is available on a channel object for this purpose and returns a JSON object that can be returned to the client that made the request. More information on this authentication scheme can be found in the docs on <http://pusher.com>
+
+### Private channels
+
+ Pusher['private-my_channel'].authenticate(params[:socket_id])
-WebHooks
---------
+### Presence channels
-See {Pusher::WebHook}
+These work in a very similar way, but require a unique identifier for the user being authenticated, and optionally some attributes that are provided to clients via presence events:
-Developing
-----------
+ Pusher['presence-my_channel'].authenticate(params[:socket_id], {
+ user_id: 'user_id',
+ user_info: {} # optional
+ })
-Use bundler in order to run specs with the correct dependencies.
- bundle
- bundle exec rspec spec/*_spec.rb
+
+## Receiving WebHooks
+
+A WebHook object may be created to validate received WebHooks against your app credentials, and to extract events. It should be created with the `Rack::Request` object (available as `request` in Rails controllers or Sinatra handlers for example).
+
+ webhook = Pusher.webhook(request)
+ if webhook.valid?
+ webhook.events.each do |event|
+ case event["name"]
+ when 'channel_occupied'
+ puts "Channel occupied: #{event["channel"]}"
+ when 'channel_vacated'
+ puts "Channel vacated: #{event["channel"]}"
+ end
+ end
+ render text: 'ok'
+ else
+ render text: 'invalid', status: 401
+ end
View
@@ -7,12 +7,11 @@
# Used for configuring API credentials and creating Channel objects
#
module Pusher
- # All Pusher errors descend from this class so you can easily rescue Pusher
- # errors
+ # All errors descend from this class so they can be easily rescued
#
# @example
# begin
- # Pusher['a_channel'].trigger!('an_event', {:some => 'data'})
+ # Pusher.trigger('channel_name', 'event_name, {:some => 'data'})
# rescue Pusher::Error => e
# # Do something on error
# end
@@ -30,25 +29,12 @@ class << self
def_delegators :default_client, :authentication_token, :url
def_delegators :default_client, :encrypted=, :url=
- def_delegators :default_client, :channels, :channel_info, :trigger
+ def_delegators :default_client, :get, :get_async, :post, :post_async
+ def_delegators :default_client, :channels, :channel_info, :trigger, :trigger_async
+ def_delegators :default_client, :webhook, :channel, :[]
attr_writer :logger
- # Return a channel by name
- #
- # @example
- # Pusher['my-channel']
- # @return [Channel]
- # @raise [ConfigurationError] unless key, secret and app_id have been
- # configured
- def [](channel_name)
- begin
- default_client[channel_name]
- rescue ConfigurationError
- raise ConfigurationError, 'Missing configuration: please check that Pusher.key, Pusher.secret and Pusher.app_id are configured.'
- end
- end
-
def logger
@logger ||= begin
log = Logger.new($stdout)
@@ -70,5 +56,7 @@ def default_client
end
require 'pusher/channel'
+require 'pusher/query_encoder'
require 'pusher/request'
+require 'pusher/resource'
require 'pusher/webhook'
View
@@ -15,6 +15,9 @@ def initialize(base_url, name, client = Pusher)
# Trigger event asynchronously using EventMachine::HttpRequest
#
+ # [Deprecated] This method will be removed in a future gem version. Please
+ # switch to Pusher.trigger_async or Pusher::Client#trigger_async instead
+ #
# @param (see #trigger!)
# @return [EM::DefaultDeferrable]
# Attach a callback to be notified of success (with no parameters).
@@ -24,13 +27,17 @@ def initialize(base_url, name, client = Pusher)
# @raise [Pusher::Error] unless the eventmachine reactor is running. You
# probably want to run your application inside a server such as thin
#
- def trigger_async(event_name, data, socket_id = nil, &block)
- request = construct_event_request(event_name, data, socket_id)
- request.send_async
+ def trigger_async(event_name, data, socket_id = nil)
+ params = {}
+ params[:socket_id] = socket_id if socket_id
+ @client.trigger_async(name, event_name, data, params)
end
# Trigger event
#
+ # [Deprecated] This method will be removed in a future gem version. Please
+ # switch to Pusher.trigger or Pusher::Client#trigger instead
+ #
# @example
# begin
# Pusher['my-channel'].trigger!('an_event', {:some => 'data'})
@@ -47,12 +54,16 @@ def trigger_async(event_name, data, socket_id = nil, &block)
# @raise [Pusher::HTTPError] on any error raised inside Net::HTTP - the original error is available in the original_error attribute
#
def trigger!(event_name, data, socket_id = nil)
- request = construct_event_request(event_name, data, socket_id)
- request.send_sync
+ params = {}
+ params[:socket_id] = socket_id if socket_id
+ @client.trigger(name, event_name, data, params)
end
# Trigger event, catching and logging any errors.
#
+ # [Deprecated] This method will be removed in a future gem version. Please
+ # switch to Pusher.trigger or Pusher::Client#trigger instead
+ #
# @note CAUTION! No exceptions will be raised on failure
# @param (see #trigger!)
#
@@ -71,7 +82,7 @@ def trigger(event_name, data, socket_id = nil)
# @raise [Pusher::HTTPError] on any error raised inside Net::HTTP - the original error is available in the original_error attribute
#
def info(attributes = [])
- @client.channel_info(name, :info => attributes.join(','))
+ @client.get("/channels/#{name}", :info => attributes.join(','))
end
# Compute authentication string required as part of the authentication
@@ -132,28 +143,5 @@ def authenticate(socket_id, custom_data = nil)
r[:channel_data] = custom_data if custom_data
r
end
-
- private
-
- def construct_event_request(event_name, data, socket_id)
- params = {
- :name => event_name,
- }
- params[:socket_id] = socket_id if socket_id
-
- body = case data
- when String
- data
- else
- begin
- MultiJson.encode(data)
- rescue MultiJson::DecodeError => e
- Pusher.logger.error("Could not convert #{data.inspect} into JSON")
- raise e
- end
- end
-
- request = Pusher::Request.new(:post, @uri + 'events', params, body, nil, @client)
- end
end
end
Oops, something went wrong.

0 comments on commit 78ccd6c

Please sign in to comment.