User Presence

Last Edit: Aug 08 2020

User presence allows you to show when a user was last active and if they are online right now. Whenever you read a user the data will look like this:


{
    id: 'unique_user_id',
    online: true,
    status: 'Eating a veggie burger...',
    last_active: '2019-01-07T13:17:42.375Z'
}
                    
The online field indicates if the user is online. The status field stores text indicating the current user status.

Invisible

To mark a user invisible simply set the invisible property to true. You can also set a custom status message at the same time:


// mark a user as invisible
await client.setUser({
    id: 'unique_user_id',
    invisible: true
});
                    

val user = User(userId)
user.invisible = true
client.setUser(user, "{{ chat_user_token }}")
                    
When invisible is set to true, the current user will appear as offline to other users.

Listening to Presence Changes

Of course, you want to listen to the user presence changes. This allows you to show a user as offline when they leave and update their status in real time. These 3 endpoints allow you to watch user presence:


// If you pass presence: true to channel.watch it will watch the list of user presence changes.
// Note that you can listen to at most 10 users using this API call
const channel = client.channel('messaging', 'my-conversation-123', {
    members: ['john', 'jack'],
    color: 'green'
});

const state = await channel.watch({ presence: true });

// queryChannels allows you to listen to the members of the channels that are returned
// so this does the same thing as above and listens to online status changes for john and jack
const channels = await client.queryChannels(
    { color: 'green' },
    { last_message_at: -1 },
    { presence: true }
);

// queryUsers allows you to listen to user presence changes for john and jack
const users = await client.queryUsers({
    id: {
      $in: [
        'john', 
        'jack'
       ]
    }}, 
    { id: -1 }, 
    { presence: true }
 );
                    

// If you pass presence: true to channel.watch it will watch the list of user presence changes.
// Note that you can listen to at most 10 users using this API call

val watchRequest = ChannelWatchRequest()
watchRequest.data["members"] = listOf("john", "jack")

channelController.watch(watchRequest).enqueue {
    val channel = it.data()
}

// queryChannels allows you to listen to the members of the channels that are returned
// so this does the same thing as above and listens to online status changes for john and jack

val wathRequestWithPresence = ChannelWatchRequest()
wathRequestWithPresence.presence = true
wathRequestWithPresence.data["members"] = listOf("john", "jack")

channelController.watch(wathRequestWithPresence).enqueue {
    val channel = it.data()
}

// queryUsers allows you to listen to user presence changes for john and jack

val offset = 0
val limit = 2
val usersFilter = Filters.`in`("id", listOf("john", "jack"))
val usersQuery = QueryUsersRequest(usersFilter, offset, limit)
usersQuery.presence = true
client.queryUsers(usersQuery).enqueue {
    val users = it.data()
}
                    

// You need to be watching some channels/queries to be able to get presence events.
// There are multiple ways of doing so:

let channel = Client.shared.channel(type: .messaging, id: "general")

// 1. Query a channel for presence event
let query = ChannelQuery(channel: channel, options: .presence)
channel.query(options: .presence) { (result) in /**/ }

// 2. Query all channels with presence events
let query = ChannelsQuery(options: .presence)
Client.shared.queryChannels(query: query) { (result) in /**/ }

// 3. Query all users for presence
let query = UsersQuery(filter: .none, sort: .none, options: .presence)
Client.shared.queryUsers(query: query) { (result) in /**/ }

// 4. Start watching a specific channel to be able to get notified
channel.watch(options: .presence) { (result) in
    // handle result of `watch` call
    // note that this callback will only be called once, not for each event
}

// Finally, Subscribe to events
let subscription = Client.shared.subscribe(forEvents: [.userPresenceChanged]) { event in
    // handle event
    // this callback will be called for all user presence change events
}
// Cancel subscription when you want to stop receiving events
subscription.cancel()
                    

A users online status change can be handled via event delegation by subscribing to the  user.presence.changed event the same you do for any other event.