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.

realm_emoji: Add a capability for emoji /add and /update_one.

Alex Vandiver559c0cad2870
diff --git a/api_docs/changelog.md b/api_docs/changelog.md
index d7a7cca9e8a..a907b9db115 100644
--- a/api_docs/changelog.md
+++ b/api_docs/changelog.md
@@ -20,6 +20,22 @@ format used by the Zulip server that they are interacting with.
## Changes in Zulip 12.0
+**Feature level 491**
+
+* [`GET /events`](/api/get-events): A new `individual_emoji_changes`
+ client capability has been added. Clients advertising this
+ capability will not receive `realm_emoji/update` events with the
+ state of all emoji whenever there is a change; instead they will
+ receive more granular `realm_emoji/add` and `realm_emoji/update_one`
+ events. The `realm_emoji/add` event sends the full emoji data for
+ the newly added emoji. The `realm_emoji/update_one` event sends only
+ the `emoji_id` and the properties being changed (currently only
+ `deactivated`), rather than the full emoji data.
+
+ Clients that do not set the `individual_emoji_changes` client
+ capability will continue to receive the legacy `realm_emoji/update`
+ event containing all emoji.
+
**Feature level 490**
* [`GET /users`](/api/get-users), [`GET /users/{user_id}`](/api/get-user),
diff --git a/version.py b/version.py
index a34590c28ff..958bc6726c9 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 = 490
+API_FEATURE_LEVEL = 491
# 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/realm_emoji.py b/zerver/actions/realm_emoji.py
index 3b6cdac8637..da3f5bc2863 100644
--- a/zerver/actions/realm_emoji.py
+++ b/zerver/actions/realm_emoji.py
@@ -13,16 +13,11 @@ from zerver.lib.thumbnail import THUMBNAIL_ACCEPT_IMAGE_TYPES, BadImageError
from zerver.lib.upload import upload_emoji_image
from zerver.models import Realm, RealmAuditLog, RealmEmoji, UserProfile
from zerver.models.realm_audit_logs import AuditLogEventType
-from zerver.models.realm_emoji import EmojiInfo, get_all_custom_emoji_for_realm
+from zerver.models.realm_emoji import emoji_as_emojiinfo, get_all_custom_emoji_for_realm
from zerver.models.users import active_user_ids
from zerver.tornado.django_api import send_event_on_commit
-def notify_realm_emoji(realm: Realm, realm_emoji: dict[str, EmojiInfo]) -> None:
- event = dict(type="realm_emoji", op="update", realm_emoji=realm_emoji)
- send_event_on_commit(realm, event, active_user_ids(realm.id))
-
-
@transaction.atomic(durable=True)
def check_add_realm_emoji(
realm: Realm, name: str, author: UserProfile, image_file: IO[bytes], content_type: str
@@ -52,17 +47,21 @@ def check_add_realm_emoji(
realm_emoji.is_animated = is_animated
realm_emoji.save(update_fields=["file_name", "is_animated"])
- realm_emoji_dict = get_all_custom_emoji_for_realm(realm.id)
+ new_emoji = emoji_as_emojiinfo(realm_emoji)
RealmAuditLog.objects.create(
realm=realm,
acting_user=author,
event_type=AuditLogEventType.REALM_EMOJI_ADDED,
event_time=timezone_now(),
extra_data={
- "added_emoji": realm_emoji_dict[str(realm_emoji.id)],
+ "added_emoji": new_emoji,
},
)
- notify_realm_emoji(realm_emoji.realm, realm_emoji_dict)
+ # TODO/compatibility: Remove realm_emoji_dict once we can require that clients support
+ # the individual_emoji_changes client capability.
+ realm_emoji_dict = get_all_custom_emoji_for_realm(realm.id)
+ event = dict(type="realm_emoji", op="add", emoji=new_emoji, realm_emoji=realm_emoji_dict)
+ send_event_on_commit(realm, event, active_user_ids(realm.id))
return realm_emoji
@@ -72,15 +71,27 @@ def do_remove_realm_emoji(realm: Realm, name: str, *, acting_user: UserProfile |
realm_emoji.deactivated = True
realm_emoji.save(update_fields=["deactivated"])
- realm_emoji_dict = get_all_custom_emoji_for_realm(realm.id)
+ deactivated_emoji = emoji_as_emojiinfo(realm_emoji)
RealmAuditLog.objects.create(
realm=realm,
acting_user=acting_user,
event_type=AuditLogEventType.REALM_EMOJI_REMOVED,
event_time=timezone_now(),
extra_data={
- "deactivated_emoji": realm_emoji_dict[str(realm_emoji.id)],
+ "deactivated_emoji": deactivated_emoji,
},
)
- notify_realm_emoji(realm, realm_emoji_dict)
+ # TODO/compatibility: Remove realm_emoji_dict once we can require that clients support
+ # the individual_emoji_changes client capability.
+ realm_emoji_dict = get_all_custom_emoji_for_realm(realm.id)
+ event = dict(
+ type="realm_emoji",
+ op="update_one",
+ emoji_id=str(realm_emoji.id),
+ data=dict(
+ deactivated=True,
+ ),
+ realm_emoji=realm_emoji_dict,
+ )
+ send_event_on_commit(realm, event, active_user_ids(realm.id))
diff --git a/zerver/lib/event_schema.py b/zerver/lib/event_schema.py
index a9e35e89a40..e81c9322453 100644
--- a/zerver/lib/event_schema.py
+++ b/zerver/lib/event_schema.py
@@ -58,7 +58,9 @@ from zerver.lib.event_types import (
EventRealmDomainsAdd,
EventRealmDomainsChange,
EventRealmDomainsRemove,
+ EventRealmEmojiAdd,
EventRealmEmojiUpdate,
+ EventRealmEmojiUpdateOne,
EventRealmExport,
EventRealmExportConsent,
EventRealmLinkifiers,
@@ -200,6 +202,8 @@ check_realm_deactivated = make_checker(EventRealmDeactivated)
check_realm_domains_add = make_checker(EventRealmDomainsAdd)
check_realm_domains_change = make_checker(EventRealmDomainsChange)
check_realm_domains_remove = make_checker(EventRealmDomainsRemove)
+check_realm_emoji_add = make_checker(EventRealmEmojiAdd)
+check_realm_emoji_update_one = make_checker(EventRealmEmojiUpdateOne)
check_realm_export_consent = make_checker(EventRealmExportConsent)
check_realm_linkifiers = make_checker(EventRealmLinkifiers)
check_realm_playgrounds = make_checker(EventRealmPlaygrounds)
diff --git a/zerver/lib/event_types.py b/zerver/lib/event_types.py
index 105e48066c6..3218ab9c416 100644
--- a/zerver/lib/event_types.py
+++ b/zerver/lib/event_types.py
@@ -478,6 +478,23 @@ class RealmEmoji(BaseModel):
still_url: str | None
+class EventRealmEmojiAdd(BaseEvent):
+ type: Literal["realm_emoji"]
+ op: Literal["add"]
+ emoji: RealmEmoji
+
+
+class RealmEmojiUpdateData(BaseModel):
+ deactivated: bool | None = None
+
+
+class EventRealmEmojiUpdateOne(BaseEvent):
+ type: Literal["realm_emoji"]
+ op: Literal["update_one"]
+ emoji_id: str
+ data: RealmEmojiUpdateData
+
+
class EventRealmEmojiUpdate(BaseEvent):
type: Literal["realm_emoji"]
op: Literal["update"]
diff --git a/zerver/lib/events.py b/zerver/lib/events.py
index b33b3b48546..97b63189e49 100644
--- a/zerver/lib/events.py
+++ b/zerver/lib/events.py
@@ -31,6 +31,7 @@ from zerver.lib.channel_folders import (
from zerver.lib.compatibility import is_outdated_server
from zerver.lib.default_streams import get_default_stream_ids_for_realm
from zerver.lib.devices import get_devices
+from zerver.lib.event_types import RealmEmojiUpdateData
from zerver.lib.exceptions import JsonableError
from zerver.lib.external_accounts import get_default_external_accounts
from zerver.lib.i18n import get_available_language_codes
@@ -1854,7 +1855,19 @@ def apply_event(
else:
raise AssertionError("Unexpected event type {type}/{op}".format(**event))
elif event["type"] == "realm_emoji":
- state["realm_emoji"] = event["realm_emoji"]
+ if event["op"] == "update":
+ # Legacy whole-list event for clients without
+ # the individual_emoji_changes capability.
+ state["realm_emoji"] = event["realm_emoji"]
+ elif event["op"] == "add":
+ state["realm_emoji"][event["emoji"]["id"]] = event["emoji"]
+ elif event["op"] == "update_one":
+ emoji_id = event["emoji_id"]
+ for key in RealmEmojiUpdateData.model_fields:
+ if key in event["data"]:
+ state["realm_emoji"][emoji_id][key] = event["data"][key]
+ else:
+ raise AssertionError("Unexpected event type {type}/{op}".format(**event))
elif event["type"] == "realm_export":
# These realm export events are only available to
# administrators, and aren't included in page_params.
@@ -2059,6 +2072,7 @@ class ClientCapabilities(TypedDict):
archived_channels: NotRequired[bool]
empty_topic_name: NotRequired[bool]
simplified_presence_events: NotRequired[bool]
+ individual_emoji_changes: NotRequired[bool]
# Deprecated and no longer has any effect
user_settings_object: NotRequired[bool]
@@ -2103,6 +2117,7 @@ def do_events_register(
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)
+ individual_emoji_changes = client_capabilities.get("individual_emoji_changes", False)
if fetch_event_types is not None:
event_types_set: set[str] | None = set(fetch_event_types)
@@ -2174,6 +2189,7 @@ def do_events_register(
archived_channels=archived_channels,
empty_topic_name=empty_topic_name,
simplified_presence_events=simplified_presence_events,
+ individual_emoji_changes=individual_emoji_changes,
)
if result is None:
diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yaml
index b4c33205b26..b5e6a9d859c 100644
--- a/zerver/openapi/zulip.yaml
+++ b/zerver/openapi/zulip.yaml
@@ -4332,6 +4332,104 @@ paths:
],
"id": 0,
}
+ - type: object
+ additionalProperties: false
+ description: |
+ Event sent to all users in a Zulip organization when
+ a [custom emoji](/help/custom-emoji) has been added.
+
+ Only sent to clients that set the
+ `individual_emoji_changes` client capability.
+
+ **Changes**: New in Zulip 12.0 (feature level ZF-dccf1a.md),
+ replacing half of the functionality of the
+ `realm_emoji/update` event.
+ properties:
+ id:
+ $ref: "#/components/schemas/EventIdSchema"
+ type:
+ allOf:
+ - $ref: "#/components/schemas/EventTypeSchema"
+ - enum:
+ - realm_emoji
+ op:
+ type: string
+ enum:
+ - add
+ emoji:
+ $ref: "#/components/schemas/RealmEmoji"
+ example:
+ {
+ "type": "realm_emoji",
+ "op": "add",
+ "emoji":
+ {
+ "id": "2",
+ "name": "my_emoji",
+ "source_url": "/user_avatars/2/emoji/images/2.png",
+ "still_url": null,
+ "deactivated": false,
+ "author_id": 11,
+ },
+ "id": 0,
+ }
+ - type: object
+ additionalProperties: false
+ description: |
+ Event sent to all users in a Zulip organization when
+ a property of a [custom emoji](/help/custom-emoji) has
+ been changed. Only the fields being updated are included
+ in the event.
+
+ Currently, the only property that can be updated is
+ `deactivated`, but this may be extended in the future.
+
+ Only sent to clients that set the
+ `individual_emoji_changes` client capability.
+
+ **Changes**: New in Zulip 12.0 (feature level ZF-dccf1a.md),
+ replacing half of the functionality of the
+ `realm_emoji/update` event.
+ properties:
+ id:
+ $ref: "#/components/schemas/EventIdSchema"
+ type:
+ allOf:
+ - $ref: "#/components/schemas/EventTypeSchema"
+ - enum:
+ - realm_emoji
+ op:
+ type: string
+ enum:
+ - update_one
+ emoji_id:
+ type: string
+ description: |
+ The ID of the custom emoji being updated.
+ data:
+ type: object
+ description: |
+ And object containing the properties that have changed.
+ properties:
+ deactivated:
+ type: boolean
+ description: |
+ Whether the custom emoji has been deactivated.
+ additionalProperties: false
+ required:
+ - id
+ - type
+ - op
+ - emoji_id
+ - data
+ example:
+ {
+ "type": "realm_emoji",
+ "op": "update_one",
+ "emoji_id": "2",
+ "data": {"deactivated": true},
+ "id": 0,
+ }
- type: object
additionalProperties: false
description: |
@@ -4341,6 +4439,16 @@ paths:
has been deactivated. The event contains all custom emoji
configured for the organization, not just the updated
custom emoji.
+
+ This legacy event is sent to clients that do not set
+ the `individual_emoji_changes` client capability.
+
+ **Changes**: Before Zulip 12.0 (feature level
+ ZF-dccf1a.md), this was the only format of
+ `realm_emoji` event sent. Clients should set the
+ `individual_emoji_changes` capability and handle
+ `realm_emoji/add` and `realm_emoji/edit` events
+ instead.
properties:
id:
$ref: "#/components/schemas/EventIdSchema"
@@ -17665,6 +17773,17 @@ paths:
<br />
**Changes**: New in Zulip 11.0 (feature level 419).
+ - `individual_emoji_changes`: Boolean for whether the client supports
+ receiving the [`realm_emoji/add` and `realm_emoji/edit` event
+ types](/api/get-events#realm_emoji-add). If true, the server will
+ send individual `realm_emoji/add` events when a custom emoji is
+ added, and `realm_emoji/edit` events when a custom emoji's
+ properties are changed (e.g., deactivated). Otherwise, the server
+ will send the legacy `realm_emoji/update` event containing all
+ custom emoji for the organization.
+ <br />
+ **Changes**: New in Zulip 12.0 (feature level ZF-dccf1a.md).
+
[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_event_system.py b/zerver/tests/test_event_system.py
index 06b12bcdbcd..8e4732440f9 100644
--- a/zerver/tests/test_event_system.py
+++ b/zerver/tests/test_event_system.py
@@ -99,8 +99,15 @@ class EventsEndpointTest(ZulipTestCase):
# We choose realm_emoji somewhat randomly--we want
# a "boring" event type for the purpose of this test.
event_type = "realm_emoji"
- empty_realm_emoji_dict: dict[str, Any] = {}
- test_event = dict(id=6, type=event_type, realm_emoji=empty_realm_emoji_dict)
+ test_realm_emoji: dict[str, Any] = {
+ "id": "1",
+ "name": "spain",
+ "source_url": "http://example.com/",
+ "still_url": None,
+ "deactivated": False,
+ "author_id": user.id,
+ }
+ test_event = dict(id=6, type=event_type, op="add", emoji=test_realm_emoji)
# Test that call is made to deal with a returning soft deactivated user.
with (
@@ -135,7 +142,7 @@ class EventsEndpointTest(ZulipTestCase):
self.assertEqual(result_dict["queue_id"], "15:12")
# sanity check the data relevant to our event
- self.assertEqual(result_dict["realm_emoji"], {})
+ self.assertEqual(result_dict["realm_emoji"], {"1": test_realm_emoji})
# Now test with `fetch_event_types` not matching the event
return_event_queue.queue_id = "15:13"
@@ -174,7 +181,7 @@ class EventsEndpointTest(ZulipTestCase):
# Check that the realm_emoji data is in there.
self.assertIn("realm_emoji", result_dict)
- self.assertEqual(result_dict["realm_emoji"], {})
+ self.assertEqual(result_dict["realm_emoji"], {"1": test_realm_emoji})
self.assertEqual(result_dict["queue_id"], "15:13")
def test_idle_queue_timeout(self) -> None:
diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py
index 79f266300f3..0c92a78e93f 100644
--- a/zerver/tests/test_events.py
+++ b/zerver/tests/test_events.py
@@ -206,7 +206,9 @@ from zerver.lib.event_schema import (
check_realm_domains_add,
check_realm_domains_change,
check_realm_domains_remove,
+ check_realm_emoji_add,
check_realm_emoji_update,
+ check_realm_emoji_update_one,
check_realm_export,
check_realm_export_consent,
check_realm_linkifiers,
@@ -359,6 +361,7 @@ class BaseAction(ZulipTestCase):
archived_channels: bool = False,
allow_empty_topic_name: bool = True,
simplified_presence_events: bool = False,
+ individual_emoji_changes: bool = True,
) -> Iterator[list[dict[str, Any]]]:
"""
Make sure we have a clean slate of client descriptors for these tests.
@@ -392,6 +395,7 @@ class BaseAction(ZulipTestCase):
include_deactivated_groups=include_deactivated_groups,
archived_channels=archived_channels,
simplified_presence_events=simplified_presence_events,
+ individual_emoji_changes=individual_emoji_changes,
)
)
@@ -3342,10 +3346,26 @@ class NormalActionsTest(BaseAction):
check_add_realm_emoji(
self.user_profile.realm, "my_emoji", author, img_file, "image/png"
)
+ check_realm_emoji_add("events[0]", events[0])
+ with self.verify_action() as events:
+ do_remove_realm_emoji(
+ self.user_profile.realm, "my_emoji", acting_user=self.user_profile
+ )
+ check_realm_emoji_update_one("events[0]", events[0])
+
+ def test_realm_emoji_events_legacy(self) -> None:
+ author = self.example_user("iago")
+ with (
+ get_test_image_file("img.png") as img_file,
+ self.verify_action(individual_emoji_changes=False) as events,
+ ):
+ check_add_realm_emoji(
+ self.user_profile.realm, "my_emoji", author, img_file, "image/png"
+ )
check_realm_emoji_update("events[0]", events[0])
- with self.verify_action() as events:
+ with self.verify_action(individual_emoji_changes=False) as events:
do_remove_realm_emoji(
self.user_profile.realm, "my_emoji", acting_user=self.user_profile
)
diff --git a/zerver/tornado/django_api.py b/zerver/tornado/django_api.py
index edf1a369cd9..f30f7ae9230 100644
--- a/zerver/tornado/django_api.py
+++ b/zerver/tornado/django_api.py
@@ -101,6 +101,7 @@ def request_event_queue(
archived_channels: bool = False,
empty_topic_name: bool = False,
simplified_presence_events: bool = False,
+ individual_emoji_changes: bool = False,
) -> EventQueueData | None:
if not settings.USING_TORNADO:
return None
@@ -131,6 +132,7 @@ def request_event_queue(
"archived_channels": orjson.dumps(archived_channels),
"empty_topic_name": orjson.dumps(empty_topic_name),
"simplified_presence_events": orjson.dumps(simplified_presence_events),
+ "individual_emoji_changes": orjson.dumps(individual_emoji_changes),
}
if idle_queue_timeout is not None:
diff --git a/zerver/tornado/event_queue.py b/zerver/tornado/event_queue.py
index fefe20318c5..c00878fc067 100644
--- a/zerver/tornado/event_queue.py
+++ b/zerver/tornado/event_queue.py
@@ -95,6 +95,7 @@ class ClientDescriptor:
archived_channels: bool,
empty_topic_name: bool,
simplified_presence_events: bool,
+ individual_emoji_changes: bool,
) -> None:
# TODO: We eventually want to upstream this code to the caller, but
# serialization concerns make it a bit difficult.
@@ -128,6 +129,7 @@ class ClientDescriptor:
self.archived_channels = archived_channels
self.empty_topic_name = empty_topic_name
self.simplified_presence_events = simplified_presence_events
+ self.individual_emoji_changes = individual_emoji_changes
self.offline = False
# Default for idle_queue_timeout is DEFAULT_EVENT_QUEUE_TIMEOUT_SECS;
@@ -166,6 +168,7 @@ class ClientDescriptor:
archived_channels=self.archived_channels,
empty_topic_name=self.empty_topic_name,
simplified_presence_events=self.simplified_presence_events,
+ individual_emoji_changes=self.individual_emoji_changes,
offline=self.offline,
)
@@ -206,6 +209,7 @@ class ClientDescriptor:
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),
+ individual_emoji_changes=d.get("individual_emoji_changes", False),
)
ret.last_connection_time = d["last_connection_time"]
ret.offline = d.get("offline", False)
@@ -1383,6 +1387,24 @@ def process_presence_event(event: Mapping[str, Any], users: Iterable[int]) -> No
client.add_event(legacy_event)
+def process_realm_emoji_event(event: Mapping[str, Any], users: Iterable[int]) -> None:
+ # For clients that support individual emoji changes, send the
+ # event as-is (without the legacy realm_emoji field). For
+ # legacy clients, transform it into the old realm_emoji/update
+ # event containing the full emoji dict.
+ new_event = dict(event)
+ realm_emoji = new_event.pop("realm_emoji")
+ legacy_event = dict(type="realm_emoji", op="update", realm_emoji=realm_emoji)
+
+ for user_profile_id in users:
+ for client in get_client_descriptors_for_user(user_profile_id):
+ if client.accepts_event(event):
+ if client.individual_emoji_changes:
+ client.add_event(new_event)
+ else:
+ client.add_event(legacy_event)
+
+
def process_event(event: Mapping[str, Any], users: Iterable[int]) -> None:
for user_profile_id in users:
for client in get_client_descriptors_for_user(user_profile_id):
@@ -1801,6 +1823,8 @@ def process_notification(notice: Mapping[str, Any]) -> None:
process_stream_creation_event(event, cast(list[int], users))
elif event["type"] == "stream" and event["op"] == "delete":
process_stream_deletion_event(event, cast(list[int], users))
+ elif event["type"] == "realm_emoji":
+ process_realm_emoji_event(event, cast(list[int], users))
elif event["type"] == "cleanup_queue":
# cleanup_event_queue may generate this event to forward cleanup
# requests to the right shard.
diff --git a/zerver/tornado/views.py b/zerver/tornado/views.py
index 78c040100c6..82a12e6d0c3 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,
+ individual_emoji_changes: Annotated[
+ Json[bool],
+ ApiParamConfig(documentation_status=DocumentationStatus.INTENTIONALLY_UNDOCUMENTED),
+ ] = False,
) -> HttpResponse:
if narrow is None:
narrow = []
@@ -258,6 +262,7 @@ def get_events_backend(
archived_channels=archived_channels,
empty_topic_name=empty_topic_name,
simplified_presence_events=simplified_presence_events,
+ individual_emoji_changes=individual_emoji_changes,
)
result = in_tornado_thread(fetch_events)(