Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
devices: Add `devices` map in `/register` response & event to update it.
Prakhar Pratyush75e70b61532a
diff --git a/api_docs/unmerged.d/ZF-42fbcd.md b/api_docs/unmerged.d/ZF-42fbcd.mdindex 6a4ff8a0333..8fc1992fe82 100644--- a/api_docs/unmerged.d/ZF-42fbcd.md+++ b/api_docs/unmerged.d/ZF-42fbcd.md@@ -1,2 +1,6 @@* [`POST /register_client_device`](/api/register-client-device):Added a new endpoint to register a logged-in device.+* [`POST /register`](/api/register-queue): Added `devices`+ field to response.+* [`GET /events`](/api/get-events): A `device` event is sent+ to clients to live-update the `devices` dictionary.diff --git a/zerver/actions/devices.py b/zerver/actions/devices.pynew file mode 100644index 00000000000..a1c5291789a--- /dev/null+++ b/zerver/actions/devices.py@@ -0,0 +1,14 @@+from zerver.models.devices import Device+from zerver.models.users import UserProfile+from zerver.tornado.django_api import send_event_on_commit+++def do_register_device(user_profile: UserProfile) -> int:+ device = Device.objects.create(user=user_profile)+ event = dict(+ type="device",+ op="add",+ device_id=device.id,+ )+ send_event_on_commit(user_profile.realm, event, [user_profile.id])+ return device.iddiff --git a/zerver/lib/devices.py b/zerver/lib/devices.pynew file mode 100644index 00000000000..8c54ca8860c--- /dev/null+++ b/zerver/lib/devices.py@@ -0,0 +1,49 @@+import base64++from typing_extensions import TypedDict++from zerver.lib.timestamp import datetime_to_timestamp+from zerver.models.devices import Device+from zerver.models.users import UserProfile+++class DeviceInfoDict(TypedDict):+ push_key_id: int | None+ push_token_id: str | None+ pending_push_token_id: str | None+ push_token_last_updated_timestamp: int | None+ push_registration_error_code: str | None+++def b64encode_token_id_int(token_id_int: int) -> str:+ token_id_bytes = token_id_int.to_bytes(8, byteorder="big", signed=True)+ return base64.b64encode(token_id_bytes).decode()+++def get_devices(user_profile: UserProfile) -> dict[str, DeviceInfoDict]:+ devices = Device.objects.filter(user=user_profile)++ devices_dict: dict[str, DeviceInfoDict] = dict()+ for device in devices:+ push_token_id_base64 = None+ pending_push_token_id_base64 = None+ push_token_last_updated_timestamp = None++ if device.push_token_id is not None:+ push_token_id_base64 = b64encode_token_id_int(device.push_token_id)+ if device.pending_push_token_id is not None:+ pending_push_token_id_base64 = b64encode_token_id_int(device.pending_push_token_id)+ if device.push_token_last_updated_timestamp is not None:+ push_token_last_updated_timestamp = datetime_to_timestamp(+ device.push_token_last_updated_timestamp+ )++ devices_dict[str(device.id)] = DeviceInfoDict(+ push_key_id=device.push_key_id,+ push_token_id=push_token_id_base64,+ pending_push_token_id=pending_push_token_id_base64,+ push_token_last_updated_timestamp=push_token_last_updated_timestamp,+ push_registration_error_code=device.push_registration_error_code,+ )++ return devices_dictdiff --git a/zerver/lib/event_schema.py b/zerver/lib/event_schema.pyindex 3bec42a18f9..9c25dfc3b1d 100644--- a/zerver/lib/event_schema.py+++ b/zerver/lib/event_schema.py@@ -30,6 +30,7 @@ from zerver.lib.event_types import (EventDefaultStreamGroups,EventDefaultStreams,EventDeleteMessage,+ EventDeviceAdd,EventDirectMessage,EventDraftsAdd,EventDraftsRemove,@@ -175,6 +176,7 @@ check_channel_folder_reorder = make_checker(EventChannelFolderReorder)check_custom_profile_fields = make_checker(EventCustomProfileFields)check_default_stream_groups = make_checker(EventDefaultStreamGroups)check_default_streams = make_checker(EventDefaultStreams)+check_device_add = make_checker(EventDeviceAdd)check_direct_message = make_checker(EventDirectMessage)check_draft_add = make_checker(EventDraftsAdd)check_draft_remove = make_checker(EventDraftsRemove)diff --git a/zerver/lib/event_types.py b/zerver/lib/event_types.pyindex 7729a1d9534..b106d2093fc 100644--- a/zerver/lib/event_types.py+++ b/zerver/lib/event_types.py@@ -297,6 +297,12 @@ class EventPushDevice(BaseEvent):error_code: str | None = None+class EventDeviceAdd(BaseEvent):+ type: Literal["device"]+ op: Literal["add"]+ device_id: int++class NavigationViewFields(BaseModel):fragment: stris_pinned: booldiff --git a/zerver/lib/events.py b/zerver/lib/events.pyindex 41ffbd1cc47..e870e01c3a2 100644--- a/zerver/lib/events.py+++ b/zerver/lib/events.py@@ -29,6 +29,7 @@ from zerver.lib.channel_folders import ()from zerver.lib.compatibility import is_outdated_serverfrom zerver.lib.default_streams import get_default_stream_ids_for_realm+from zerver.lib.devices import get_devicesfrom zerver.lib.exceptions import JsonableErrorfrom zerver.lib.external_accounts import get_default_external_accountsfrom zerver.lib.i18n import get_available_language_codes@@ -951,6 +952,9 @@ def fetch_initial_state_data(if want("push_device"):state["push_devices"] = {} if user_profile is None else get_push_devices(user_profile)+ if want("device"):+ state["devices"] = {} if user_profile is None else get_devices(user_profile)+if user_profile is None:# To ensure we have the correct user state set.assert state["is_admin"] is False@@ -2016,6 +2020,17 @@ def apply_event(elif event["type"] == "push_device":state["push_devices"][str(event["push_account_id"])]["status"] = event["status"]state["push_devices"][str(event["push_account_id"])]["error_code"] = event.get("error_code")+ elif event["type"] == "device":+ if event["op"] == "add":+ state["devices"][str(event["device_id"])] = {+ "push_key_id": None,+ "push_token_id": None,+ "pending_push_token_id": None,+ "push_token_last_updated_timestamp": None,+ "push_registration_error_code": None,+ }+ else:+ raise AssertionError("Unexpected event type {type}/{op}".format(**event))else:raise AssertionError("Unexpected event type {}".format(event["type"]))diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex b77b812fba1..f2144ea5f56 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -1848,6 +1848,70 @@ paths:"push_account_id": 1234,"status": "active",}+ - type: object+ additionalProperties: false+ description: |+ Event sent to a user's clients when they [register a device](/api/register-client-device).++ Helps clients to live-update the `devices` dictionary+ returned in [`POST /register`](/api/register-queue) response.++ **Changes**: New in Zulip 12.0 (feature level ZF-42fbcd).+ properties:+ id:+ $ref: "#/components/schemas/EventIdSchema"+ type:+ allOf:+ - $ref: "#/components/schemas/EventTypeSchema"+ - enum:+ - device+ op:+ type: string+ enum:+ - add+ device_id:+ type: integer+ description: |+ The ID of the new registered device.+ example:+ {+ "id": 1,+ "type": "device",+ "op": "add",+ "device_id": 1144,+ }+ - type: object+ additionalProperties: false+ description: |+ Event sent to a user's clients when they deregister a device.++ Helps clients to live-update the `devices` dictionary+ returned in [`POST /register`](/api/register-queue) response.++ **Changes**: New in Zulip 12.0 (feature level ZF-42fbcd).+ properties:+ id:+ $ref: "#/components/schemas/EventIdSchema"+ type:+ allOf:+ - $ref: "#/components/schemas/EventTypeSchema"+ - enum:+ - device+ op:+ type: string+ enum:+ - remove+ device_id:+ type: integer+ description: |+ The ID of the device which deregistered.+ example:+ {+ "id": 1,+ "type": "device",+ "op": "remove",+ "device_id": 1144,+ }- type: objectadditionalProperties: falsedescription: |@@ -18561,6 +18625,58 @@ paths:The following error codes have recommended client behavior:+ - `"INVALID_BOUNCER_PUBLIC_KEY"` - Inform the user to update app.+ - `"REQUEST_EXPIRED` - Retry with a fresh payload.+ devices:+ type: object+ description: |+ Present if `device` is present in `fetch_event_types`.++ Dictionary where each entry describes the user's logged-in devices,+ registered using [`POST /register_client_device`](/api/register-client-device).++ **Changes**: New in Zulip 12.0 (feature level ZF-42fbcd).+ additionalProperties:+ description: |+ `{device_id}`: Dictionary containing the details of+ a device with the device ID as the key.+ type: object+ additionalProperties: false+ properties:+ push_key_id:+ type: integer+ nullable: true+ description: |+ ID to reference the encryption key used to encrypt+ push notifications sent to the device.+ push_token_id:+ type: string+ nullable: true+ description: |+ ID to reference the token provided by FCM/APNs to the device,+ which is registered to the push bouncer service.+ pending_push_token_id:+ type: string+ nullable: true+ description: |+ ID to reference the token provided by FCM/APNs to the device,+ whose registration is in progress to the push bouncer service.+ push_token_last_updated_timestamp:+ type: integer+ nullable: true+ description: |+ The UNIX timestamp for the last time when `pending_push_token_id`+ was set to a new non-null value, in UTC seconds.+ push_registration_error_code:+ type: string+ nullable: true+ description: |+ If the push registration failed, a [Zulip API error+ code](/api/rest-error-handling) indicating the type of+ failure that occurred.++ The following error codes have recommended client behavior:+- `"INVALID_BOUNCER_PUBLIC_KEY"` - Inform the user to update app.- `"REQUEST_EXPIRED` - Retry with a fresh payload.receives_typing_notifications:diff --git a/zerver/tests/test_event_system.py b/zerver/tests/test_event_system.pyindex 525d25f13c4..65719d14ef5 100644--- a/zerver/tests/test_event_system.py+++ b/zerver/tests/test_event_system.py@@ -1223,7 +1223,7 @@ class FetchQueriesTest(ZulipTestCase):self.login_user(user)with (- self.assert_database_query_count(48),+ self.assert_database_query_count(49),mock.patch("zerver.lib.events.always_want") as want_mock,):fetch_initial_state_data(user, realm=user.realm)@@ -1234,6 +1234,7 @@ class FetchQueriesTest(ZulipTestCase):custom_profile_fields=1,default_streams=1,default_stream_groups=1,+ device=1,drafts=1,giphy=0,tenor=0,diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.pyindex 85a2b849f99..3389bcb4648 100644--- a/zerver/tests/test_events.py+++ b/zerver/tests/test_events.py@@ -54,6 +54,7 @@ from zerver.actions.default_streams import (do_remove_streams_from_default_stream_group,lookup_default_stream_groups,)+from zerver.actions.devices import do_register_devicefrom zerver.actions.invites import (do_create_multiuse_invite_link,do_invite_users,@@ -176,6 +177,7 @@ from zerver.lib.event_schema import (check_default_stream_groups,check_default_streams,check_delete_message,+ check_device_add,check_direct_message,check_draft_add,check_draft_remove,@@ -4315,6 +4317,11 @@ class NormalActionsTest(BaseAction):self.assertEqual(events[0]["status"], "failed")self.assertEqual(events[0]["error_code"], "INVALID_BOUNCER_PUBLIC_KEY")+ def test_register_device(self) -> None:+ with self.verify_action() as events:+ do_register_device(self.user_profile)+ check_device_add("events[0]", events[0])+def test_notify_realm_export_on_failure(self) -> None:self.set_user_role(self.user_profile, UserProfile.ROLE_REALM_ADMINISTRATOR)self.login_user(self.user_profile)diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.pyindex 91b94ca8425..4d85a296422 100644--- a/zerver/tests/test_home.py+++ b/zerver/tests/test_home.py@@ -84,6 +84,7 @@ class HomeTest(ZulipTestCase):"custom_profile_fields","delivery_email","development_environment",+ "devices","drafts","email","event_queue_longpoll_timeout_seconds",@@ -298,7 +299,7 @@ class HomeTest(ZulipTestCase):# Verify succeeds once logged-inwith (- self.assert_database_query_count(58),+ self.assert_database_query_count(59),patch("zerver.lib.cache.cache_set") as cache_mock,):result = self._get_home_page(stream="Denmark")@@ -605,7 +606,7 @@ class HomeTest(ZulipTestCase):# Verify number of queries for Realm admin isn't much higher than for normal users.self.login("iago")with (- self.assert_database_query_count(57),+ self.assert_database_query_count(58),patch("zerver.lib.cache.cache_set") as cache_mock,):result = self._get_home_page()@@ -637,7 +638,7 @@ class HomeTest(ZulipTestCase):self._get_home_page()# Then for the second page load, measure the number of queries.- with self.assert_database_query_count(53):+ with self.assert_database_query_count(54):result = self._get_home_page()# Do a sanity check that our new streams were in the payload.diff --git a/zerver/views/devices.py b/zerver/views/devices.pyindex dee99ca38a0..ccafddbc8dd 100644--- a/zerver/views/devices.py+++ b/zerver/views/devices.py@@ -1,12 +1,12 @@from django.http import HttpRequest, HttpResponse+from zerver.actions.devices import do_register_devicefrom zerver.lib.response import json_successfrom zerver.lib.typed_endpoint import typed_endpoint_without_parameters-from zerver.models.devices import Devicefrom zerver.models.users import UserProfile@typed_endpoint_without_parametersdef register_device(request: HttpRequest, user_profile: UserProfile) -> HttpResponse:- device = Device.objects.create(user=user_profile)- return json_success(request, data={"device_id": device.id})+ device_id = do_register_device(user_profile)+ return json_success(request, data={"device_id": device_id})