Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

events: Add support for sending presence events in modern format.

Vector73f1d1d5f1a4c4
diff --git a/api_docs/changelog.md b/api_docs/changelog.md
index e3894d05db8..aedaa51cc7c 100644
--- a/api_docs/changelog.md
+++ b/api_docs/changelog.md
@@ -20,6 +20,19 @@ format used by the Zulip server that they are interacting with.
## Changes in Zulip 11.0
+**Feature level 419**
+
+* [`POST /register`](/api/register-queue): Added `simplified_presence_events`
+ [client capability](/api/register-queue#parameter-client_capabilities),
+ which allows clients to specify whether they support receiving the
+ `presence` event type with user presence data in the modern API format.
+* [`GET /events`](/api/get-events): Added the `presences` field to the
+ `presence` event type for clients that support the `simplified_presence_events`
+ [client capability](/api/register-queue#parameter-client_capabilities).
+ The `presences` field will have the user presence data in the modern
+ API format. For clients that don't support that client capability the
+ event will contain fields with the legacy format for user presence data.
+
**Feature level 418**
* [`GET /events`](/api/get-events): An event with `type: "channel_folder"`
diff --git a/tools/check-schemas b/tools/check-schemas
index 277af854aca..cb0c6cc910d 100755
--- a/tools/check-schemas
+++ b/tools/check-schemas
@@ -68,6 +68,9 @@ def get_event_checker(event: dict[str, Any]) -> Callable[[str, dict[str, Any]],
# Change to CamelCase
name = name.replace("_", " ").title().replace(" ", "")
+ if name == "Presence":
+ name = "Legacy" + name
+
# And add the prefix.
name = "Event" + name
diff --git a/version.py b/version.py
index 94966178577..91e64e3eb73 100644
--- a/version.py
+++ b/version.py
@@ -34,7 +34,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"
# new level means in api_docs/changelog.md, as well as "**Changes**"
# entries in the endpoint's documentation in `zulip.yaml`.
-API_FEATURE_LEVEL = 418
+API_FEATURE_LEVEL = 419
# Bump the minor PROVISION_VERSION to indicate that folks should provision
# only when going from an old version of the code to a newer version. Bump
diff --git a/zerver/actions/presence.py b/zerver/actions/presence.py
index 1c90f6ddc87..b7548e46396 100644
--- a/zerver/actions/presence.py
+++ b/zerver/actions/presence.py
@@ -9,6 +9,7 @@ from psycopg2 import sql
from zerver.actions.user_activity import update_user_activity_interval
from zerver.lib.presence import (
format_legacy_presence_dict,
+ get_modern_user_presence_info,
user_presence_datetime_with_date_joined_default,
)
from zerver.lib.users import get_user_ids_who_can_access_user
@@ -63,13 +64,15 @@ def send_presence_changed(
# The mobile app handles these events so we need to use the old format.
# The format of the event should also account for the slim_presence
# API parameter when this becomes possible in the future.
- presence_dict = format_legacy_presence_dict(last_active_time, last_connected_time)
+ legacy_presence_dict = format_legacy_presence_dict(last_active_time, last_connected_time)
+ modern_presence_dict = get_modern_user_presence_info(last_active_time, last_connected_time)
event = dict(
type="presence",
email=user_profile.email,
user_id=user_profile.id,
server_timestamp=time.time(),
- presence={presence_dict["client"]: presence_dict},
+ legacy_presence={legacy_presence_dict["client"]: legacy_presence_dict},
+ modern_presence=modern_presence_dict,
)
send_event_rollback_unsafe(user_profile.realm, event, user_ids)
diff --git a/zerver/lib/event_schema.py b/zerver/lib/event_schema.py
index c9f72585003..d0dd9ee2dbc 100644
--- a/zerver/lib/event_schema.py
+++ b/zerver/lib/event_schema.py
@@ -39,6 +39,7 @@ from zerver.lib.event_types import (
EventInvitesChanged,
EventLegacyPresence,
EventMessage,
+ EventModernPresence,
EventMutedTopics,
EventMutedUsers,
EventNavigationViewAdd,
@@ -247,6 +248,7 @@ _check_channel_folder_update = make_checker(EventChannelFolderUpdate)
_check_delete_message = make_checker(EventDeleteMessage)
_check_has_zoom_token = make_checker(EventHasZoomToken)
_check_legacy_presence = make_checker(EventLegacyPresence)
+_check_modern_presence = make_checker(EventModernPresence)
_check_muted_topics = make_checker(EventMutedTopics)
_check_realm_bot_add = make_checker(EventRealmBotAdd)
_check_realm_bot_update = make_checker(EventRealmBotUpdate)
@@ -357,6 +359,15 @@ def check_legacy_presence(
assert event_presence_value["status"] == status
+def check_modern_presence(var_name: str, event: dict[str, object], user_id: int) -> None:
+ _check_modern_presence(var_name, event)
+
+ assert isinstance(event["presences"], dict)
+
+ [(event_presences_key, event_presences_value)] = event["presences"].items()
+ assert event_presences_key == str(user_id)
+
+
def check_realm_bot_add(
var_name: str,
event: dict[str, object],
diff --git a/zerver/lib/event_types.py b/zerver/lib/event_types.py
index 3ea6677b452..e24eff92d2e 100644
--- a/zerver/lib/event_types.py
+++ b/zerver/lib/event_types.py
@@ -345,6 +345,16 @@ class EventLegacyPresence(EventLegacyPresenceCore):
email: str | None = None
+class ModernPresence(BaseModel):
+ active_timestamp: int
+ idle_timestamp: int
+
+
+class EventModernPresence(BaseEvent):
+ type: Literal["presence"]
+ presences: dict[str, ModernPresence]
+
+
# Type for the legacy user field; the `user_id` field is intended to
# replace this and we expect to remove this once clients have migrated
# to support the modern API.
diff --git a/zerver/lib/events.py b/zerver/lib/events.py
index 0a42e40d72c..20283d057fc 100644
--- a/zerver/lib/events.py
+++ b/zerver/lib/events.py
@@ -178,6 +178,7 @@ def fetch_initial_state_data(
user_list_incomplete: bool = False,
include_deactivated_groups: bool = False,
archived_channels: bool = False,
+ simplified_presence_events: bool = False,
) -> dict[str, Any]:
"""When `event_types` is None, fetches the core data powering the
web app's `page_params` and `/api/v1/register` (for mobile/terminal
@@ -350,7 +351,7 @@ def fetch_initial_state_data(
state["muted_users"] = [] if user_profile is None else get_user_mutes(user_profile)
if want("presence"):
- if presence_last_update_id_fetched_by_client is not None:
+ if presence_last_update_id_fetched_by_client is not None or simplified_presence_events:
# This param being submitted by the client, means they want to use
# the modern API.
slim_presence = True
@@ -948,6 +949,7 @@ def apply_events(
user_list_incomplete: bool,
include_deactivated_groups: bool,
archived_channels: bool = False,
+ simplified_presence_events: bool = False,
) -> None:
for event in events:
if fetch_event_types is not None and event["type"] not in fetch_event_types:
@@ -971,6 +973,7 @@ def apply_events(
user_list_incomplete=user_list_incomplete,
include_deactivated_groups=include_deactivated_groups,
archived_channels=archived_channels,
+ simplified_presence_events=simplified_presence_events,
)
@@ -986,6 +989,7 @@ def apply_event(
user_list_incomplete: bool,
include_deactivated_groups: bool,
archived_channels: bool = False,
+ simplified_presence_events: bool = False,
) -> None:
if event["type"] == "message":
state["max_message_id"] = max(state["max_message_id"], event["message"]["id"])
@@ -1717,13 +1721,17 @@ def apply_event(
# This means that the state resulting from fetch_initial_state + apply_events will not
# match the state of a hypothetical fetch_initial_state fetch that included the fully
# updated data. This is intended and not a bug.
- if slim_presence:
+ if simplified_presence_events:
+ user_key = next(iter(event["presences"].keys()))
+ user_id = user_key
+ slim_presence = True
+ elif slim_presence:
user_key = str(event["user_id"])
+ user_id = event["user_id"]
else:
user_key = event["email"]
- state["presences"][user_key] = get_presence_for_user(event["user_id"], slim_presence)[
- user_key
- ]
+ user_id = event["user_id"]
+ state["presences"][user_key] = get_presence_for_user(user_id, slim_presence)[user_key]
elif event["type"] == "update_message":
# We don't return messages in /register, so we don't need to
# do anything for content updates, but we may need to update
@@ -2006,6 +2014,7 @@ class ClientCapabilities(TypedDict):
include_deactivated_groups: NotRequired[bool]
archived_channels: NotRequired[bool]
empty_topic_name: NotRequired[bool]
+ simplified_presence_events: NotRequired[bool]
DEFAULT_CLIENT_CAPABILITIES = ClientCapabilities(notification_settings_null=False)
@@ -2048,6 +2057,7 @@ def do_events_register(
include_deactivated_groups = client_capabilities.get("include_deactivated_groups", False)
archived_channels = client_capabilities.get("archived_channels", False)
empty_topic_name = client_capabilities.get("empty_topic_name", False)
+ simplified_presence_events = client_capabilities.get("simplified_presence_events", False)
if fetch_event_types is not None:
event_types_set: set[str] | None = set(fetch_event_types)
@@ -2083,6 +2093,7 @@ def do_events_register(
include_streams=include_streams,
spectator_requested_language=spectator_requested_language,
include_deactivated_groups=include_deactivated_groups,
+ simplified_presence_events=simplified_presence_events,
)
post_process_state(
@@ -2119,6 +2130,7 @@ def do_events_register(
include_deactivated_groups=include_deactivated_groups,
archived_channels=archived_channels,
empty_topic_name=empty_topic_name,
+ simplified_presence_events=simplified_presence_events,
)
if queue_id is None:
@@ -2142,6 +2154,7 @@ def do_events_register(
user_list_incomplete=user_list_incomplete,
include_deactivated_groups=include_deactivated_groups,
archived_channels=archived_channels,
+ simplified_presence_events=simplified_presence_events,
)
# Apply events that came in while we were fetching initial data
@@ -2157,6 +2170,7 @@ def do_events_register(
linkifier_url_template=linkifier_url_template,
user_list_incomplete=user_list_incomplete,
include_deactivated_groups=include_deactivated_groups,
+ simplified_presence_events=simplified_presence_events,
)
post_process_state(
diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yaml
index db95f1a5a09..dcc98612b3b 100644
--- a/zerver/openapi/zulip.yaml
+++ b/zerver/openapi/zulip.yaml
@@ -1199,12 +1199,24 @@ paths:
if the newly-online user sends a message or otherwise demonstrates
they're online).
+ If the client supports the `simplified_presence_events` [client
+ capability](/api/register-queue#parameter-client_capabilities),
+ these events will include the `presences` field, which provides the
+ modified user's presence data in the modern format. Clients are
+ strongly encouraged to implement this client capability, as legacy
+ format support will be removed in a future release.
+
If the `CAN_ACCESS_ALL_USERS_GROUP_LIMITS_PRESENCE` server-level
setting is set to `true`, then the event is only sent to users
who can access the user who came back online.
- **Changes**: Prior to Zulip 8.0 (feature level 228), this event
- was sent to all users in the organization.
+ **Changes**: Prior to Zulip 11.0 (feature level 419), the
+ `simplified_presence_events` client capability did not exist.
+ Therefore, all events were in the legacy format, and did not
+ include the `presences` field.
+
+ Prior to Zulip 8.0 (feature level 228), this event was sent to all
+ users in the organization.
properties:
id:
$ref: "#/components/schemas/EventIdSchema"
@@ -1213,13 +1225,32 @@ paths:
- $ref: "#/components/schemas/EventTypeSchema"
- enum:
- presence
+ presences:
+ type: object
+ description: |
+ Only present for clients that support the `simplified_presence_events`
+ [client capability](/api/register-queue#parameter-client_capabilities).
+
+ A dictionary mapping user IDs to the presence data (modern
+ format) for the modified user(s). Clients should support
+ updating multiple users in a single event.
+
+ **Changes**: New in Zulip 11.0 (feature level 419).
+ additionalProperties:
+ $ref: "#/components/schemas/ModernPresenceFormat"
user_id:
type: integer
description: |
+ Not present for clients that support the `simplified_presence_events`
+ [client capability](/api/register-queue#parameter-client_capabilities).
+
The ID of the modified user.
email:
type: string
description: |
+ Not present for clients that support the `simplified_presence_events`
+ [client capability](/api/register-queue#parameter-client_capabilities).
+
The Zulip API email of the user.
**Deprecated**: This field will be removed in a future
@@ -1228,12 +1259,19 @@ paths:
server_timestamp:
type: number
description: |
+ Not present for clients that support the `simplified_presence_events`
+ [client capability](/api/register-queue#parameter-client_capabilities).
+
The timestamp of when the Zulip server received the user's
presence as a UNIX timestamp.
presence:
type: object
description: |
- Object containing the details of the user's most recent presence.
+ Not present for clients that support the `simplified_presence_events`
+ [client capability](/api/register-queue#parameter-client_capabilities).
+
+ Object containing the presence data (legacy format) of of the modified
+ user.
additionalProperties:
type: object
description: |
@@ -16186,6 +16224,15 @@ paths:
**Changes**: New in Zulip 10.0 (feature level 334). Previously,
the empty string was not a valid topic name.
+ - `simplified_presence_events`: Boolean for whether the client supports
+ receiving the [`presence` event type](/api/get-events#presence) with
+ user presence data in the modern format. If true, the server will
+ send these events with the `presences` field that has the user presence
+ data in the modern format. Otherwise, these event will contain fields
+ with legacy format user presence data.
+ <br />
+ **Changes**: New in Zulip 11.0 (feature level 419).
+
[help-linkifiers]: /help/add-a-custom-linkifier
[rfc6570]: https://www.rfc-editor.org/rfc/rfc6570.html
[events-linkifiers]: /api/get-events#realm_linkifiers
diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py
index 13f67b1ebdc..0dea6e1d51b 100644
--- a/zerver/tests/test_events.py
+++ b/zerver/tests/test_events.py
@@ -185,6 +185,7 @@ from zerver.lib.event_schema import (
check_invites_changed,
check_legacy_presence,
check_message,
+ check_modern_presence,
check_muted_topics,
check_muted_users,
check_navigation_view_add,
@@ -360,6 +361,7 @@ class BaseAction(ZulipTestCase):
include_deactivated_groups: bool = False,
archived_channels: bool = False,
allow_empty_topic_name: bool = True,
+ simplified_presence_events: bool = False,
) -> Iterator[list[dict[str, Any]]]:
"""
Make sure we have a clean slate of client descriptors for these tests.
@@ -392,6 +394,7 @@ class BaseAction(ZulipTestCase):
user_list_incomplete=user_list_incomplete,
include_deactivated_groups=include_deactivated_groups,
archived_channels=archived_channels,
+ simplified_presence_events=simplified_presence_events,
)
)
@@ -457,6 +460,7 @@ class BaseAction(ZulipTestCase):
user_list_incomplete=user_list_incomplete,
include_deactivated_groups=include_deactivated_groups,
archived_channels=archived_channels,
+ simplified_presence_events=simplified_presence_events,
)
post_process_state(
self.user_profile, hybrid_state, notification_settings_null, allow_empty_topic_name
@@ -490,6 +494,7 @@ class BaseAction(ZulipTestCase):
user_list_incomplete=user_list_incomplete,
include_deactivated_groups=include_deactivated_groups,
archived_channels=archived_channels,
+ simplified_presence_events=simplified_presence_events,
)
post_process_state(
self.user_profile, normal_state, notification_settings_null, allow_empty_topic_name
@@ -1853,6 +1858,16 @@ class NormalActionsTest(BaseAction):
status="active",
)
+ def test_modern_presence_events(self) -> None:
+ with self.verify_action(simplified_presence_events=True) as events:
+ do_update_user_presence(
+ self.user_profile,
+ get_client("ZulipAndroid/1.0"),
+ timezone_now(),
+ UserPresence.LEGACY_STATUS_ACTIVE_INT,
+ )
+ check_modern_presence("events[0]", events[0], self.user_profile.id)
+
def test_presence_events_multiple_clients(self) -> None:
now = timezone_now()
initial_presence = now - timedelta(days=365)
diff --git a/zerver/tornado/django_api.py b/zerver/tornado/django_api.py
index 252eedad784..a85014992e6 100644
--- a/zerver/tornado/django_api.py
+++ b/zerver/tornado/django_api.py
@@ -94,6 +94,7 @@ def request_event_queue(
include_deactivated_groups: bool = False,
archived_channels: bool = False,
empty_topic_name: bool = False,
+ simplified_presence_events: bool = False,
) -> str | None:
if not settings.USING_TORNADO:
return None
@@ -125,6 +126,7 @@ def request_event_queue(
"include_deactivated_groups": orjson.dumps(include_deactivated_groups),
"archived_channels": orjson.dumps(archived_channels),
"empty_topic_name": orjson.dumps(empty_topic_name),
+ "simplified_presence_events": orjson.dumps(simplified_presence_events),
}
if event_types is not None:
diff --git a/zerver/tornado/event_queue.py b/zerver/tornado/event_queue.py
index abd54be722c..4bad1ac4130 100644
--- a/zerver/tornado/event_queue.py
+++ b/zerver/tornado/event_queue.py
@@ -84,6 +84,7 @@ class ClientDescriptor:
include_deactivated_groups: bool,
archived_channels: bool,
empty_topic_name: bool,
+ simplified_presence_events: bool,
) -> None:
# TODO: We eventually want to upstream this code to the caller, but
# serialization concerns make it a bit difficult.
@@ -118,6 +119,7 @@ class ClientDescriptor:
self.include_deactivated_groups = include_deactivated_groups
self.archived_channels = archived_channels
self.empty_topic_name = empty_topic_name
+ self.simplified_presence_events = simplified_presence_events
# Default for lifespan_secs is DEFAULT_EVENT_QUEUE_TIMEOUT_SECS;
# but users can set it as high as MAX_QUEUE_TIMEOUT_SECS.
@@ -151,6 +153,7 @@ class ClientDescriptor:
include_deactivated_groups=self.include_deactivated_groups,
archived_channels=self.archived_channels,
empty_topic_name=self.empty_topic_name,
+ simplified_presence_events=self.simplified_presence_events,
)
@override
@@ -191,6 +194,7 @@ class ClientDescriptor:
include_deactivated_groups=d.get("include_deactivated_groups", False),
archived_channels=d.get("archived_channels", False),
empty_topic_name=d.get("empty_topic_name", False),
+ simplified_presence_events=d.get("simplified_presence_events", False),
)
ret.last_connection_time = d["last_connection_time"]
return ret
@@ -1276,7 +1280,7 @@ def process_presence_event(event: Mapping[str, Any], users: Iterable[int]) -> No
type="presence",
user_id=event["user_id"],
server_timestamp=event["server_timestamp"],
- presence=event["presence"],
+ presence=event["legacy_presence"],
)
legacy_event = dict(
@@ -1284,13 +1288,20 @@ def process_presence_event(event: Mapping[str, Any], users: Iterable[int]) -> No
user_id=event["user_id"],
email=event["email"],
server_timestamp=event["server_timestamp"],
- presence=event["presence"],
+ presence=event["legacy_presence"],
+ )
+
+ modern_event = dict(
+ type="presence",
+ presences={str(event["user_id"]): event["modern_presence"]},
)
for user_profile_id in users:
for client in get_client_descriptors_for_user(user_profile_id):
if client.accepts_event(event):
- if client.slim_presence:
+ if client.simplified_presence_events:
+ client.add_event(modern_event)
+ elif client.slim_presence:
client.add_event(slim_event)
else:
client.add_event(legacy_event)
diff --git a/zerver/tornado/views.py b/zerver/tornado/views.py
index 4b7f2c149e4..f735ee01b0b 100644
--- a/zerver/tornado/views.py
+++ b/zerver/tornado/views.py
@@ -218,6 +218,10 @@ def get_events_backend(
Json[bool],
ApiParamConfig(documentation_status=DocumentationStatus.INTENTIONALLY_UNDOCUMENTED),
] = False,
+ simplified_presence_events: Annotated[
+ Json[bool],
+ ApiParamConfig(documentation_status=DocumentationStatus.INTENTIONALLY_UNDOCUMENTED),
+ ] = False,
) -> HttpResponse:
if narrow is None:
narrow = []
@@ -259,6 +263,7 @@ def get_events_backend(
include_deactivated_groups=include_deactivated_groups,
archived_channels=archived_channels,
empty_topic_name=empty_topic_name,
+ simplified_presence_events=simplified_presence_events,
)
result = in_tornado_thread(fetch_events)(