API Pusher

Pusher

 

Pusher it's an easy and reliable platform with nice features based on WebSocket protocol: flexible pub/sub messaging, live user lists (presence), authentication...

 

Pusher WebSocket API is 7.

 

Data is sent bi-directionally over a WebSocket as text data containing UTF8 encoded JSON (Binary WebSocket frames are not supported).

 

You can call Ping method to test connection to the server. Essentially any messages received from the other party are considered to mean that the connection is alive. In the absence of any messages, either party may check that the other side is responding by sending a ping message, to which the other party should respond with a pong.

 

Before you connect, you must complete the following fields:

 


Pusher.Cluster := 'eu'; // cluster where is located your pusher account
Pusher.Key := '9c3b7ef25qe97a00116c'; // your pusher api key
Pusher.Name := 'js'; // optional, name of your application
Pusher.Version := '4.1';  // optional, version of your application
Pusher.TLS := True; // if encrypted, set to True
Pusher.Secret := '2dc792e1916ac49e6b3f'; // pusher secret string (needed for privateand absence channels)

 

Important

Pusher requires that websocket client connects to a URL using previous fields (key, cluster...), these fields are used to build the url and this is done when you assign the client in pusher component. So, to be sure that URL is built correctly, set the client after you have fill the pusher configuration fields. Find below pseudo-code:

 

// configure pusher fields

pusher.cluster = ...

pusher.key = ...

// set client

pusher.client = websocket client

// start connection

websocket client.Active = true;

 

 

After a successful connection, OnPusherConnect event is raised and you get following fields:

 

 

In case of error, OnPusherError will be raised, and information about error provided. An error may be sent from Pusher in response to invalid authentication, an invalid command, etc.

 

4000-4099

 

Indicates an error resulting in the connection being closed by Pusher, and that attempting to reconnect using the same parameters will not succeed.

 

4000: Application only accepts SSL connections, reconnect using wss://

4001: Application does not exist

4003: Application disabled

4004: Application is over connection quota

4005: Path not found

4006: Invalid version string format

4007: Unsupported protocol version

4008: No protocol version supplied

 

4100-4199

 

Indicates an error resulting in the connection being closed by Pusher, and that the client may reconnect after 1s or more.

 

4100: Over capacity

 

4200-4299

 

Indicates an error resulting in the connection being closed by Pusher, and that the client may reconnect immediately.

 

4200: Generic reconnect immediately

4201: Pong reply not received: ping was sent to the client, but no reply was received - see ping and pong messages

4202: Closed after inactivity: The client has been inactive for a long time (currently 24 hours) and client does not support ping. Please upgrade to a newer WebSocket draft or implement version 5 or above of this protocol.

 

4300-4399

 

Any other type of error.

 

4301: Client event rejected due to rate limit

 

Channels

Channels are a fundamental concept in Pusher. Each application has a number of channels, and each client can choose which channels it subscribes to.

 

Channels provide:

 

 

It's strongly recommended that channels are used to filter your data and that it is not achieved using events. This is because all events published to a channel are sent to all subscribers, regardless of their event binding.

 

Channels don’t need to be explicitly created and are instantiated on client demand. This means that creating a channel is easy. Just tell a client to subscribe to it.

 

There are 3 types of channels:

 

 

Public Channels

Public channels should be used for publicly accessible data as they do not require any form authorisation in order to be subscribed to.

 

You can subscribe and unsubscribe from channels at any time. There’s no need to wait for the Pusher to finish connecting first.

 

Example: subscribe to channel "my-channel".

 


Delphi
APIPusher.Subscribe('my-channel');

 

If you are subscribed successfully OnPusherSubscribe event will be raised, if there is an error you will get a message in OnPusherError event.

 

All messages from the subscribed channel will be received OnPusherEvent event.

 

When Publish method is called and the channel is Public, the component instead of use the WebSocket protocol, uses the HTTP protocol and calls the method TriggerEvent (publishi is not allowed using websocket protocol).

Private Channels

Requires Indy 10.5.7 or later

 

Private channels should be used when access to the channel needs to be restricted in some way. In order for a user to subscribe to a private channel permission must be authorised.

 

Example: subscribe to channel "my-private-channel".

 


Delphi
APIPusher.Subscribe('my-private-channel', pscPrivateChannel);

 

If you are subscribed successfully OnPusherSubscribe event will be raised, if there is an error you will get a message in OnPusherError event.

 

All messages from the subscribed channel will be received OnPusherEvent event.

 

Presence Channels

Requires Indy 10.5.7 or later

 

Presence channels build on the security of Private channels and expose the additional feature of an awareness of who is subscribed to that channel. This makes it extremely easy to build chat room and “who’s online” type functionality to your application. Think chat rooms, collaborators on a document, people viewing the same web page, competitors in a game, that kind of thing.

 

Presence channels are subscribed to from the client API in the same way as private channels but the channel name must be prefixed with presence-. As with private channels an HTTP Request is made to a configurable authentication URL to determine if the current user has permissions to access the channel.

 

Information on users subscribing to, and unsubscribing from a channel can then be accessed by binding to events on the presence channel and the current state of users subscribed to the channel is available via the channel.members property.

 

Example: subscribe to channel "my-presence-channel".

 


APIPusher.Subscribe('my-presence-channel', pscPresenceChannel, 
  '{"user_id":"John_Smith","user_info":{"name":"John Smith"}}')

 

If you are subscribed successfully OnPusherSubscribe event will be raised, if there is an error you will get a message in OnPusherError event.

 

All messages from the subscribed channel will be received OnPusherEvent event.

 

 

Cache Channels

A cache channel remembers the last triggered event, and sends this as the first event to new subscribers.

 

When an event is triggered on a cache channel, Pusher Channels caches this event, and when a client subscribes to a cache channel, if a cached value exists, this is sent to the client as the first event on that channel. This behavior helps developers to provide the initial state without adding additional logic to fetch it from else where.

 

The following Cache Channels are supported:

 

 

Example: subscribe to public cache channel "my-cache-channel".

 


APIPusher.Subscribe('my-cache-channel', pscCacheChannel);

If you are subscribed successfully OnPusherSubscribe event will be raised, if there is an error you will get a message in OnPusherError event.

 

All messages from the subscribed channel will be received OnPusherEvent event.

 

Publish Messages

Not only you can receive messages from subscribed channels, but you can also send messages to other subscribed users.

Call method Publish to send a message to all subscribed users of channel.

 

Example: send an event to all subscribed users of "my-channel'

 


APIPusher.Publish('my-event', 'my-channel');

 

Publish no more than 10 messages per second per client (connection). Any events triggered above this rate limit will be rejected by Pusher API. This is not a system issue, it is a client issue. 100 clients in a channel sending messages at this rate would each also have to be processing 1,000 messages per second! Whilst some modern browsers might be able to handle this it’s most probably not a good idea.

 

REST API

The API is hosted at http://api-CLUSTER.pusher.com , where CLUSTER is replaced with your own apps cluster (for instance, eu).

 

HTTP status codes are used to indicate the success or otherwise of requests. The following status are common:

 

200 Successful request. Body will contain a JSON hash of response data

400 Error: details in response body

401 Authentication error: response body will contain an explanation

403 Forbidden: app disabled or over message quota

 

The following REST API functions have been implemented.

 

Function Description
TriggerEvent triggers a new event on the specified channel.
GetChannels provide a list of all channels active.
GetChannel provide information of a channel.
GetUsers provide a list of all users connected to a channel.

 

 

Custom Authentication

Pusher only allow subscribe to private or presence channels, if the connection provides an authentication token, this allows to restrict the access.

You can build your own Authentication flow, using OnPusherAuthentication event, this event is called before the subscription message is signed with the secret key provided by Pusher. This event has 2 parameters a request authentication with fields like SocketId, channel name... which can be used by your own authentication server to authenticate or not the request. Find below a screenshot which shows the pusher authentication flow

 

 

When a client connects to the pusher server, it sends the Key provided by pusher and the server returns an identification id (socket_id).

 

When a client subscribes to a private (or presence) channel, the sgcWebSockets client uses the Secret Key provided by pusher to create a signature which is included in the subscription message. Using the OnPusherAutentication event, you can capture the fields required to sign the message, implement your own authentication methods and if successful, return the signature and this signature will be included in the subscription message and sent to the server.

 

Example:


oClient := TsgcWebSocketClient.Create(nil);
oPusher := TsgcWSAPI_Pusher.Create(nil);
oPusher.Client := oClient;
oPusher.Cluster := 'eu'; 
Pusher.Name := 'js';
Pusher.Version := '4.1';
Pusher.TLS := True;
Pusher.Key := '9c3b7ef25qe97a00116c'; 
Pusher.Secret := ''; // the secret key is not known by the client, only by the authentication module
 
oPusher.OnPusherAuthentication := OnPusherAuthenticationEvent;
 
procedure OnPusherAuthenticationEvent(Sender: TObject; AuthRequest: TsgcWSPusherRequestAuthentication; 
  AuthResponse: TsgcWSPusherResponseAuthentication);
begin
  // if the authentication request is succesful return the signature
  if CustomAuthentication(AuthRequest.Channel, AuthRequest.SocketID) then
    AuthResponse.Signature := GetCustomAuthenticationSignature;
end;

The format of the signature is:

 

Private channels: key:HMAC256(SocketID, ChannelName)

Presence channels: key: HMAC256(SocketID, ChannelName, Data)