• Stars
    star
    659
  • Rank 68,396 (Top 2 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 15 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Ruby library for Pusher Channels HTTP API

Gem for Pusher Channels

This Gem provides a Ruby interface to the Pusher HTTP API for Pusher Channels.

Build Status Gem Gem

Supported Platforms

  • Ruby - supports Ruby 2.6 or greater.

Installation and Configuration

Add pusher to your Gemfile, and then run bundle install

gem 'pusher'

or install via gem

gem install pusher

After registering at Pusher, configure your Channels app with the security credentials.

Instantiating a Pusher Channels client

Creating a new Pusher Channels client can be done as follows.

require 'pusher'

pusher = Pusher::Client.new(
  app_id: 'your-app-id',
  key: 'your-app-key',
  secret: 'your-app-secret',
  cluster: 'your-app-cluster',
  use_tls: true
)

The cluster value will set the host to api-<cluster>.pusher.com. The use_tls value is optional and defaults to true. It will set the scheme and port. A custom port value takes precendence over use_tls.

If you want to set a custom host value for your client then you can do so when instantiating a Pusher Channels client like so:

require 'pusher'

pusher = Pusher::Client.new(
  app_id: 'your-app-id',
  key: 'your-app-key',
  secret: 'your-app-secret',
  host: 'your-app-host'
)

If you pass both host and cluster options, the host will take precendence and cluster will be ignored.

Finally, if you have the configuration set in an PUSHER_URL environment variable, you can use:

pusher = Pusher::Client.from_env

Global configuration

The library can also be configured globally on the Pusher class.

Pusher.app_id = 'your-app-id'
Pusher.key = 'your-app-key'
Pusher.secret = 'your-app-secret'
Pusher.cluster = 'your-app-cluster'

Global configuration will automatically be set from the PUSHER_URL environment variable if it exists. This should be in the form http://KEY:SECRET@HOST/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)'

By default API requests are made over HTTPS. HTTP can be used by setting use_tls to false. Issuing this command is going to reset port value if it was previously specified.

Pusher.use_tls = false

As of version 0.12, SSL certificates are verified when using the synchronous http client. If you need to disable this behaviour for any reason use:

Pusher.default_client.sync_http_client.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE

Interacting with the Channels HTTP API

The pusher gem contains a number of helpers for interacting with the API. 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.trigger('a_channel', 'an_event', :some => 'data')
rescue Pusher::Error => e
  # (Pusher::AuthenticationError, Pusher::HTTPError, or Pusher::Error)
end

Logging

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 published to one or more channels (limited to 10) in one API call:

pusher.trigger('channel', 'event', foo: 'bar')
pusher.trigger(['channel_1', 'channel_2'], 'event_name', foo: 'bar')

An optional fourth argument may be used to send additional parameters to the API, for example to exclude a single connection from receiving the event.

pusher.trigger('channel', 'event', {foo: 'bar'}, {socket_id: '123.456'})

Batches

It's also possible to send multiple events with a single API call (max 10 events per call on multi-tenant clusters):

pusher.trigger_batch([
  {channel: 'channel_1', name: 'event_name', data: { foo: 'bar' }},
  {channel: 'channel_1', name: 'event_name', data: { hello: 'world' }}
])

Deprecated publisher API

Most examples and documentation will refer to the following syntax for triggering an event:

Pusher['a_channel'].trigger('an_event', :some => 'data')

This will continue to work, but has been replaced by pusher.trigger which supports one or multiple channels.

Getting information about the channels in your Pusher Channels app

This gem provides methods for accessing information from the Channels HTTP API. The documentation also shows an example of the responses from each of the API endpoints.

The following methods are provided by the gem.

  • pusher.channel_info('channel_name', {info:"user_count,subscription_count"}) returns a hash describing the state of the channel(docs).

  • pusher.channel_users('presence-channel_name') returns a list of all the users subscribed to the channel (only for Presence Channels) (docs).

  • pusher.channels({filter_by_prefix: 'presence-', info: 'user_count'}) returns a hash of occupied channels (optionally filtered by prefix, f.i. presence-), and optionally attributes for these channels (docs).

Asynchronous requests

There are two main reasons for using the _async methods:

  • In a web application where the response from the Channels HTTP API is not used, but you'd like to avoid a blocking call in the request-response cycle
  • Your application is running in an event loop and you need to avoid blocking the reactor

Asynchronous calls are supported either by using an event loop (eventmachine, preferred), or via a thread.

The following methods are available (in each case the calling interface matches the non-async version):

  • pusher.get_async
  • pusher.post_async
  • pusher.trigger_async

It is of course also possible to make calls to the Channels HTTP API via a job queue. This approach is recommended if you're sending a large number of events.

With EventMachine

  • Add the em-http-request gem to your Gemfile (it's not a gem dependency).
  • Run the EventMachine reactor (either using EM.run or by running inside an evented server such as Thin).

The _async methods return an EM::Deferrable which you can bind callbacks to:

pusher.get_async("/channels").callback { |response|
  # use reponse[:channels]
}.errback { |error|
  # error is an instance of Pusher::Error
}

A HTTP error or an error response from Channels will cause the errback to be called with an appropriate error object.

Without EventMachine

If the EventMachine reactor is not running, async requests will be made using threads (managed by the httpclient gem).

An HTTPClient::Connection object is returned immediately which can be interrogated to discover the status of the request. The usual response checking and processing is not done when the request completes, and frankly this method is most useful when you're not interested in waiting for the response.

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 https://pusher.com/docs/channels/server_api/authenticating-users

Private channels

pusher.authenticate('private-my_channel', params[:socket_id])

Presence channels

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:

pusher.authenticate('presence-my_channel', params[:socket_id],
  user_id: 'user_id',
  user_info: {} # optional
)

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

End-to-end encryption

This library supports end-to-end encrypted channels. This means that only you and your connected clients will be able to read your messages. Pusher cannot decrypt them. You can enable this feature by following these steps:

  1. Add the rbnacl gem to your Gemfile (it's not a gem dependency).

  2. Install Libsodium, which we rely on to do the heavy lifting. Follow the installation instructions for your platform.

  3. Encrypted channel subscriptions must be authenticated in the exact same way as private channels. You should therefore create an authentication endpoint on your server.

  4. Next, generate your 32 byte master encryption key, encode it as base64 and pass it to the Pusher constructor.

    This is secret and you should never share this with anyone. Not even Pusher.

    openssl rand -base64 32
    pusher = new Pusher::Client.new({
      app_id: 'your-app-id',
      key: 'your-app-key',
      secret: 'your-app-secret',
      cluster: 'your-app-cluster',
      use_tls: true
      encryption_master_key_base64: '<KEY GENERATED BY PREVIOUS COMMAND>',
    });
  5. Channels where you wish to use end-to-end encryption should be prefixed with private-encrypted-.

  6. Subscribe to these channels in your client, and you're done! You can verify it is working by checking out the debug console on the https://dashboard.pusher.com/ and seeing the scrambled ciphertext.

Important note: This will not encrypt messages on channels that are not prefixed by private-encrypted-.

Limitation: you cannot trigger a single event on multiple channels in a call to trigger, e.g.

pusher.trigger(
  ['channel-1', 'private-encrypted-channel-2'],
  'test_event',
  { message: 'hello world' },
)

Rationale: the methods in this library map directly to individual Channels HTTP API requests. If we allowed triggering a single event on multiple channels (some encrypted, some unencrypted), then it would require two API requests: one where the event is encrypted to the encrypted channels, and one where the event is unencrypted for unencrypted channels.

More Repositories

1

pusher-js

Pusher Javascript library
JavaScript
1,970
star
2

atom-pair

An Atom package that allows for epic pair programming
JavaScript
1,454
star
3

pusher-http-php

PHP library for interacting with the Pusher Channels HTTP API
PHP
1,355
star
4

libPusher

An Objective-C interface to Pusher Channels
C
409
star
5

pusher-http-laravel

[DEPRECATED] A Pusher Channels bridge for Laravel
PHP
405
star
6

pusher-http-python

Pusher Channels HTTP API library for Python
Python
368
star
7

k8s-spot-rescheduler

Tries to move K8s Pods from on-demand to spot instances
Go
313
star
8

pusher-websocket-java

Pusher Channels client library for Java targeting general Java and Android
Java
302
star
9

pusher-websocket-swift

Pusher Channels websocket library for Swift
Swift
267
star
10

build-a-slack-clone-with-react-and-pusher-chatkit

In this tutorial, you'll learn how to build a chat app with React, complete with typing indicators, online status, and more.
JavaScript
235
star
11

pusher-angular

Pusher Angular Library | owner=@leesio
JavaScript
233
star
12

pusher-http-go

Pusher Channels HTTP API library for Go
Go
196
star
13

NWWebSocket

A WebSocket client written in Swift, using the Network framework from Apple.
Swift
123
star
14

k8s-spot-termination-handler

Monitors AWS for spot termination notices when run on spot instances and shuts down gracefully
Makefile
118
star
15

go-interface-fuzzer

Automate the boilerplate of fuzz testing Go interfaces | owner: @willsewell
Go
110
star
16

pusher-http-dotnet

.NET library for interacting with the Pusher HTTP API
C#
109
star
17

pusher-websocket-dotnet

Pusher Channels Client Library for .NET
C#
107
star
18

k8s-auth-example

Example Kubernetes Authentication helper. Performs OIDC login and configures Kubectl appropriately.
Go
107
star
19

faros

Faros is a CRD based GitOps controller
Go
99
star
20

backbone-todo-app

JavaScript
92
star
21

chatkit-client-js

JavaScript client SDK for Pusher Chatkit
JavaScript
90
star
22

pusher-channels-flutter

Pusher Channels client library for Flutter targeting IOS, Android, and WEB
Dart
72
star
23

quack

In-Cluster templating for Kubernetes manifests
Go
70
star
24

pusher-websocket-react-native

React Native official Pusher SDK
TypeScript
61
star
25

websockets-from-scratch-tutorial

Tutorial that shows how to implement a websocket server using Ruby's built-in libs
Ruby
60
star
26

push-notifications-php

Pusher Beams PHP Server SDK
PHP
56
star
27

backpusher

JavaScript
54
star
28

chatkit-android

Android client SDK for Pusher Chatkit
Kotlin
53
star
29

django-pusherable

Real time notification when an object view is accessed via Pusher
Python
52
star
30

cli

A CLI for Pusher (beta)
Go
51
star
31

notify

Ruby
51
star
32

k8s-spot-price-monitor

Monitors the spot prices of instances in a Kubernetes cluster and exposes them as prometheus metrics
Python
44
star
33

chatkit-command-line-chat

A CLI chat, built with Chatkit
JavaScript
41
star
34

pusher-http-java

Java client to interact with the Pusher HTTP API
Java
40
star
35

chatkit-swift

Swift SDK for Pusher Chatkit
Swift
40
star
36

push-notifications-web

Beams Browser notifications
JavaScript
39
star
37

electron-desktop-chat

A desktop chat built with React, React Desktop and Electron
JavaScript
38
star
38

crank

Process slow restarter
Go
37
star
39

pusher-websocket-android

Library built on top of pusher-websocket-java for Android. Want Push Notifications? Check out Pusher Beams!
Java
35
star
40

chameleon

A collection of front-end UI components used across Pusher ✨
CSS
35
star
41

chatkit-server-php

PHP SDK for Pusher Chatkit
PHP
35
star
42

push-notifications-swift

Swift SDK for the Pusher Beams product:
Swift
34
star
43

cide

Isolated test runner with Docker
Ruby
33
star
44

pusher-phonegap-android

JavaScript
30
star
45

push-notifications-python

Pusher Beams Python Server SDK
Python
30
star
46

pusher-websocket-unity

Pusher Channels Unity Client Library
C#
27
star
47

hacktoberfest

24
star
48

laravel-chat

PHP
23
star
49

push-notifications-android

Android SDK for Pusher Beams
Kotlin
21
star
50

push-notifications-node

Pusher Beams Node.js Server SDK
JavaScript
20
star
51

pusher-test-iOS

iOS app for developers to test connections to Pusher
Objective-C
19
star
52

push-notifications-ruby

Pusher Beams Ruby Server SDK
Ruby
18
star
53

chatkit-server-node

Node.js SDK for Pusher Chatkit
TypeScript
16
star
54

rack-headers_filter

Remove untrusted headers from Rack requests | owner=@zimbatm
Ruby
15
star
55

pusher-test-android

Test and diagnostic app for Android, based on pusher-java-client
Java
14
star
56

pusher-realtime-tfl-cameras

Realtime TfL Traffic Camera API, powered by Pusher
JavaScript
14
star
57

buddha

Buddha command execution and health checking | owner: @willsewell
Go
14
star
58

chatkit-server-go

Chatkit server SDK for Golang
Go
13
star
59

pusher-channels-auth-example

A simple server exposing a pusher auth endpoint
JavaScript
13
star
60

pusher-platform-js

Pusher Platform client library for browsers and react native
TypeScript
13
star
61

stronghold

[DEPRECATED] A configuration service | owner: @willsewell
Haskell
12
star
62

sample-chatroom-ios-chatkit

How to make an iOS Chatroom app using Swift and Chatkit
PHP
12
star
63

pusher-twilio-example

CSS
12
star
64

chatkit-server-ruby

Ruby server SDK for Chatkit
Ruby
12
star
65

prom-rule-reloader

Watches configmaps for prometheus rules and keeps prometheus in-sync
Go
12
star
66

electron-desktop-starter-template

JavaScript
11
star
67

realtime-visitor-tracker

Realtime location aware visitor tracker for a web site or application
PHP
11
star
68

push-notifications-server-java

Pusher Beams Java Server SDK
Kotlin
10
star
69

android-slack-clone

Android chat application, built with Chatkit
Kotlin
10
star
70

filtrand

JavaScript
10
star
71

vault

Front-end pattern library
Ruby
9
star
72

git-store

Go git abstraction for use in Kubernetes Controllers
Go
9
star
73

pusher-platform-android

Pusher Platform SDK for Android
Kotlin
9
star
74

push-notifications-go

Pusher Beams Go Server SDK
Go
9
star
75

pusher-platform-swift

Swift SDK for Pusher platform products
Swift
8
star
76

realtime_survey_complete

JavaScript
8
star
77

docs

The all new Pusher docs, powered by @11ty and @vercel
CSS
8
star
78

push-notifications-server-swift

Pusher Beams Swift Server SDK
Swift
8
star
79

pusher-python-rest

Python client to interact with the Pusher REST API. DEPRECATED in favour of https://github.com/pusher/pusher-http-python
Python
8
star
80

real-time-progress-bar-tutorial

Used inthe realtime progress bar tutorial blog post - http://blog.pusher.com
JavaScript
7
star
81

pusher-channels-chunking-example

HTML
7
star
82

pusher-http-swift

Swift library for interacting with the Pusher Channels HTTP API
Swift
7
star
83

feeds-client-js

JS client for Pusher Feeds
JavaScript
6
star
84

pusher-test

Simple website which allows manual testing of pusher-js versions
JavaScript
6
star
85

java-websocket

A fork of https://github.com/TooTallNate/Java-WebSocket | owner=@zmarkan
HTML
6
star
86

navarchos

Node replacing controller
Go
5
star
87

bridge-troll

A Troll that ensures files don't change
Go
5
star
88

realtime-notifications-tutorial

Create realtime notifications in minutes, not days =)
4
star
89

pusher-socket-protocol

Protocol for pusher sockets
HTML
4
star
90

icanhazissues

Github issues kanban
JavaScript
4
star
91

textsync-server-node

[DEPRECATED] A node.js library to simplify token generation for TextSync authorization endpoints.
TypeScript
4
star
92

pusher_tutorial_realtimeresults

JavaScript
3
star
93

pusher-js-diagnostics

JavaScript
3
star
94

react-rest-api-tutorial

Accompanying tutorial for consuming RESTful APIs in React
CSS
3
star
95

feeds-server-node

The server Node SDK for Pusher Feeds
JavaScript
3
star
96

testing

Configuration for Pusher's Open Source Prow instance
Go
3
star
97

spacegame_example

Simple example of a space game using node.js and Pusher
JavaScript
3
star
98

chatkit-quickstart-swift

A project to get started with Chatkit.
Swift
2
star
99

pusher-whos-in

Ruby
2
star
100

healthz-proxy

healthz proxy for zero downtime rollouts
Go
2
star