Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
presence: Restore legacy fields on single-user presence endpoint.
Tim Abbotta78abf7a96c8
diff --git a/api_docs/changelog.md b/api_docs/changelog.mdindex dddb2aca0cb..81af996d320 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 12.0+**Feature level 497**++* [`GET /users/{user_id_or_email}/presence`](/api/get-user-presence): The+ endpoint now additionally returns presence data in the legacy format,+ with `website` and `aggregated` keys, alongside the modern+ `active_timestamp` and `idle_timestamp` fields. Clients are recommended+ to migrate to the modern fields; the legacy fields are retained for+ backwards compatibility with integrations written against previous+ versions of the API.+* [`GET /users/{user_id_or_email}/presence`](/api/get-user-presence): The+ response now includes a top-level `server_timestamp` field, matching+ the behavior of other presence endpoints.+**Feature level 496*** [`GET /user_groups`](/api/get-user-groups),diff --git a/docs/overview/changelog.md b/docs/overview/changelog.mdindex 22822e756ef..1bb1fdc85ba 100644--- a/docs/overview/changelog.md+++ b/docs/overview/changelog.md@@ -204,13 +204,12 @@ _Released 2026-03-12_such groups will be created automatically when syncing the groupsfor a user who should be a member of that group.- The [`GET /api/v1/users/{user_id_or_email}/presence`](https://zulip.com/api/get-user-presence)- API endpoint was migrated to the modern presence API format that is- incompatible with the previous format. Custom API integrations that- fetch presence data for a user using this endpoint will need to be- updated after upgrading. (See the [API changelog][api-changelog] for- the dozens of other API changes in this release; this specific- change is notable only because backwards-compatibility was not- implemented, because the endpoint is rarely used).+ API endpoint now returns presence data in the modern format, in+ addition to the legacy format that it has always returned. Custom+ API integrations that fetch presence data for a user using this+ endpoint are encouraged to migrate to the modern `active_timestamp`+ and `idle_timestamp` fields, but the legacy `website` and+ `aggregated` dictionaries remain supported.[api-changelog]: https://zulip.com/api/changelog[docker-upgrade-to-12]: https://zulip.readthedocs.io/projects/docker/en/latest/how-to/compose-upgrading.html#upgrading-from-zulip-docker-zulip-11-x-and-earlierdiff --git a/version.py b/version.pyindex d3559c5ccd3..cbb61440d00 100644--- a/version.py+++ b/version.py@@ -33,7 +33,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"# https://zulip.readthedocs.io/en/latest/documentation/api.html#step-by-step-guide# Also available at docs/documentation/api.md.-API_FEATURE_LEVEL = 496+API_FEATURE_LEVEL = 497# 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. Bumpdiff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex 061844a34cc..32a422c5f07 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -11695,24 +11695,110 @@ paths:result: {}msg: {}ignored_parameters_unsupported: {}+ server_timestamp:+ type: number+ description: |+ The time when the server fetched the `presence` data+ included in the response. Matches the similar field+ in other presence responses.++ **Changes**: New in Zulip 12.0 (feature level+ ZF-25f246).presence:- allOf:- - $ref: "#/components/schemas/ModernPresenceFormat"+ type: object+ additionalProperties: falsedescription: |An object containing the presence details for the user.- **Changes**: In Zulip 12.0 (feature level 487), the- `active_timestamp` and `idle_timestamp` fields were added to- this object, deprecating and removing the `website` and- `aggregated` dictionaries, which contained a timestamp and- a status string.+ The object contains both the modern format fields+ (`active_timestamp` and `idle_timestamp`) and the legacy+ format fields (`website` and `aggregated` dictionaries,+ which contain a timestamp and a status string). New+ integrations should use the modern fields; the legacy+ fields are retained for backwards compatibility.++ **Changes**: In Zulip 12.0 (feature level 497),+ the `website` and `aggregated` legacy dictionaries were+ restored alongside the modern fields, for backwards+ compatibility with integrations written against earlier+ versions of the API.++ In Zulip 12.0 (feature level 487), the `active_timestamp`+ and `idle_timestamp` fields were added to this object, and+ the `website` and `aggregated` dictionaries were+ temporarily removed.+ required:+ - website+ - aggregated+ properties:+ active_timestamp:+ type: integer+ description: |+ The UNIX timestamp of the last time a client connected+ to Zulip reported that the user was actually present.+ idle_timestamp:+ type: integer+ description: |+ The UNIX timestamp of the last time the user had a+ client connected to Zulip, including idle clients.+ website:+ type: object+ additionalProperties: false+ description: |+ Presence details for the user in the legacy format.+ Starting with Zulip 7.0 (feature level 178), the+ `website` and `aggregated` dictionaries always contain+ identical data, since the server no longer stores which+ client submitted presence updates.+ properties:+ status:+ type: string+ enum:+ - idle+ - active+ description: |+ The status of the user. Will be either `"idle"` or+ `"active"`.+ timestamp:+ type: integer+ description: |+ The UNIX timestamp of when the user's presence data+ was last updated.+ aggregated:+ type: object+ additionalProperties: false+ description: |+ Presence details for the user in the legacy format.+ Unlike `website`, the `status` will be `"offline"` if+ the most recent presence update is older than the+ server's offline threshold.+ properties:+ status:+ type: string+ enum:+ - idle+ - active+ - offline+ description: |+ The status of the user. Will be either `"idle"`,+ `"active"`, or `"offline"`.+ timestamp:+ type: integer+ description: |+ The UNIX timestamp of when the user's presence data+ was last updated.example:{"msg": "",+ "server_timestamp": 1656958540.123,"presence":{"active_timestamp": 1656958520,"idle_timestamp": 1656958530,+ "website":+ {"status": "active", "timestamp": 1656958520},+ "aggregated":+ {"status": "active", "timestamp": 1656958520},},"result": "success",}diff --git a/zerver/tests/test_presence.py b/zerver/tests/test_presence.pyindex bfe87f6084e..05aba795a13 100644--- a/zerver/tests/test_presence.py+++ b/zerver/tests/test_presence.py@@ -735,31 +735,33 @@ class SingleUserPresenceTests(ZulipTestCase):result = self.client_get(f"/json/users/{othello.id}/presence")self.assert_json_error(result, "Insufficient permission")+ expected_keys = {"active_timestamp", "idle_timestamp", "website", "aggregated"}+result = self.client_get(f"/json/users/{othello.id}/presence")result_dict = self.assert_json_success(result)- self.assertEqual(- set(result_dict["presence"].keys()), {"active_timestamp", "idle_timestamp"}- )+ self.assertEqual(set(result_dict["presence"].keys()), expected_keys)self.assertIsInstance(result_dict["presence"]["active_timestamp"], int)self.assertIsInstance(result_dict["presence"]["idle_timestamp"], int)+ self.assertIsInstance(result_dict["server_timestamp"], float)+ self.assertEqual(set(result_dict["presence"]["website"].keys()), {"status", "timestamp"})# Then, we check everything worksself.login("hamlet")result = self.client_get("/json/users/[email protected]/presence")result_dict = self.assert_json_success(result)- self.assertEqual(- set(result_dict["presence"].keys()), {"active_timestamp", "idle_timestamp"}- )+ self.assertEqual(set(result_dict["presence"].keys()), expected_keys)self.assertIsInstance(result_dict["presence"]["active_timestamp"], int)self.assertIsInstance(result_dict["presence"]["idle_timestamp"], int)+ self.assertIsInstance(result_dict["server_timestamp"], float)+ self.assertEqual(set(result_dict["presence"]["website"].keys()), {"status", "timestamp"})result = self.client_get(f"/json/users/{othello.id}/presence")result_dict = self.assert_json_success(result)- self.assertEqual(- set(result_dict["presence"].keys()), {"active_timestamp", "idle_timestamp"}- )+ self.assertEqual(set(result_dict["presence"].keys()), expected_keys)self.assertIsInstance(result_dict["presence"]["active_timestamp"], int)self.assertIsInstance(result_dict["presence"]["idle_timestamp"], int)+ self.assertIsInstance(result_dict["server_timestamp"], float)+ self.assertEqual(set(result_dict["presence"]["website"].keys()), {"status", "timestamp"})def test_ping_only(self) -> None:self.login("othello")@@ -798,7 +800,19 @@ class UserPresenceAggregationTests(ZulipTestCase):HTTP_USER_AGENT="ZulipIOS/1.0",)latest_result_dict = self.assert_json_success(latest_result)- return latest_result_dict+ self.assertDictEqual(+ latest_result_dict["presences"][user.email]["aggregated"],+ {+ "status": status,+ "timestamp": datetime_to_timestamp(validate_time - timedelta(seconds=5)),+ # We no longer store the client information, but keep the field in these dicts,+ # with the value 'website' for backwards compatibility.+ "client": "website",+ },+ )++ result = self.client_get(f"/json/users/{user.email}/presence")+ return self.assert_json_success(result)def test_aggregated_info(self) -> None:user = self.example_user("othello")@@ -827,11 +841,10 @@ class UserPresenceAggregationTests(ZulipTestCase):validate_time = timezone_now()result_dict = self._send_presence_for_aggregated_tests(user, "active", validate_time)self.assertDictEqual(- result_dict["presences"][user.email]["aggregated"],+ result_dict["presence"]["aggregated"],{"status": "active","timestamp": datetime_to_timestamp(validate_time - timedelta(seconds=5)),- "client": "website",},)@@ -840,11 +853,10 @@ class UserPresenceAggregationTests(ZulipTestCase):validate_time = timezone_now()result_dict = self._send_presence_for_aggregated_tests(user, "idle", validate_time)self.assertDictEqual(- result_dict["presences"][user.email]["aggregated"],+ result_dict["presence"]["aggregated"],{"status": "idle","timestamp": datetime_to_timestamp(validate_time - timedelta(seconds=5)),- "client": "website",},)@@ -870,6 +882,29 @@ class UserPresenceAggregationTests(ZulipTestCase):},)+ def test_aggregated_presence_offline(self) -> None:+ user = self.example_user("othello")+ self.login_user(user)+ validate_time = timezone_now()+ self._send_presence_for_aggregated_tests(user, "idle", validate_time)++ with time_machine.travel(+ (validate_time + timedelta(seconds=settings.OFFLINE_THRESHOLD_SECS + 1)),+ tick=False,+ ):+ # After settings.OFFLINE_THRESHOLD_SECS + 1 this generated, recent presence data+ # will count as offline.+ result = self.client_get(f"/json/users/{user.email}/presence")+ result_dict = self.assert_json_success(result)++ self.assertDictEqual(+ result_dict["presence"]["aggregated"],+ {+ "status": "offline",+ "timestamp": datetime_to_timestamp(validate_time - timedelta(seconds=5)),+ },+ )+class GetRealmStatusesTest(ZulipTestCase):def test_get_statuses(self) -> None:diff --git a/zerver/views/presence.py b/zerver/views/presence.pyindex 88905fe8029..33f105e9f59 100644--- a/zerver/views/presence.py+++ b/zerver/views/presence.py@@ -1,3 +1,4 @@+import timefrom typing import Annotated, Anyfrom django.conf import settings@@ -10,9 +11,10 @@ from zerver.actions.presence import update_user_presencefrom zerver.actions.user_status import do_update_user_statusfrom zerver.decorator import human_users_onlyfrom zerver.lib.exceptions import JsonableError-from zerver.lib.presence import get_presence_for_user, get_presence_response+from zerver.lib.presence import get_presence_dicts_for_rows, get_presence_responsefrom zerver.lib.request import RequestNotesfrom zerver.lib.response import json_success+from zerver.lib.timestamp import datetime_to_timestampfrom zerver.lib.typed_endpoint import (ApiParamConfig,PathOnly,@@ -31,9 +33,6 @@ def get_presence_backend(user_profile: UserProfile,user_id_or_email: PathOnly[str],) -> HttpResponse:- # This isn't used by the web app; it's available for API use by- # bots and other clients.-try:try:user_id = int(user_id_or_email)@@ -56,14 +55,40 @@ def get_presence_backend():raise JsonableError(_("Insufficient permission"))- presence_dict = get_presence_for_user(target.id, slim_presence=True)- if len(presence_dict) == 0:+ server_timestamp = time.time()+ # Other callers of get_presence_dicts_for_rows also fetch+ # user_profile__enable_offline_push_notifications, but it is no+ # longer read by the helper (the legacy `pushable` field is+ # hardcoded to False), so we omit it here.+ presence_rows = list(+ UserPresence.objects.filter(user_profile_id=target.id).values(+ "last_active_time",+ "last_connected_time",+ "user_profile__email",+ "user_profile_id",+ "user_profile__date_joined",+ )+ )+ if not presence_rows:raise JsonableError(_("No presence data for {user_id_or_email}").format(user_id_or_email=user_id_or_email))-- result = dict(presence=presence_dict[str(target.id)])- return json_success(request, data=result)+ modern_presence = get_presence_dicts_for_rows(presence_rows, slim_presence=True)[str(target.id)]+ legacy_presence = get_presence_dicts_for_rows(presence_rows, slim_presence=False)[target.email]++ # The legacy API reports "offline" in the aggregated dict when the+ # user's latest presence update is older than OFFLINE_THRESHOLD_SECS.+ # The modern format leaves that computation to the client.+ aggregated_info = legacy_presence["aggregated"]+ aggr_status_duration = datetime_to_timestamp(timezone_now()) - aggregated_info["timestamp"]+ if aggr_status_duration > settings.OFFLINE_THRESHOLD_SECS:+ aggregated_info["status"] = "offline"+ for val in legacy_presence.values():+ val.pop("client", None)+ val.pop("pushable", None)++ presence = {**modern_presence, **legacy_presence}+ return json_success(request, data={"presence": presence, "server_timestamp": server_timestamp})def get_status_backend(