Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
presence: Always return modern format from single-user presence API.
Agnish Bauri4c3aa4c007ef
diff --git a/api_docs/changelog.md b/api_docs/changelog.mdindex 0e16cda85fe..2014a87bd13 100644--- a/api_docs/changelog.md+++ b/api_docs/changelog.md@@ -20,6 +20,13 @@ format used by the Zulip server that they are interacting with.## Changes in Zulip 12.0+**Feature level 487**++* [`GET /users/{user_id_or_email}/presence`](/api/get-user-presence): The+ endpoint now returns presence data in the modern format, with+ `active_timestamp` and `idle_timestamp` fields. Previously, a legacy+ format for presence data was returned, with `website` and `aggregated` keys.+**Feature level 486*** [`POST /register`](/api/register-queue): Added new `klipy_api_key`diff --git a/version.py b/version.pyindex 498e9720436..57d8018a8ac 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 = 486+API_FEATURE_LEVEL = 487# 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/lib/presence.py b/zerver/lib/presence.pyindex df6051a5422..57d66d4e576 100644--- a/zerver/lib/presence.py+++ b/zerver/lib/presence.py@@ -17,12 +17,11 @@ def get_presence_dicts_for_rows() -> dict[str, dict[str, Any]]:# This function takes the presence data fetched from the database and# turn it into an appropriate format for the API to return to clients.- # Used by the two endpoints that conduct realm-wide presence fetch:- # 1) `POST /users/me/presence`: https://zulip.com/api/update-presenc+ # Used by the endpoints that fetch presence data:+ # 1) `POST /users/me/presence`: https://zulip.com/api/update-presence# 2) `POST /register` when presence data is requested:# https://zulip.com/api/register-queue- # TODO: For consistency, we likely also should be using this for formatting- # presence data for https://zulip.com/api/get-user-presence+ # 3) `GET /users/{user_id_or_email}/presence`: https://zulip.com/api/get-user-presenceif slim_presence:# Stringify user_id here, since it's gonna be turned# into a string anyway by JSON, and it keeps mypy happy.diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex 6f0f8a66923..b5fedbaa356 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -11325,48 +11325,26 @@ paths:msg: {}ignored_parameters_unsupported: {}presence:- type: object+ allOf:+ - $ref: "#/components/schemas/ModernPresenceFormat"description: |An object containing the presence details for the user.- additionalProperties:- type: object- additionalProperties: false- properties:- timestamp:- type: integer- description: |- When this update was received. If the timestamp- is more than a few minutes in the past, the user is offline.- status:- type: string- description: |- Whether the user had recently interacted with Zulip at the time- of the timestamp.-- Will be either `"active"` or `"idle"`- description: |- `{client_name}` or `"aggregated"`: Object containing the details of the user's- presence.-- **Changes**: Starting with Zulip 7.0 (feature level 178), this will always- contain two keys, `"website"` and `"aggregated"`, with identical data. The- server no longer stores which client submitted presence updates.- Previously, the `{client_name}` keys for these objects were the names of the- different clients where the user was logged in, for example `website` or- `ZulipDesktop`.- example:+ **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.+ example:+ {+ "msg": "",+ "presence":{- "presence":- {- "website":- {"timestamp": 1532697622, "status": "active"},- "aggregated":- {"timestamp": 1532697622, "status": "active"},- },- "result": "success",- "msg": "",- }+ "active_timestamp": 1656958520,+ "idle_timestamp": 1656958530,+ },+ "result": "success",+ }/users/me:get:operationId: get-own-userdiff --git a/zerver/tests/test_presence.py b/zerver/tests/test_presence.pyindex 3b54262548a..bfe87f6084e 100644--- a/zerver/tests/test_presence.py+++ b/zerver/tests/test_presence.py@@ -615,7 +615,7 @@ class UserPresenceTests(ZulipTestCase):# Ensure date_joined was used as the fallback.self.assertEqual(- result_dict["presence"]["website"]["timestamp"],+ result_dict["presence"]["active_timestamp"],datetime_to_timestamp(othello.date_joined),)@@ -737,20 +737,29 @@ class SingleUserPresenceTests(ZulipTestCase):result = self.client_get(f"/json/users/{othello.id}/presence")result_dict = self.assert_json_success(result)- self.assertEqual(set(result_dict["presence"].keys()), {"website", "aggregated"})- self.assertEqual(set(result_dict["presence"]["website"].keys()), {"status", "timestamp"})+ self.assertEqual(+ set(result_dict["presence"].keys()), {"active_timestamp", "idle_timestamp"}+ )+ self.assertIsInstance(result_dict["presence"]["active_timestamp"], int)+ self.assertIsInstance(result_dict["presence"]["idle_timestamp"], int)# 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()), {"website", "aggregated"})- self.assertEqual(set(result_dict["presence"]["website"].keys()), {"status", "timestamp"})+ self.assertEqual(+ set(result_dict["presence"].keys()), {"active_timestamp", "idle_timestamp"}+ )+ self.assertIsInstance(result_dict["presence"]["active_timestamp"], int)+ self.assertIsInstance(result_dict["presence"]["idle_timestamp"], int)result = self.client_get(f"/json/users/{othello.id}/presence")result_dict = self.assert_json_success(result)- self.assertEqual(set(result_dict["presence"].keys()), {"website", "aggregated"})- self.assertEqual(set(result_dict["presence"]["website"].keys()), {"status", "timestamp"})+ self.assertEqual(+ set(result_dict["presence"].keys()), {"active_timestamp", "idle_timestamp"}+ )+ self.assertIsInstance(result_dict["presence"]["active_timestamp"], int)+ self.assertIsInstance(result_dict["presence"]["idle_timestamp"], int)def test_ping_only(self) -> None:self.login("othello")@@ -789,19 +798,7 @@ class UserPresenceAggregationTests(ZulipTestCase):HTTP_USER_AGENT="ZulipIOS/1.0",)latest_result_dict = self.assert_json_success(latest_result)- 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)+ return latest_result_dictdef test_aggregated_info(self) -> None:user = self.example_user("othello")@@ -830,10 +827,11 @@ class UserPresenceAggregationTests(ZulipTestCase):validate_time = timezone_now()result_dict = self._send_presence_for_aggregated_tests(user, "active", validate_time)self.assertDictEqual(- result_dict["presence"]["aggregated"],+ result_dict["presences"][user.email]["aggregated"],{"status": "active","timestamp": datetime_to_timestamp(validate_time - timedelta(seconds=5)),+ "client": "website",},)@@ -842,10 +840,11 @@ class UserPresenceAggregationTests(ZulipTestCase):validate_time = timezone_now()result_dict = self._send_presence_for_aggregated_tests(user, "idle", validate_time)self.assertDictEqual(- result_dict["presence"]["aggregated"],+ result_dict["presences"][user.email]["aggregated"],{"status": "idle","timestamp": datetime_to_timestamp(validate_time - timedelta(seconds=5)),+ "client": "website",},)@@ -871,29 +870,6 @@ class UserPresenceAggregationTests(ZulipTestCase):},)- def test_aggregated_presence_offline(self) -> None:- user = self.example_user("othello")- self.login_user(user)- validate_time = timezone_now()- result_dict = 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 d22870cc9dc..88905fe8029 100644--- a/zerver/views/presence.py+++ b/zerver/views/presence.py@@ -13,20 +13,26 @@ from zerver.lib.exceptions import JsonableErrorfrom zerver.lib.presence import get_presence_for_user, get_presence_responsefrom zerver.lib.request import RequestNotesfrom zerver.lib.response import json_success-from zerver.lib.timestamp import datetime_to_timestamp-from zerver.lib.typed_endpoint import ApiParamConfig, PathOnly, typed_endpoint+from zerver.lib.typed_endpoint import (+ ApiParamConfig,+ PathOnly,+ typed_endpoint,+ typed_endpoint_without_parameters,+)from zerver.lib.user_status import check_update_user_status, get_user_statusfrom zerver.lib.users import access_user_by_id, check_can_access_userfrom zerver.models import UserPresence, UserProfilefrom zerver.models.users import get_active_user, get_active_user_profile_by_id_in_realm+@typed_endpoint_without_parametersdef get_presence_backend(- request: HttpRequest, user_profile: UserProfile, user_id_or_email: str+ request: HttpRequest,+ 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. We may want to add slim_presence- # support for it (or just migrate its API wholesale) later.+ # bots and other clients.try:try:@@ -50,21 +56,13 @@ def get_presence_backend():raise JsonableError(_("Insufficient permission"))- presence_dict = get_presence_for_user(target.id)+ presence_dict = get_presence_for_user(target.id, slim_presence=True)if len(presence_dict) == 0:raise JsonableError(_("No presence data for {user_id_or_email}").format(user_id_or_email=user_id_or_email))- # For initial version, we just include the status and timestamp keys- result = dict(presence=presence_dict[target.email])- aggregated_info = result["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 result["presence"].values():- val.pop("client", None)- val.pop("pushable", None)+ result = dict(presence=presence_dict[str(target.id)])return json_success(request, data=result)