Presence

Creating presence channels allow you to display lists of users who are connected to a given channel in your UI.

This feature requires version 1.6 or above of the Pusher Javascript library.

Overview

Presence channels are an extension of private channels, so read the documentation on those before attempting to add presence to your application.

The difference between private channels and presence channels is that when the Pusher JS library makes the authentication callback to your server, your response will not only contain the signed socket_id, but will also contain a unique identifier for that user (user_id), and an optional set of identifying information (user_info). It is usually possibly to use the primary key of your user as the unique identifier, but it could be their login etc.

Presence channel names must be prefixed with ‘presence-‘.

In Rails (using the Pusher Ruby gem version 0.6 or above), you would change your auth endpoint to look like the following:

Note: you can change the location of the endpoint on your server in the javascript eg:

Pusher.channel_auth_endpoint = '/pusher_auth.php';

Pusher[channel_name].authenticate() takes the socket id (provided by Pusher.js in your browser) as the first parameter and a hash of options as the second parameter. For presence channels you must include a :user_id in those options.

You can also include an optional hash of extra data for each user under the key :user_info.

Adding presence information to your UI

When you subscribe to presence channels, you get 3 new events you can bind to. These are:

pusher:subscription_succeeded

pusher:member_added

pusher:member_removed

Javascript member objects

Member objects returned to your Javascript will look like so:

{
user_id: 123,
user_info: {name: 'Mr. Pusher'}
}

“user_id” is always present in member objects. “user_info” will be also included if you declared it when authenticating the channel in your app (see above).

Initialise

When you successfully connect to a presence channel, it will return you a list of the members who are already in it:

var socket = new Pusher('APP_KEY');
var myPresenceChannel = socket.subscribe('presence-foo')
myPresenceChannel.bind('pusher:subscription_succeeded', function(member_list){
// iterate through the members and add them into the DOM
})

Member added

When a user connects to a presence channel, it sends their details to all other connected members.