Presence
It can often be useful to track online status of users on a website. By default, SocialStack sites use authenticated websockets which are typically the foundation of all presense checking, as you can identify when they disconnect as well. There are some caveats to this which it helps to be aware of as it may affect your design goals and those are noted below too.
Websocket based presence
The simplest way to handle user presence is by handling the following events:
- Events.WebSocket.AfterLogin
- Events.WebSocket.AfterLogout
These events are triggered whenever a user account has authenticated via the websocket. If you don't care about user accounts and are more interested in the raw number of sessions, anonymous users included, use the underlying disconnect and connect events instead:
- Events.WebSocket.Connected
- Events.WebSocket.Disconnected
If a user is authenticated, it is often the case that Connected triggers immediately before AfterLogin does, and similarly, AfterLogout triggers immediately before Disconnected.
Active logins
There is nothing stopping someone opening multiple tabs of your website across multiple devices. Indeed this is very common with people frequently switching between mobile devices and desktops. A user is therefore not necessarily present or not - they can be present in 3 places, and all 3 sessions must end before their overall online state can change. If this sounds like a situation you need to handle, consider installing the ActiveLogins module which does it for you and keeps a user OnlineState field up to date.
socialstack install Api/ActiveLogins
This module creates a personal "network room" which keeps track of a users presence from multiple devices, potentially also across multiple servers if you have a larger cluster too. The current state of the personal network room is tracked via "ActiveLoginHistory" records which can be used to identify a user logging in and out over time. These login audit trails are also often necessary on sites where unauthorised access is a concern due to the potential for privacy or property breaches.
Web presence caveats
Your website is likely to be left open in a tab for days or longer as well. In Chrome, an idle tab can actually keep the websocket connection open for a while (days) too. This means a user is "present" because the tab is open, but they are not active - often because the tab is one of dozens. If user activity is important to you, it is suggested to send a websocket message indicating activity and handle that directly. If you don't receive such an activity message, then you can mark the websocket connection as "away".