Channel Metadata
The Objects service allows you to persist metadata about channels, channel memberships, channel members, and users. The name
and description
are the predefined properties for channel metadata. Additionally, there is a custom
property that you can use to store any custom attribute about a channel as per your business needs.
Channel Metadata
The PubNub Objects service emits events when the metadata associated to a particular channel ID is set or deleted. Your application can receive these events in real time and dynamically react to data changes by updating the information visible on the front end of your app, for instance.
In the following sections, we're going to focus on what you can actually do with channels and their metadata.
Set Channel Metadata
You can set any of the predefined or custom channel metadata by providing the desired information as key/value pairs. The code below adds the name
, description
, and custom owner
information to the channel my_channel
.
pubnub.objects.setChannelMetadata({
channel: "my_channel",
data: {
name: "main channel",
description: "This channel is for company wide chatter.",
custom: { "owner": "johndoe_1" }
}
});
self.client.objects().setChannelMetadata(@"my_channel")
.name(@"main channel")
.information(@"This channel is for company wide chatter.")
.custom(@{ @"owner": @"johndoe_1" })
.includeFields(PNChannelCustomField)
.performWithCompletion(^(PNSetChannelMetadataStatus *status) {
if (!status.isError) {
/**
* Channel metadata successfully has been set.
* Channel metadata information available here: status.data.metadata
*/
} else {
/**
* Handle channel metadata update error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
Map<String, Object> custom = new HashMap<>();
custom.put("owner", "johndoe_1");
pubnub.setChannelMetadata()
.channel("my_channel")
.name("main channel")
.description("This channel is for company wide chatter.")
.custom(custom)
.includeCustom(true)
.async(new PNCallback<PNSetChannelMetadataResult>() {
@Override
public void onResponse(@Nullable final PNSetChannelMetadataResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle result
}
}
});
PNResult<PNSetChannelMetadataResult> setChannelMetadataResponse = await pubnub.SetChannelMetadata()
.Channel("my_channel")
.Name("main channel")
.Description("This channel is for company wide chatter.")
.Custom(new Dictionary<string, object>() { { "owner", "johndoe_1" } })
.IncludeCustom(true)
.ExecuteAsync();
PNSetChannelMetadataResult setChannelMetadataResult = setChannelMetadataResponse.Result;
PNStatus status = setChannelMetadataResponse.Status;
On success, the PubNub SDK returns same metadata object along with status 200, it will also fire objects
-> channel
-> set
event so it can be consumed for other clients(users). Refer to Init & Add Listener section to learn more.
Get Channel Metadata
You can retrieve the metadata of a specific channel by simply providing the channel ID. You can optionally specify whether custom metadata should be included in the response. The code below returns all metadata of the channel with the ID my_channel
.
pubnub.objects.getChannelMetadata({
channel: "my_channel"
});
self.client.objects().channelMetadata(@"my_channel")
.includeFields(PNChannelCustomField)
.performWithCompletion(^(PNFetchChannelsMetadataResult *result, PNErrorStatus *status) {
if (!status.isError) {
/**
* Channel metadata successfully fetched.
* Channel metadata information available here: result.data.metadata
*/
} else {
/**
* Handle channel metadata fetch error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
pubnub.getChannelMetadata()
.channel("my_channel")
.includeCustom(true)
.async(new PNCallback<PNGetChannelMetadataResult>() {
@Override
public void onResponse(@Nullable final PNGetChannelMetadataResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle result
}
}
});
PNResult<PNGetChannelMetadataResult> getChannelMetadataResponse = await pubnub.GetChannelMetadata()
.Channel("my_channel")
.IncludeCustom(true)
.ExecuteAsync();
PNGetChannelMetadataResult getChannelMetadataResult = getChannelMetadataResponse.Result;
PNStatus status = getChannelMetadataResponse.Status;
On success, the PubNub SDK returns the metadata of the specified channel along with status 200.
Get Metadata for All Channels
You can also retrieve metadata for all the channels associated with the API key. You can optionally specify whether custom metadata should be included in the response. The code below returns all predefined and custom metadata of all channels:
pubnub.objects.getAllChannelMetadata();
self.client.objects().allChannelsMetadata()
.start(@"<next from previous request>")
.includeFields(PNChannelCustomField)
.performWithCompletion(^(PNFetchAllChannelsMetadataResult *result, PNErrorStatus *status) {
if (!status.isError) {
/**
* Channels metadata successfully fetched.
* Result object has following information:
* result.data.metadata - list of fetched channels metadata,
* result.data.next - cursor bookmark for fetching the next page,
* result.data.prev - cursor bookmark for fetching the previous page,
* result.data.totalCount - total number of associated channel metadata.
} else {
/**
* Handle channels metadata fetch error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
pubnub.getAllChannelsMetadata()
.includeCustom(true)
.async(new PNCallback<PNGetAllChannelsMetadataResult>() {
@Override
public void onResponse(@Nullable final PNGetAllChannelsMetadataResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle result
}
}
});
PNResult<PNGetAllChannelMetadataResult> getAllChannelMetadataResponse = await pubnub.GetAllChannelMetadata()
.IncludeCustom(true)
.ExecuteAsync();
PNGetAllChannelMetadataResult getAllChannelMetadataResult = getAllChannelMetadataResponse.Result;
PNStatus status2 = getAllChannelMetadataResponse.Status;
On success, the PubNub SDK returns a paginated list of metadata for all channels.
Remove Channel Metadata
You can remove all metadata for a single channel. The code below removes all metadata of the channel with the ID my_channel
.
pubnub.objects.removeChannelMetadata({
channel: "my_channel"
});
self.client.objects().removeChannelMetadata(@"my_channel")
.performWithCompletion(^(PNAcknowledgmentStatus *status) {
if (!status.isError) {
// Channel metadata successfully removed.
} else {
/**
* Handle channel metadata remove error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
pubnub.removeChannelMetadata()
.channel("my_channel")
.async(new PNCallback<PNRemoveChannelMetadataResult>() {
@Override
public void onResponse(@Nullable final PNRemoveChannelMetadataResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle result
}
}
});
PNResult<PNRemoveChannelMetadataResult> removeChannelMetadataResponse = await pubnub.RemoveChannelMetadata()
.Channel("my_channel")
.ExecuteAsync();
PNRemoveChannelMetadataResult removeChannelMetadataResult = removeChannelMetadataResponse.Result;
PNStatus status = removeChannelMetadataResponse.Status;
On completion, the PubNub SDK will fire objects
-> channel
-> delete
event so it can be consumed for other clients(users). Refer to Init & Add Listener section to learn more.
Channel Membership
Apart from users and channels, PubNub also allows you to store the relations between them called memberships. Each user that you add to a channel becomes a member of that specific channel.
Persisting membership information isn't necessary to send or receive messages, but comes in handy when you want to keep track of the subscribers of a particular channel. Using membership association, your application can display channel memberships lists for each user or give the user the possibility to join or leave channels at their discretion, for example.
When a user opens a messaging app and joins a few channels they're interested in, they're expressing the desire to change their current memberships—it's always the user who wants to manage their own memberships. Because of this, membership methods take the current client's UUID by default unless another user's UUID is explicitly specified.
PubNub emits events to notify clients when users are added to or removed from a channel. You can enable this feature using the Admin Portal. In the Objects section, select or clear the appropriate checkboxes to enable or disable sending particular events.
The PubNub Objects service allows you to perform the following operations on memberships:
Operation | Description |
---|---|
Set channel memberships | Adds the current user to one or more channels or updates the custom metadata for the existing memberships. This operation creates a membership for the user to the specified channels. |
Remove channel memberships | Removes the current user from one or more channels. This operation removes a membership for the user from the specified channels. |
Get channel memberships | Returns a list of channel memberships for the current user. |
Set Channel Memberships
You can add a single user to one or more channels (effectively creating a membership relation between the user and the channels) or update the custom metadata of the user's one or more existing memberships. To update custom metadata of existing memberships, provide the desired information as key/value pairs.
The code below adds the current user to the channels my_channel
and my_channel_2
and adds the starred
metadata to the newly created my_channel_2
membership.
pubnub.objects.setMemberships({
channels: [
"channel-1",
{id: "channel-2", custom: {starred: true}
}]
});
NSArray<NSDictionary *> *channels = @[
@{ @"channel": @"my_channel" },
@{ @"channel": @"my_channel_2", @"custom": @{ @"starred": @YES } }
];
self.client.objects().setMemberships()
.uuid(@"uuid")
.channels(channels)
.includeCount(YES)
.limit(40)
.includeFields(NMembershipCustomField | PNMembershipChannelField)
.performWithCompletion(^(PNManageMembershipsStatus *status) {
if (!status.isError) {
/**
* UUID's memberships successfully set.
* Result object has following information:
* status.data.memberships - list of UUID's existing memberships,
* status.data.next - cursor bookmark for fetching the next page,
* status.data.prev - cursor bookmark for fetching the previous page,
* status.data.totalCount - total number of UUID's memberships.
*/
} else {
/**
* Handle UUID's memberships set error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
Map<String, Object> custom = new HashMap<>();
custom.put("starred", true);
pubnub.setMemberships()
.channelMemberships(Arrays.asList(PNChannelMembership.channel("my_channel"), PNChannelMembership.channelWithCustom("my_channel_2", custom)))
.async(new PNCallback<PNSetMembershipResult>() {
@Override
public void onResponse(@Nullable final PNSetMembershipResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle result
}
}
});
List<PNMembership> setMembershipChannelMetadataIdList = new List<PNMembership>();
if (!string.IsNullOrEmpty(seMembershipChannelMetaId))
{
setMembershipChannelMetadataIdList.Add(new PNMembership() { Channel = "my_channel" });
setMembershipChannelMetadataIdList.Add(new PNMembership() { Channel = "my_channel_2", Custom = new Dictionary<string, object>() { { "starred", true } } });
}
PNResult<PNMembershipsResult> setMembershipsResponse = await pubnub.SetMemberships()
.Uuid("my-uuid")
.Channels(setMembershipChannelMetadataIdList)
.Include(new PNMembershipField[] { PNMembershipField.CUSTOM, PNMembershipField.CHANNEL, PNMembershipField.CHANNEL_CUSTOM })
.IncludeCount(true)
.ExecuteAsync();
PNMembershipsResult setMembershipsResult = setMembershipsResponse.Result;
PNStatus status = setMembershipsResponse.Status;
On success, the PubNub SDK will return the channel data for all the specified channels along with the status 200. It will also fire objects
-> membership
-> set
event so it can be consumed for other clients(users). Refer to the Init & Add Listener section to learn more.
Remove Channel Memberships
You can remove a single user from one or more channels, effectively deleting a membership relation between the user and the channels. The code below removes the current user from the channel my_channel_2
.
pubnub.objects.removeMemberships({
channels: ["my_channel_2"]
});
self.client.objects().removeMemberships()
.uuid(@"uuid")
.channels(@"my_channel_2")
.includeFields(PNMembershipCustomField | PNMembershipChannelField)
.performWithCompletion(^(PNManageMembershipsStatus *status) {
if (!status.isError) {
/**
* UUID's memberships successfully removed.
* Result object has following information:
* status.data.memberships - list of UUID's existing memberships,
* status.data.next - cursor bookmark for fetching the next page,
* status.data.prev - cursor bookmark for fetching the previous page,
* status.data.totalCount - total number of UUID's memberships.
*/
} else {
/**
* Handle UUID's memberships remove error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
pubnub.removeMemberships()
.channelMemberships(Collections.singletonList(PNChannelMembership.channel("my_channel_2")))
.async(new PNCallback<PNRemoveMembershipResult>() {
@Override
public void onResponse(@Nullable final PNRemoveMembershipResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle result
}
}
});
List<string> removeMembershipList = new List<string>();
if (!string.IsNullOrEmpty(removeMembershipChannelMetaId))
{
removeMembershipList.Add("my_channel_2");
}
PNResult<PNMembershipsResult> removeMembershipsResponse = await pubnub.RemoveMemberships()
.Uuid("uuid")
.Channels(removeMembershipList)
.Include(new PNMembershipField[] { PNMembershipField.CUSTOM, PNMembershipField.CHANNEL, PNMembershipField.CHANNEL_CUSTOM })
.IncludeCount(true)
.ExecuteAsync();
PNMembershipsResult removeMembershipsResult = removeMembershipsResponse.Result;
PNStatus status2 = removeMembershipsResponse.Status;
On completion, the PubNub SDK will fire objects
-> membership
-> delete
event so it can be consumed for other clients(users). Refer to the Init & Add Listener section to learn more.
Get Channel Memberships
You can retrieve a list of channel memberships for the current user. The code below returns all memberships for the current user.
pubnub.objects.getMemberships();
self.client.objects().memberships()
.uuid(@"uuid")
.includeFields(PNMembershipCustomField | PNMembershipChannelField)
.performWithCompletion(^(PNFetchMembershipsResult *result, PNErrorStatus *status) {
if (!status.isError) {
/**
* UUID's memberships successfully fetched.
* Result object has following information:
* result.data.memberships - list of UUID's memberships,
* result.data.next - cursor bookmark for fetching the next page,
* result.data.prev - cursor bookmark for fetching the previous page,
* result.data.totalCount - total number of UUID's memberships
*/
} else {
/**
* Handle UUID's memberships fetch error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
pubnub.getMemberships()
.async(new PNCallback<PNGetMembershipsResult>() {
@Override
public void onResponse(@Nullable final PNGetMembershipsResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle result
}
}
})
PNResult<PNGetMembershipsResult> getMembershipsResponse = await pubnub.GetMemberships()
.Uuid("my-uuid")
.Include(new PNMembershipField[] { PNMembershipField.CUSTOM, PNMembershipField.CHANNEL, PNMembershipField.CHANNEL_CUSTOM })
.IncludeCount(true)
.Page(new PNPageObject() { Next = "", Prev = "" })
.ExecuteAsync();
PNGetMembershipsResult getMembershipsResult = getMembershipsResponse.Result;
PNStatus status = getMembershipsResponse.Status;
On success, the PubNub SDK will return the all channels for which the user is a member along with the status 200.
Channel Member
Apart from users and channels, PubNub also allows you to store the relations between them called memberships. Each user that you add to a channel becomes a member of that specific channel.
The following section describes how to add channel memberships from an external user's perspective, that is, when another user wants to add/remove members to a channel. This is the case when a user already is a member (or a moderator) of a specific channel and wishes to add/remove users to that channel. Setting members in a channel is also a more efficient way of handling bulk operations than setting memberships.
PubNub emits events to notify clients when users are added to or removed from a channel. You can enable this feature using the Admin Portal. In the Objects section, select or clear the appropriate checkboxes to enable or disable sending particular events.
The PubNub Objects service allows you to perform the following operations on channel members:
Operation | Description |
---|---|
Set members in channel | Adds one or more users to a single channel. This operation creates memberships for these users to the specified channel. |
Remove members from channel | Removes one or more users from a single channel. This operation removes memberships for these users from the specified channel. |
Get members in channel | Returns a list of users on a single channel. The list includes user's custom metadata if available and includes only uuids for users who do not have custom metadata. |
Set Members in Channel
You can add one or more users to a single channel (effectively creating a membership relation between the users and the channel) or update the custom metadata of one or more users that are existing members of a single channel. To update custom metadata of existing memberships, provide the desired information as key/value pairs.
The code below adds the membership to my_channel
for the users johndoe_1
and janedoe_1
. Additionally, custom metadata trialPeriod
is also added to the newly created membership for janedoe_1
.
pubnub.objects.setChannelMembers({
channel: "my_channel",
uuids: [
'johndoe_1',
{ id: 'janedoe_1', custom: { trialPeriod: false } },
],
});
NSArray<NSDictionary *> *uuids = @[
@{ @"uuid": @"johndoe_1" }
@{ @"uuid": @"janedoe_1", @"custom": @{ @"trialPeriod": @YES } }
];
self.client.objects().setChannelMembers(@"my_channel")
.uuids(uuids)
.includeFields(PNChannelMemberCustomField | PNChannelMemberUserField)
.performWithCompletion(^(PNManageChannelMembersStatus *status) {
if (!status.isError) {
/**
* Channel's members successfully set.
* Result object has following information:
* result.data.members - list of existing channel's members,
* result.data.next - cursor bookmark for fetching the next page,
* result.data.prev - cursor bookmark for fetching the previous page,
* result.data.totalCount - total number of channel's members.
*/
} else {
/**
* Handle channel's members set error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
Map<String, Object> custom = new HashMap<>();
custom.put("trialPeriod", true);
pubnub.setChannelMembers()
.channel("my_channel")
.uuids(Arrays.asList(PNUUID.uuid("johndoe_1"), PNUUID.uuidWithCustom("janedoe_1", custom)))
.async(new PNCallback<PNSetChannelMembersResult>() {
@Override
public void onResponse(@Nullable final PNSetChannelMembersResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle result
}
}
});
List<PNChannelMember> setMemberChannelList = new List<PNChannelMember>();
if (!string.IsNullOrEmpty(setMemberChUuid))
{
setMemberChannelList.Add(new PNChannelMember() { Uuid = "johndoe_1" } );
setMemberChannelList.Add(new PNChannelMember() { Uuid = "janedoe_1", Custom = new Dictionary<string, object>() { { "trialPeriod", false } } });
}
PNResult<PNChannelMembersResult> setChannelMembersResponse = await pubnub.SetChannelMembers()
.Channel(setmemberChMetadataId)
.Uuids(setMemberChannelList)
.Include(new PNChannelMemberField[] { PNChannelMemberField.CUSTOM, PNChannelMemberField.UUID, PNChannelMemberField.UUID_CUSTOM })
.IncludeCount(true)
.ExecuteAsync();
PNChannelMembersResult setChannelMembersResult = setChannelMembersResponse.Result;
PNStatus status2 = setChannelMembersResponse.Status;
On success, the PubNub SDK will return the channel data of the specified channel along with the status 200. It will also fire objects
-> membership
-> set
event so it can be consumed for other clients(users). Refer to the Init & Add Listener section to learn more.
Remove Members from Channel
You can remove one or more users from a single channel by providing the channel ID and a list of users. The code below deletes the membership to my_channel_2
for the users johndoe_1
and janedoe_1
.
pubnub.objects.removeChannelMembers({
channel: "my_channel_2",
uuids: ["johndoe_1", "janedoe_1"]
}
);
self.client.objects().removeChannelMembers(@"my_channel_2")
.uuids(@[@"johndoe_1", @"janedoe_1"])
.includeFields(PNChannelMemberCustomField | PNChannelMemberUserField)
.performWithCompletion(^(PNManageChannelMembersStatus *status) {
if (!status.isError) {
/**
* Channel's members successfully removed.
* Result object has following information:
* result.data.members - list of channel's existing members,
* result.data.next - cursor bookmark for fetching the next page,
* result.data.prev - cursor bookmark for fetching the previous page,
* result.data.totalCount - total number of channel's members.
*/
} else {
/**
* Handle channel's members remove error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
pubnub.removeChannelMembers()
.channel("my_channel_2")
.uuids(Arrays.asList(PNUUID.uuid("johndoe_1"), PNUUID.uuid("janedoe_1")))
.async(new PNCallback<PNRemoveChannelMembersResult>() {
@Override
public void onResponse(@Nullable final PNRemoveChannelMembersResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle result
}
}
});
List<string> removeChannelMemberList = new List<string>();
removeChannelMemberList.Add("johndoe_1");
removeChannelMemberList.Add("janedoe_1");
PNResult<PNChannelMembersResult> removeChannelMembersResponse = await pubnub.RemoveChannelMembers()
.Channel("my_channel_2")
.Uuids(removeChannelMemberList)
.Include(new PNChannelMemberField[] { PNChannelMemberField.CUSTOM, PNChannelMemberField.UUID, PNChannelMemberField.UUID_CUSTOM })
.IncludeCount(true)
.ExecuteAsync();
PNChannelMembersResult removeChannelMembersResult = removeChannelMembersResponse.Result;
PNStatus status = removeChannelMembersResponse.Status;
On completion, the PubNub SDK will fire objects
-> membership
-> delete
event.
Get Members in Channel
You can retrieve a list of members of a single channel simply by providing its ID. The code below returns the members of the channel my_channel
.
pubnub.objects.getChannelMembers({
channel: "my_channel"
});
self.client.objects().channelMembers(@"my_channel")
.includeFields(PNChannelMemberCustomField | PNChannelMemberUUIDField)
.performWithCompletion(^(PNFetchChannelMembersResult *result, PNErrorStatus *status) {
if (!status.isError) {
/**
* Channel's members successfully fetched.
* Result object has following information:
* result.data.members - list of channel's members,
* result.data.next - cursor bookmark for fetching the next page,
* result.data.prev - cursor bookmark for fetching the previous page,
* result.data.totalCount - total number of channel's members.
*/
} else {
/**
* Handle channel's members fetch error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
pubnub.getChannelMembers()
.channel("my_channel")
.async(new PNCallback<PNGetChannelMembersResult>() {
@Override
public void onResponse(@Nullable final PNGetChannelMembersResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle response
}
}
});
PNResult<PNChannelMembersResult> getChannelMembersResponse = await pubnub.GetChannelMembers()
.Channel("my_channel")
.Include(new PNChannelMemberField[] { PNChannelMemberField.CUSTOM, PNChannelMemberField.UUID, PNChannelMemberField.UUID_CUSTOM })
.IncludeCount(true)
.ExecuteAsync();
PNChannelMembersResult getChannelMembersResult = getChannelMembersResponse.Result;
PNStatus status2 = getChannelMembersResponse.Status;
On success, the PubNub SDK returns the UUIDs of all the users, and the associated channel metadata for that channel, along with the status 200.