Friend Lists, Status Feed and Presence
Using Subscription Management features and the Presence service, you can create simple friend graphs and a status message feed. The friend graph is a simple follow/followers model. For anything more complex, such as a true multi-degree graph or an application that requires querying or traversing graphs, consider a specialized implementation that uses a graph database such as Neo4J or other more sophisticated data mechanisms; these types of use cases are fairly uncommon.
The essential feature required to implement this is the Channel Group feature, which can also be thought of as a Subscribe Group. A Channel Group groups channels into a persistent collection of channels that you can modify dynamically, and it allows you to subscribe to all these channels by subscribing to the group. Learn More about Channel Groups here.
Channel Group's multiplexing capabilities enables us to create friend lists and status feeds. The diagram and the steps to implement follow:
User Identification
All Presence features use the UUID that's set on PubNub client initialization for tracking of that client, which typically is the user. Please refer to Managing UUIDs to learn more about creating and managing UUIDs.
User Channels
Every user will need two channels:
- A channel the user publishes to for their own status messages.
- A channel the user subscribes to, to indicate they're online. This channel will be unique for each user. For convenience, we'll use user-[letter], like user-a or user-b, as the unique identifier.
We'll follow this naming convention:
ch-user-a-status
(publish)ch-user-a-present
(subscribe)
These channels will be added into Channel Groups to enable the monitoring and aggregation of both status messages into a feed, and presence for online status. It's not required to do both if you only want to support friend lists/presence or you only want to support status feeds.
// Publish a status message
pubnub.publish(
{
channel: "ch-user-a-status",
message: {
author: "user-a",
status: "I am reading about Advanced Channel Groups!",
timestamp: Date.now() / 1000
}
},
function (status, response) {
if (status.error) {
console.log(status);
}
else {
console.log("message Published w/ timetoken", response.timetoken);
}
}
);
let timestamp = Date().timeIntervalSince1970
pubnub.publish(
channel: "channelSwift",
message: [
"author": "user-a",
"status": "I am reading about Advanced Channel Groups!",
"timestamp": timestamp
]
) { result in
switch result {
case let .success(response):
print("Successful Publish Response: \(response)")
case let .failure(error):
print("Failed Publish Response: \(error.localizedDescription)")
}
}
NSTimeInterval timestamp = [NSDate date].timeIntervalSince1970;
NSDictionary *data = @{
@"author": @"user-a",
@"status": @"I am reading about Advanced Channel Groups!",
@"timestamp": @(timestamp)
};
[self.pubnub publish:data toChannel:@"ch-user-a-status"
withCompletion:^(PNPublishStatus *status) {
if (!status.isError) {
NSLog(@"Message Published w/ timetoken: %@", status.data.timetoken);
}
else {
NSLog(@"Error happened while publishing: %@", status.errorData.information);
}
}
];
Date date = new Date();
JsonObject data = new JsonObject();
data.put("author", "user-a");
data.put("status", "I am reading about Advanced Channel Groups!");
data.put("timestamp", date.getTime() / 1000);
pubnub.publish()
.channel("ch-user-a-status")
.message(data)
.async(new PNCallback<PNPublishResult>() {
@Override
public void onResponse(PNPublishResult result, PNStatus status) {
if (status.isError()) {
System.out.println("error happened while publishing: "
+ status.toString());
}
else {
System.out.println("message Published w/ timetoken "
+ result.getTimetoken());
}
}
});
// Publish a status message
pubnub.Publish()
.Message(data)
.Channel("ch-user-a-status")
.Execute(new DemoPublishResult());
public class DemoPublishResult : PNCallback<PNPublishResult> {
public override void OnResponse(PNPublishResult result, PNStatus status) {
if (status.Error) {
Console.WriteLine("error happened while publishing: " +
pubnub.JsonPluggableLibrary.SerializeToJsonString(status));
}
else {
Console.WriteLine("message Published w/ timetoken "
+ result.Timetoken.ToString());
}
}
};
# Publish a status message
import time
data = {
'author': 'user-a',
'status': 'I am reading about Advanced Channel Groups!',
'timestamp': time.time()
}
try:
envelope = pubnub.publish()\
.channel("ch-user-b-present")\
.message(data)\
.sync()
print("Message published with timetoken %s" % envelope.result.timetoken)
except PubNubException as e:
print("Operation failed w/ status: %s" % e)
User Channel Groups
Each user will also have two channel groups:
- A channel group for observing the online status of friends.
- A channel group to receive status updates in realtime.
Again, we'll use the same convention for unique user identifiers:
cg-user-a-friends
cg-user-a-status-feed
Creating channel groups requires you to add at least one channel to the channel group. The easiest way to do this is add the user's present channel (ch-user-a-present
) to each channel group.
Channel Group Management
You should only call the Add/Remove Channel to/from Channel Group APIs from your back-end server when a user registers for an account. Doing so from the client side reduces the security of your channels.
// Add ch-user-a-present to cg-user-a-friends
pubnub.channelGroups.addChannels(
{
channels: ["ch-user-a-present"],
channelGroup: "cg-user-a-friends",
},
function(status) {
if (status.error) {
console.log("operation failed w/ status: ", status);
}
else {
console.log("Channel added to channel group");
}
}
);
// Add ch-user-a-present to cg-user-a-status-feed
pubnub.channelGroups.addChannels(
{
channels: ["ch-user-a-present"],
channelGroup: "cg-user-a-status-feed",
},
function(status) {
if (status.error) {
console.log("operation failed w/ status: ", status);
}
else {
console.log("Channel added to channel group");
}
}
);
// Add ch-user-a-present to cg-user-a-friends
pubnub.addChannels(
["ch-user-a-present"],
to: "cg-user-a-friends"
) { result in
switch result {
case let .success(response):
print("Successful Add Channels Response: \(response)")
case let .failure(error):
print("Failed Add Channels Response: \(error.localizedDescription)")
}
}
// Add ch-user-a-present to cg-user-a-status-feed
pubnub.addChannels(
["ch-user-a-present"],
to: "cg-user-a-feed"
) { result in
switch result {
case let .success(response):
print("Successful Add Channels Response: \(response)")
case let .failure(error):
print("Failed Add Channels Response: \(error.localizedDescription)")
}
}
// Add ch-user-a-present to cg-user-a-friends
[self.client addChannels:@[@"ch-user-a-present"] toGroup:@"cg-user-a-friends"
withCompletion:^(PNAcknowledgmentStatus *status) {
if (!status.isError) {
NSLog(@"Channel added to channel group.");
}
else {
NSLog(@"Operation failed w/ status: %@", status.errorData.information);
}
}
];
// Add ch-user-a-present to cg-user-a-status-feed
[self.client addChannels:@[@"ch-user-a-present"] toGroup:@"cg-user-a-status-feed"
withCompletion:^(PNAcknowledgmentStatus *status) {
if (!status.isError) {
NSLog(@"Channel added to channel group.");
}
else {
NSLog(@"Operation failed w/ status: %@", status.errorData.information);
}
}
];
// Add ch-user-a-present to cg-user-a-friends
pubnub.addChannelsToChannelGroup()
.channelGroup("cg-user-a-friends")
.channels(Arrays.asList("ch-user-a-present"))
.async(new PNCallback<PNChannelGroupsAddChannelResult>() {
@Override
public void onResponse(PNChannelGroupsAddChannelResult result, PNStatus status) {
if (status.isError()) {
System.out.println("Operation failed w/ status:" + status.getStatusCode());
}
else {
System.out.println("Channel added to channel group");
}
}
});
// Add ch-user-a-present to cg-user-a-status-feed
pubnub.addChannelsToChannelGroup()
.channelGroup("cg-user-a-status-feed")
.channels(Arrays.asList("ch-user-a-present"))
.async(new PNCallback<PNChannelGroupsAddChannelResult>() {
@Override
public void onResponse(PNChannelGroupsAddChannelResult result, PNStatus status) {
if (status.isError()) {
System.out.println("Operation failed w/ status:" + getStatusCode());
}
else {
System.out.println("Channel added to channel group");
}
}
});
// Add ch-user-a-present to cg-user-a-friends
pubnub.AddChannelsToChannelGroup()
.ChannelGroup("cg-user-a-friends")
.Channels(new string[] { "ch-user-a-present" })
.Execute(new DemoChannelGroupAddChannel());
// Add ch-user-a-present to cg-user-a-status-feed
pubnub.AddChannelsToChannelGroup()
.ChannelGroup("cg-user-a-status-feed")
.Channels(new string[] { "ch-user-a-present" })
.Execute(new DemoChannelGroupAddChannel());
public class DemoChannelGroupAddChannel : PNCallback<PNChannelGroupsAddChannelResult> {
public override void OnResponse(PNChannelGroupsAddChannelResult result, PNStatus status) {
if (status.Error) {
Console.WriteLine("Operation failed w/ status: " + status.StatusCode.ToString());
}
else {
Console.WriteLine("Channel added to channel group");
}
}
}
# Add ch-user-a-present to cg-user-a-friends
pubnub.add_channel_to_channel_group()\
.channels(["ch-user-a-present"])\
.channel_group("cg-user-a-friends")\
.sync()
# Add ch-user-a-present to cg-user-a-status-feed
pubnub.add_channel_to_channel_group()\
.channels(["ch-user-a-present"])\
.channel_group("cg-user-a-status-feed")\
.sync()
Friending
Expanding the friend graph through friending is straightforward: you add channels to channel groups. When User A and User B become friends, you add each user's -present
channel to the other's friend group, and add the -status
channel to each user's status-feed
group. Again, you should only call these APIs from your back-end server when you receive the friendship confirmation from both users.
User A and User B become friends:
// ************************************
// * User A and User B become friends
// ************************************
// Add User B to User A's groups: Add ch-user-b-present to cg-user-a-friends
pubnub.channelGroups.addChannels(
{
channels: ["ch-user-b-present"],
channelGroup: "cg-user-a-friends"
},
function(status) {
if (status.error) {
console.log("operation failed w/ status: ", status);
}
else {
console.log("Channel added to channel group");
}
}
);
// Add User B to User A's groups: ch-user-b-status to cg-user-a-status-feed
pubnub.channelGroups.addChannels(
{
channels: ["ch-user-b-status"],
channelGroup: "cg-user-a-status-feed"
},
function(status) {
if (status.error) {
console.log("operation failed w/ status: ", status);
}
else {
console.log("Channel added to channel group");
}
}
);
// Add User A to User B's groups: Add ch-user-a-present to cg-user-b-friends
pubnub.channelGroups.addChannels(
{
channels: ["ch-user-a-present"],
channelGroup: "cg-user-b-friends"
},
function(status) {
if (status.error) {
console.log("operation failed w/ status: ", status);
}
else {
console.log("Channel added to channel group");
}
}
);
// Add User B to User A's groups: ch-user-a-status to cg-user-b-status-feed
pubnub.channelGroups.addChannels(
{
channels: ["ch-user-a-status"],
channelGroup: "cg-user-b-status-feed"
},
function(status) {
if (status.error) {
console.log("operation failed w/ status: ", status);
}
else {
console.log("Channel added to channel group");
}
}
);
// ************************************
// * User A and User B become friends
// ************************************
// Add User B to User A's groups: Add ch-user-b-present to cg-user-a-friends
pubnub.addChannels(
["ch-user-a-present"],
to: "cg-user-a-friends"
) { result in
switch result {
case let .success(response):
print("Successful Add Channels Response: \(response)")
case let .failure(error):
print("Failed Add Channels Response: \(error.localizedDescription)")
}
}
// Add User B to User A's groups: ch-user-b-status to cg-user-a-status-feed
pubnub.addChannels(
["ch-user-a-status"],
to: "cg-user-a-feed"
) { result in
switch result {
case let .success(response):
print("Successful Add Channels Response: \(response)")
case let .failure(error):
print("Failed Add Channels Response: \(error.localizedDescription)")
}
}
// Add User A to User B's groups: Add ch-user-a-present to cg-user-b-friends
pubnub.addChannels(
["ch-user-a-present"],
to: "cg-user-b-friends"
) { result in
switch result {
case let .success(response):
print("Successful Add Channels Response: \(response)")
case let .failure(error):
print("Failed Add Channels Response: \(error.localizedDescription)")
}
}
// Add User B to User A's groups: ch-user-a-status to cg-user-b-status-feed
pubnub.addChannels(
["ch-user-a-status"],
to: "cg-user-b-feed"
) { result in
switch result {
case let .success(response):
print("Successful Add Channels Response: \(response)")
case let .failure(error):
print("Failed Add Channels Response: \(error.localizedDescription)")
}
}
// Add User B to User A's groups: Add ch-user-b-present to cg-user-a-friends
[self.pubnub addChannels:@[@"ch-user-b-present"] toGroup:@"cg-user-a-friends"
withCompletion:^(PNAcknowledgmentStatus *status) {
if (!status.isError) {
NSLog(@"Channel added to channel group.");
}
else {
NSLog(@"Operation failed w/ status: %@", status.errorData.information);
}
}
];
// Add User B to User A's groups: ch-user-b-status to cg-user-a-status-feed
[self.pubnub addChannels:@[@"ch-user-b-status"] toGroup:@"cg-user-a-status-feed"
withCompletion:^(PNAcknowledgmentStatus *status) {
if (!status.isError) {
NSLog(@"Channel added to channel group.");
}
else {
NSLog(@"Operation failed w/ status: %@", status.errorData.information);
}
}
];
// Add User A to User B's groups: Add ch-user-a-present to cg-user-b-friends
[self.pubnub addChannels:@[@"ch-user-a-present"] toGroup:@"cg-user-b-friends"
withCompletion:^(PNAcknowledgmentStatus *status) {
if (!status.isError) {
NSLog(@"Channel added to channel group.");
}
else {
NSLog(@"Operation failed w/ status: %@", status.errorData.information);
}
}];
// Add User B to User A's groups: ch-user-a-status to cg-user-b-status-feed
[self.pubnub addChannels:@[@"ch-user-a-status"] toGroup:@"cg-user-b-status-feed"
withCompletion:^(PNAcknowledgmentStatus *status) {
if (!status.isError) {
NSLog(@"Channel added to channel group.");
}
else {
NSLog(@"Operation failed w/ status: %@", status.errorData.information);
}
}
];
// ************************************
// * User A and User B become friends
// ************************************
// Add User B to User A's groups: Add ch-user-b-present to cg-user-a-friends
pubnub.addChannelsToChannelGroup()
.channelGroup("cg-user-a-friends")
.channels(Arrays.asList("ch-user-b-present"))
.async(new PNCallback<PNChannelGroupsAddChannelResult>() {
@Override
public void onResponse(PNChannelGroupsAddChannelResult result, PNStatus status) {
if (status.isError()) {
System.out.println("Operation failed w/ status:" + status.getStatusCode());
}
else {
System.out.println("Channel added to channel group");
}
}
});
// Add User B to User A's groups: ch-user-b-status to cg-user-a-status-feed
pubnub.addChannelsToChannelGroup()
.channelGroup("cg-user-a-status-feed")
.channels(Arrays.asList("ch-user-b-status"))
.async(new PNCallback<PNChannelGroupsAddChannelResult>() {
@Override
public void onResponse(PNChannelGroupsAddChannelResult result, PNStatus status) {
if (status.isError()) {
System.out.println("Operation failed w/ status:" + status.getStatusCode());
}
else {
System.out.println("Channel added to channel group");
}
}
});
// Add User A to User B's groups: Add ch-user-a-present to cg-user-b-friends
pubnub.addChannelsToChannelGroup()
.channelGroup("cg-user-b-friends")
.channels(Arrays.asList("ch-user-a-present"))
.async(new PNCallback<PNChannelGroupsAddChannelResult>() {
@Override
public void onResponse(PNChannelGroupsAddChannelResult result, PNStatus status) {
if (status.isError()) {
System.out.println("Operation failed w/ status:" + status.getStatusCode());
}
else {
System.out.println("Channel added to channel group");
}
}
});
// Add User B to User A's groups: ch-user-a-status to cg-user-b-status-feed
pubnub.addChannelsToChannelGroup()
.channelGroup("cg-user-b-status-feed")
.channels(Arrays.asList("ch-user-a-status"))
.async(new PNCallback<PNChannelGroupsAddChannelResult>() {
@Override
public void onResponse(PNChannelGroupsAddChannelResult result, PNStatus status) {
if (status.isError()) {
System.out.println("Operation failed w/ status:" + status.getStatusCode());
}
else {
System.out.println("Channel added to channel group");
}
}
});
// ************************************
// * User A and User B become friends
// ************************************
// Add ch-user-a-present to cg-user-a-friends
pubnub.AddChannelsToChannelGroup()
.ChannelGroup("cg-user-a-friends")
.Channels(new string[] { "ch-user-b-present" })
.Execute(new DemoChannelGroupAddChannel());
// Add User B to User A's groups: ch-user-b-status to cg-user-a-status-feed
pubnub.AddChannelsToChannelGroup()
.ChannelGroup("cg-user-a-status-feed")
.Channels(new string[] { "ch-user-b-status" })
.Execute(new DemoChannelGroupAddChannel());
// Add User A to User B's groups: Add ch-user-a-present to cg-user-b-friends
pubnub.AddChannelsToChannelGroup()
.ChannelGroup("cg-user-b-friends")
.Channels(new string[] { "ch-user-a-present" })
.Execute(new DemoChannelGroupAddChannel());
// Add User B to User A's groups: ch-user-a-status to cg-user-b-status-feed
pubnub.AddChannelsToChannelGroup()
.ChannelGroup("cg-user-b-status-feed")
.Channels(new string[] { "ch-user-a-status" })
.Execute(new DemoChannelGroupAddChannel());
public class DemoChannelGroupAddChannel : PNCallback<PNChannelGroupsAddChannelResult> {
public override void OnResponse(PNChannelGroupsAddChannelResult result, PNStatus status) {
if (status.Error) {
Console.WriteLine("Operation failed w/ status: "
+ status.StatusCode.ToString());
}
else {
Console.WriteLine("Channel added to channel group");
}
}
}
# ************************************
# * User A and User B become friends
# ************************************
try:
result = pubnub.add_channel_to_channel_group()\
.channel_group("cg-user-a-friends")\
.channels("ch-user-b-present")\
.sync()
print("Channel added to channel group")
except PubNubException as e:
print("Operation failed w/ status: %s" % e)
try:
result = pubnub.add_channel_to_channel_group()\
.channel_group("cg-user-a-status-feed")\
.channels("ch-user-b-status")\
.sync()
print("Channel added to channel group")
except PubNubException as e:
print("Operation failed w/ status: %s" % e)
try:
result = pubnub.add_channel_to_channel_group()\
.channel_group("cg-user-b-friends")\
.channels("ch-user-a-present")\
.sync()
print("Channel added to channel group")
except PubNubException as e:
print("Operation failed w/ status: %s" % e)
try:
result = pubnub.add_channel_to_channel_group()\
.channel_group("cg-user-b-status-feed")\
.channels("ch-user-a-status")\
.sync()
print("Channel added to channel group")
except PubNubException as e:
print("Operation failed w/ status: %s" % e)
Subscribe
To see these working, it comes to how you subscribe. What is a bit different here is that you'll subscribe to one channel group for messages (status-feed) but subscribe to the other channel group's presence event channel group for the online/offline status of friends.
Friends Online/Offline
For presence, we track the subscribers on a channel, and we create a side channel based on the channel name for all the presence events on the main channel. This side channel is the channel name + -pnpres
. So for channel ch-user-a-present
, the presence side channel is ch-user-a-present-pnpres
and that is where PubNub publishes presence events that occur on ch-user-a-present
.
The presence events are as follows:
join
- client subscribedleave
- client unsubscribedtimeout
- client disconnected without unsubscribing (occurs after the timeout period expires)state-change
- client changed the contents of the state object
And for each event, we also include the UUID and the channel occupancy (how many subscribers).
To see your friends online/offline status and be updated in realtime, you subscribe to the friends channel group, but not directly. You subscribe to the presence event side channel group only, by appending -pnpres
to the channel group name.
The reason you do not want to subscribe directly to the channel group is because Channel Groups are Subscribe
groups, and therefore you would inadvertently subscribe to all of that users' friends' presence
channels. We are only interested in the presence events of this channel group and not the message of those users.
// Get the List of Friends
pubnub.channelGroups.listChannels(
{
channelGroup: "cg-user-a-friends"
},
function (status, response) {
if (status.error) {
console.log("operation failed w/ error:", status);
return;
}
console.log("FRIENDLIST: ")
response.channels.forEach( function (channel) {
console.log(channel);
});
}
);
// Which Friends are online right now
pubnub.hereNow(
{
channelGroups: ["cg-user-a-friends"]
},
function (status, response) {
if (status.error) {
console.log("operation failed w/ error:", status);
}
else {
console.log("ONLINE NOW: ", response);
}
}
);
pubnub.addListener({
presence: function(presence) {
console.log("FRIEND PRESENCE: ", presence);
},
});
// Watch Friends come online / go offline
pubnub.subscribe({channelGroups:["cg-user-a-friends-pnpres"]});
// Get the List of Friends
pubnub.listChannels(for: "cg-user-a-friends") { result in
switch result {
case let .success(response):
print("Successful List Channels Response: \(response)")
case let .failure(error):
print("Failed List Channels Response: \(error.localizedDescription)")
}
}
// Which Friends are online right now
pubnub.hereNow(
on: [],
and: ["cg-user-a-friends"]
) { result in
switch result {
case let .success(response):
print("Successful hereNow Response: \(response)")
case let .failure(error):
print("Failed hereNow Response: \(error.localizedDescription)")
}
}
// Watch Friends come online / go offline
pubnub.subscribe(
to: [],
and: ["cg-user-a-friends"],
withPresence: true
) { result in
switch result {
case let .success(response):
print("Successful Response: \(response)")
case let .failure(error):
print("Failed Response: \(error.localizedDescription)")
}
}
// Get the List of Friends
[self.pubnub channelsForGroup:@"cg-user-a-friends"
withCompletion:^(PNChannelGroupChannelsResult *result, PNErrorStatus *status) {
if (!status) {
NSLog(@"Friendslist: %@", result.data.channels);
}
else {
NSLog(@"Operation failed w/ status: %@", status.errorData.information);
}
}
];
// Which Friends are online right now
[self.client hereNowForChannelGroup:@"cg-user-a-friends"
withCompletion:^(PNPresenceChannelGroupHereNowResult *result, PNErrorStatus *status) {
if (!status) {
NSLog(@"Online now: %@", result.data.totalOccupancy);
}
else {
NSLog(@"Operation failed w/ status: %@", status.errorData.information);
}
}
];
// Watch Friends come online / go offline
[self.pubnub addListener:self];
[self.pubnub subscribeToChannelGroups:@[@"cg-user-a-friends-pnpres"]];
- (void)pubnub:(PubNub *)client didReceivePresenceEvent:(PNPresenceEventResult *)event {
if (![event.data.presenceEvent isEqualToString:@"state-change"]) {
NSLog(@"%@ \"%@'ed\"", event.data.presence.uuid, event.data.presenceEvent);
}
}
// Get the List of Friends
pubnub.listChannelsForChannelGroup()
.channelGroup("cg-user-a-friends")
.async(new PNCallback<PNChannelGroupsAllChannelsResult>() {
@Override
public void onResponse(PNChannelGroupsAllChannelsResult result, PNStatus status) {
if (status.isError()) {
System.out.println("operation failed w/ status:" + status.getStatusCode());
}
System.out.println("FRIENDLIST:");
result.getChannels().stream().forEach((channelName) -> {
System.out.println("channels: " + channelName);
});
}
});
// Which Friends are online right now
pubnub.hereNow()
.channels(Arrays.asList("cg-user-a-friends"))
.async(new PNCallback<PNHereNowResult>() {
@Override
public void onResponse(PNHereNowResult result, PNStatus status) {
if (status.isError()) {
System.out.println("Operation failed w/ status:" + status.getStatusCode());
}
else {
System.out.println("ONLINE NOW: " + result.getTotalOccupancy());
}
}
});
pubnub.addListener(new SubscribeCallback() {
@Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {
System.out.println("FRIEND PRESENCE: " + presence);
}
});
// Watch Friends come online / go offline
pubnub.subscribe()
.channelGroups(Arrays.asList("cg-user-a-friends-pnpres"))
.execute();
// Get the List of Friends
pubnub.ListChannelsForChannelGroup()
.ChannelGroup("cg-user-a-friends")
.Execute(new DemoListChannelGroupAllChannels());
// Which Friends are online right now
pubnub.HereNow()
.Channels(new string[] { "cg-user-a-friends" })
.Execute(new DemoHereNowResult());
pubnub.AddListener(new DemoSubscribeCallback());
// Watch Friends come online / go offline
pubnub.Subscribe<string>()
.ChannelGroups(new string[] { "cg-user-a-friends-pnpres" })
.Execute();
public class DemoListChannelGroupAllChannels : PNCallback<PNChannelGroupsAllChannelsResult> {
public override void OnResponse(PNChannelGroupsAllChannelsResult result, PNStatus status) {
if (status.Error) {
Console.WriteLine("Operation failed w/ status: " + status.StatusCode.ToString());
}
else {
Console.WriteLine("FRIENDLIST:");
foreach(string channelName in result.Channels) {
Console.WriteLine("channel:" + channelName);
}
}
}
}
public class DemoHereNowResult : PNCallback<PNHereNowResult> {
public override void OnResponse(PNHereNowResult result, PNStatus status) {
if (status.Error) {
Console.WriteLine("Operation failed w/ status: " + status.StatusCode.ToString());
}
else {
Console.WriteLine("ONLINE NOW:" + result.TotalOccupancy.ToString());
}
}
};
public class DemoSubscribeCallback : SubscribeCallback {
public override void Message<T>(Pubnub pubnub, PNMessageResult<T> message) {
}
public override void Presence(Pubnub pubnub, PNPresenceEventResult presence) {
Console.WriteLine("FRIEND PRESENCE:" + pubnub.JsonPluggableLibrary.SerializeToJsonString(presence));
}
public override void Status(Pubnub pubnub, PNStatus status) {
}
}
# Get the List of Friends
try:
env = pubnub.list_channels_in_channel_group()\
.channel_group("cg-user-a-friends")\
.sync()
print("FRIEND LIST:")
for channel in env.result.channels:
print(channel)
except PubNubException as e:
print("Operation failed w/ status: %s" % e)
try:
env = pubnub.here_now()\
.channels("cg-user-a-status") \
.sync()
print("ONLINE NOW: %d" % env.result.total_occupancy)
except PubNubException as e:
print("Operation failed w/ status: %s" % e)
class PresenceListener(SubscribeCallback):
def status(self, pubnub, status):
pass
def message(self, pubnub, message):
pass
def presence(self, pubnub, presence):
print("FRIEND PRESENCE: %s" % presence)
my_listener = PresenceListener()
pubnub.add_listener(my_listener)
pubnub.subscribe()\
.channel_groups("cg-user-a-friends")\
.with_presence()\
.execute()
Status Feed (Messages)
The status-feed channel group is much more straightforward, you're going to subscribe directly to the channel group and you'll receive status updates in realtime via each channel in the channel group.
Since we include the user's present channel (ch-user-a-present
) for this user in the channel group, this will also have the net effect of subscribing to that channel. It also means it generates a join
event for every channel group that includes this user's present channel. So, if User B is friends with User A, when User A subscribes to this status-feed channel group, it also subscribes to User A's present channel and generates that join
event, in addition to all the other presence events.
Friend List Only Implementation
If you're implementing only the friend list and not the status feed, User A will need to subscribe to this ch-user-a-present
channel directly since User A isn't subscribing to the status feed group which includes this channel.
pubnub.addListener({
message: function(message) {
console.log("STATUS: ", message);
}
});
// Get Status Feed Messages
pubnub.subscribe({channelGroups: ["cg-user-a-status-feed"]});
// Get Status Feed Messages
pubnub.subscribe(
to: [],
and: ["cg-user-a-friends"],
withPresence: true
) { result in
switch result {
case let .success(response):
print("Successful Response: \(response)")
case let .failure(error):
print("Failed Response: \(error.localizedDescription)")
}
}
// Get Status Feed Messages
[self.pubnub addListener:self];
[self.pubnub subscribeToChannelGroups:@[@"cg-user-a-friends"] withPresence:YES];
- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {
NSLog(@"Status: %@", message.data.message);
}
pubnub.addListener(new SubscribeCallback() {
@Override
public void message(PubNub pubnub, PNMessageResult message) {
System.out.println("STATUS" + message);
}
});
// Get Status Feed Messages
pubnub.subscribe()
.channelGroups(Arrays.asList("cg-user-a-friends"))
.execute();
pubnub.AddListener(new DemoSubscribeCallback());
// Get Status Feed Messages
pubnub.Subscribe<string>()
.ChannelGroups(new string[] { "cg-user-a-friends" })
.Execute();
public class DemoSubscribeCallback : SubscribeCallback {
public override void Message<T>(Pubnub pubnub, PNMessageResult<T> message) {
Console.WriteLine("STATUS:" +
pubnub.JsonPluggableLibrary.SerializeToJsonString(message));
}
public override void Presence(Pubnub pubnub, PNPresenceEventResult presence) {
}
public override void Status(Pubnub pubnub, PNStatus status) {
}
}
class MessageListener(SubscribeCallback):
def status(self, pubnub, status):
pass
def message(self, pubnub, message):
print("MESSAGE: %s" % message)
def presence(self, pubnub, presence):
pass
pubnub.add_listener(my_listener)
pubnub.subscribe()\
.channel_groups("cg-user-a-friends")\
.execute()
Retrieve History
Retrieving history of status messages can be a bit more work as you have to retrieve messages from each channel in the group individually (each friend) and mash/sort them together client side. You can retrieve message from multiple channels in a single request, but you still have to mash/sort them together when you get those messages.
Complex Use Cases
There are other complex use cases of changing status feeds that can make things a bit trickier, one is weighting the status message, so that it's no longer chronological, but rather based on interests, or activity, or other things. Another layer of complexity that you can add is commenting on status items. Again, it requires a bit more logic here, and PubNub has some additional features, like Message Actions, that will provide some assistance.
Summary
Simple and powerful friend graphs are fairly easy to do with PubNub. It's much easier than trying to develop a full back end to support the presence and status feeds, and on top of that, it's realtime.