Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
streams events: Use pydantic types for untransformed events.
Evy Kassirerb0d3ae78eddd
diff --git a/zerver/actions/streams.py b/zerver/actions/streams.pyindex 292b2546a99..72087526539 100644--- a/zerver/actions/streams.py+++ b/zerver/actions/streams.py@@ -1,6 +1,6 @@from collections import defaultdictfrom collections.abc import Collection, Iterable, Mapping-from typing import Any, TypeAlias+from typing import Any, Literal, TypeAliasfrom django.conf import settingsfrom django.db import transaction@@ -21,6 +21,18 @@ from zerver.lib.cache import (display_recipient_cache_key,to_dict_cache_key_id,)+from zerver.lib.event_types import (+ RealmUserRemoveEvent,+ RemovedUser,+ RemoveSub,+ SingleSubscription,+ StreamUpdateEvent,+ SubscriptionAddEvent,+ SubscriptionPeerAddEvent,+ SubscriptionPeerRemoveEvent,+ SubscriptionRemoveEvent,+ SubscriptionUpdateEvent,+)from zerver.lib.exceptions import JsonableErrorfrom zerver.lib.mention import silent_mention_syntax_for_user, silent_mention_syntax_for_user_groupfrom zerver.lib.message import get_last_message_id@@ -51,7 +63,7 @@ from zerver.lib.streams import ()from zerver.lib.subscription_info import bulk_get_subscriber_peer_info, get_subscribers_queryfrom zerver.lib.topic import get_topic_display_name, messages_for_topic-from zerver.lib.types import APISubscriptionDict, UserGroupMembersData+from zerver.lib.types import UserGroupMembersDatafrom zerver.lib.user_groups import (convert_to_user_group_members_dict,get_group_setting_value_for_api,@@ -165,9 +177,7 @@ def do_deactivate_stream(stream: Stream, *, acting_user: UserProfile | None) ->for group in default_stream_groups_for_stream:do_remove_streams_from_default_stream_group(stream.realm, group, [stream])- event = dict(- type="stream",- op="update",+ event = StreamUpdateEvent(stream_id=stream.id,name=stream.name,property="is_archived",@@ -294,9 +304,7 @@ def do_unarchive_stream(stream: Stream, new_name: str, *, acting_user: UserProfinotify_user_ids = list(can_access_stream_metadata_user_ids(stream))- event = dict(- type="stream",- op="update",+ event = StreamUpdateEvent(stream_id=stream.id,name=stream.name,property="is_archived",@@ -454,16 +462,15 @@ def send_subscription_add_events(anonymous_group_membership = get_anonymous_group_membership_dict_for_streams(streams)for user_id, sub_infos in info_by_user.items():- sub_dicts: list[APISubscriptionDict] = []+ sub_dicts: list[SingleSubscription] = []for sub_info in sub_infos:stream = sub_info.streamstream_subscribers = stream_subscribers_dict[stream.id]subscription = sub_info.substream_dict = stream_to_dict(stream, recent_traffic, anonymous_group_membership)- # This is verbose as we cannot unpack existing TypedDict- # to initialize another TypedDict while making mypy happy.- # https://github.com/python/mypy/issues/5382- sub_dict = APISubscriptionDict(+ # mypy rejects unpacking stream_dict here: its is_default+ # key is not a model field.+ sub_dict = SingleSubscription(# Fields from Subscription.API_FIELDSaudible_notifications=subscription.audible_notifications,color=subscription.color,@@ -518,7 +525,7 @@ def send_subscription_add_events(sub_dicts.append(sub_dict)# Send a notification to the user who subscribed.- event = dict(type="subscription", op="add", subscriptions=sub_dicts)+ event = SubscriptionAddEvent(subscriptions=sub_dicts)send_event_on_commit(realm, event, [user_id])@@ -609,8 +616,16 @@ def send_stream_creation_events_for_previously_inaccessible_streams()+def peer_subscriber_event(+ op: Literal["peer_add", "peer_remove"], stream_ids: list[int], user_ids: list[int]+) -> SubscriptionPeerAddEvent | SubscriptionPeerRemoveEvent:+ if op == "peer_add":+ return SubscriptionPeerAddEvent(stream_ids=stream_ids, user_ids=user_ids)+ return SubscriptionPeerRemoveEvent(stream_ids=stream_ids, user_ids=user_ids)++def send_peer_subscriber_events(- op: str,+ op: Literal["peer_add", "peer_remove"],realm: Realm,stream_dict: dict[int, Stream],altered_user_dict: dict[int, set[int]],@@ -638,12 +653,7 @@ def send_peer_subscriber_events(peer_user_ids = private_peer_dict[stream_id] - altered_user_idsif peer_user_ids and altered_user_ids:- event = dict(- type="subscription",- op=op,- stream_ids=[stream_id],- user_ids=sorted(altered_user_ids),- )+ event = peer_subscriber_event(op, [stream_id], sorted(altered_user_ids))send_event_on_commit(realm, event, peer_user_ids)if public_stream_ids:@@ -684,31 +694,20 @@ def send_peer_subscriber_events(peer_user_ids = (non_guest_user_ids | subscriber_dict[stream_id]) - altered_user_ids- event = dict(- type="subscription",- op=op,- stream_ids=[stream_id],- user_ids=list(altered_user_ids),- )+ event = peer_subscriber_event(op, [stream_id], list(altered_user_ids))send_event_on_commit(realm, event, peer_user_ids)if len(web_public_user_stream_ids) > 0:web_public_peer_ids = set(active_user_ids(realm.id))- web_public_streams_event = dict(- type="subscription",- op=op,- stream_ids=sorted(web_public_user_stream_ids),- user_ids=list(altered_user_ids),+ web_public_streams_event = peer_subscriber_event(+ op, sorted(web_public_user_stream_ids), list(altered_user_ids))send_event_on_commit(realm, web_public_streams_event, web_public_peer_ids - altered_user_ids)if len(public_user_stream_ids_without_guest_users) > 0:- public_streams_event = dict(- type="subscription",- op=op,- stream_ids=sorted(public_user_stream_ids_without_guest_users),- user_ids=list(altered_user_ids),+ public_streams_event = peer_subscriber_event(+ op, sorted(public_user_stream_ids_without_guest_users), list(altered_user_ids))send_event_on_commit(realm, public_streams_event, non_guest_user_ids - altered_user_ids@@ -971,8 +970,8 @@ def send_peer_remove_events(def notify_subscriptions_removed(realm: Realm, user_profile: UserProfile, streams: Iterable[Stream]) -> None:- payload = [dict(name=stream.name, stream_id=stream.id) for stream in streams]- event = dict(type="subscription", op="remove", subscriptions=payload)+ payload = [RemoveSub(name=stream.name, stream_id=stream.id) for stream in streams]+ event = SubscriptionRemoveEvent(subscriptions=payload)send_event_on_commit(realm, event, [user_profile.id])@@ -1065,10 +1064,10 @@ def send_user_remove_events_on_removing_subscriptions()if subscribers_without_access_to_altered_user:- event_remove_user = dict(- type="realm_user",- op="remove",- person=dict(user_id=user.id, full_name=str(UserProfile.INACCESSIBLE_USER_NAME)),+ event_remove_user = RealmUserRemoveEvent(+ person=RemovedUser(+ user_id=user.id, full_name=str(UserProfile.INACCESSIBLE_USER_NAME)+ ),)send_event_on_commit(realm, event_remove_user, list(subscribers_without_access_to_altered_user)@@ -1080,10 +1079,10 @@ def send_user_remove_events_on_removing_subscriptions()for user_id in users_inaccessible_to_altered_user:- event_remove_user = dict(- type="realm_user",- op="remove",- person=dict(user_id=user_id, full_name=str(UserProfile.INACCESSIBLE_USER_NAME)),+ event_remove_user = RealmUserRemoveEvent(+ person=RemovedUser(+ user_id=user_id, full_name=str(UserProfile.INACCESSIBLE_USER_NAME)+ ),)send_event_on_commit(realm, event_remove_user, [user.id])@@ -1237,9 +1236,7 @@ def do_change_subscription_property(# with is_muted as the property name.if database_property_name == "is_muted":event_value = not database_value- in_home_view_event = dict(- type="subscription",- op="update",+ in_home_view_event = SubscriptionUpdateEvent(property="in_home_view",value=event_value,stream_id=stream.id,@@ -1247,9 +1244,7 @@ def do_change_subscription_property(send_event_on_commit(user_profile.realm, in_home_view_event, [user_profile.id])- event = dict(- type="subscription",- op="update",+ event = SubscriptionUpdateEvent(property=database_property_name,value=database_value,stream_id=stream.id,@@ -1402,9 +1397,7 @@ def do_change_stream_permission(stream_subscriber_user_ids = get_active_subscriptions_for_stream_id(stream.id, include_deactivated_users=False).values_list("user_profile_id", flat=True)- peer_add_event = dict(- type="subscription",- op="peer_add",+ peer_add_event = SubscriptionPeerAddEvent(stream_ids=[stream.id],user_ids=sorted(stream_subscriber_user_ids),)@@ -1416,9 +1409,7 @@ def do_change_stream_permission(if user_ids_losing_metadata_access:send_stream_deletion_event(stream.realm, user_ids_losing_metadata_access, [stream])- event = dict(- op="update",- type="stream",+ event = StreamUpdateEvent(property="invite_only",value=stream.invite_only,history_public_to_subscribers=stream.history_public_to_subscribers,@@ -1548,9 +1539,7 @@ def do_rename_stream(stream: Stream, new_name: str, user_profile: UserProfile) -# We want to key these updates by id, not name, since id is# the immutable primary key, and obviously name is not.- event = dict(- op="update",- type="stream",+ event = StreamUpdateEvent(property="name",value=new_name,stream_id=stream.id,@@ -1626,9 +1615,7 @@ def do_change_stream_description(},)- event = dict(- type="stream",- op="update",+ event = StreamUpdateEvent(property="description",name=stream.name,stream_id=stream.id,@@ -1715,9 +1702,7 @@ def do_change_stream_message_retention_days(},)- event = dict(- op="update",- type="stream",+ event = StreamUpdateEvent(property="message_retention_days",value=message_retention_days,stream_id=stream.id,@@ -1753,18 +1738,16 @@ def do_set_stream_property(stream: Stream, name: str, value: Any, acting_user: U},)- event = dict(- op="update",- type="stream",+ event_value = value+ if name == "topics_policy":+ event_value = StreamTopicsPolicyEnum(value).name++ event = StreamUpdateEvent(property=name,- value=value,+ value=event_value,stream_id=stream.id,name=stream.name,)-- if name == "topics_policy":- event["value"] = StreamTopicsPolicyEnum(value).name-send_event_on_commit(stream.realm, event, can_access_stream_metadata_user_ids(stream))if name != "topics_policy":@@ -1857,9 +1840,7 @@ def do_change_stream_group_based_setting("property": setting_name,},)- update_event = dict(- op="update",- type="stream",+ update_event = StreamUpdateEvent(property=setting_name,value=convert_to_user_group_members_dict(new_setting_api_value),stream_id=stream.id,@@ -1893,9 +1874,7 @@ def do_change_stream_group_based_setting(subscriber_ids = get_active_subscriptions_for_stream_id(stream.id, include_deactivated_users=False).values_list("user_profile_id", flat=True)- peer_add_event = dict(- type="subscription",- op="peer_add",+ peer_add_event = SubscriptionPeerAddEvent(stream_ids=[stream.id],user_ids=sorted(subscriber_ids),)@@ -1914,9 +1893,7 @@ def do_change_stream_group_based_setting(stream_post_policy = get_stream_post_policy_value_based_on_group_setting(user_group)if old_stream_post_policy != stream_post_policy:- event = dict(- op="update",- type="stream",+ event = StreamUpdateEvent(property="stream_post_policy",value=stream_post_policy,stream_id=stream.id,@@ -1928,9 +1905,7 @@ def do_change_stream_group_based_setting(# is_announcement_only property in early 2020, but we send a# duplicate event for legacy mobile clients that might want the# data.- event = dict(- op="update",- type="stream",+ event = StreamUpdateEvent(property="is_announcement_only",value=stream_post_policy == Stream.STREAM_POST_POLICY_ADMINS,stream_id=stream.id,@@ -1973,9 +1948,7 @@ def do_change_stream_folder(},)- event = dict(- op="update",- type="stream",+ event = StreamUpdateEvent(property="folder_id",value=stream.folder_id,stream_id=stream.id,diff --git a/zerver/lib/event_types.py b/zerver/lib/event_types.pyindex bab5151c022..541074070d5 100644--- a/zerver/lib/event_types.py+++ b/zerver/lib/event_types.py@@ -723,8 +723,8 @@ class RemovedUser(BaseEventModel):class RealmUserRemoveEvent(BaseEvent):- type: Literal["realm_user"]- op: Literal["remove"]+ type: Literal["realm_user"] = "realm_user"+ op: Literal["remove"] = "remove"person: RemovedUser@@ -961,8 +961,8 @@ class StreamDeleteEvent(BaseEvent):class StreamUpdateCoreEvent(BaseEvent):- type: Literal["stream"]- op: Literal["update"]+ type: Literal["stream"] = "stream"+ op: Literal["update"] = "update"property: strvalue: bool | int | str | UserGroupMembersDict | Nonename: str@@ -1030,8 +1030,8 @@ class SingleSubscription(BaseEventModel):class SubscriptionAddEvent(BaseEvent):- type: Literal["subscription"]- op: Literal["add"]+ type: Literal["subscription"] = "subscription"+ op: Literal["add"] = "add"subscriptions: list[SingleSubscription]@@ -1043,8 +1043,8 @@ class SubscriptionPeerAddEvent(BaseEvent):class SubscriptionPeerRemoveEvent(BaseEvent):- type: Literal["subscription"]- op: Literal["peer_remove"]+ type: Literal["subscription"] = "subscription"+ op: Literal["peer_remove"] = "peer_remove"user_ids: list[int]stream_ids: list[int]@@ -1055,14 +1055,14 @@ class RemoveSub(BaseEventModel):class SubscriptionRemoveEvent(BaseEvent):- type: Literal["subscription"]- op: Literal["remove"]+ type: Literal["subscription"] = "subscription"+ op: Literal["remove"] = "remove"subscriptions: list[RemoveSub]class SubscriptionUpdateEvent(BaseEvent):- type: Literal["subscription"]- op: Literal["update"]+ type: Literal["subscription"] = "subscription"+ op: Literal["update"] = "update"property: strstream_id: intvalue: bool | int | strdiff --git a/zerver/lib/streams.py b/zerver/lib/streams.pyindex 7376065aa92..b38bc7d28f0 100644--- a/zerver/lib/streams.py+++ b/zerver/lib/streams.py@@ -10,6 +10,7 @@ from django.utils.timezone import now as timezone_nowfrom django.utils.translation import gettext as _from zerver.lib.default_streams import get_default_stream_ids_for_realm+from zerver.lib.event_types import StreamUpdateEventfrom zerver.lib.exceptions import (CannotAdministerChannelError,CannotSetTopicsPolicyError,@@ -2113,9 +2114,7 @@ def do_get_streams(def notify_stream_is_recently_active_update(stream: Stream, value: bool) -> None:- event = dict(- type="stream",- op="update",+ event = StreamUpdateEvent(property="is_recently_active",value=value,stream_id=stream.id,diff --git a/zerver/lib/types.py b/zerver/lib/types.pyindex ca1d966ca7f..605e3ce1c62 100644--- a/zerver/lib/types.py+++ b/zerver/lib/types.py@@ -347,24 +347,6 @@ class APIStreamDict(DefaultStreamDict):stream_weekly_traffic: int | None-class APISubscriptionDict(APIStreamDict):- """Similar to StreamClientDict, it should contain all the fields specified in- `zerver.models.Subscription.API_FIELDS` and several additional fields.- """-- audible_notifications: bool | None- color: str- desktop_notifications: bool | None- email_notifications: bool | None- is_muted: bool- pin_to_top: bool- push_notifications: bool | None- wildcard_mentions_notify: bool | None- # Computed fields not specified in `Subscription.API_FIELDS`- in_home_view: bool- subscribers: list[int]--@dataclassclass SubscriptionInfo:subscriptions: list[SubscriptionStreamDict]diff --git a/zerver/tests/test_channel_fetch.py b/zerver/tests/test_channel_fetch.pyindex e463f473245..ae76e6a9f10 100644--- a/zerver/tests/test_channel_fetch.py+++ b/zerver/tests/test_channel_fetch.py@@ -14,12 +14,12 @@ from zerver.actions.streams import (do_deactivate_stream,)from zerver.lib.email_mirror_helpers import encode_email_address, get_channel_email_token+from zerver.lib.event_types import SingleSubscriptionfrom zerver.lib.subscription_info import gather_subscriptions, gather_subscriptions_helperfrom zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.test_helpers import most_recent_messagefrom zerver.lib.types import (APIStreamDict,- APISubscriptionDict,NeverSubscribedStreamDict,SubscriptionInfo,UserGroupMembersData,@@ -576,7 +576,7 @@ class GetSubscribersTest(ZulipTestCase):def test_api_fields(self) -> None:"""Verify that all the fields from `Stream.API_FIELDS` and `Subscription.API_FIELDS` present- in `APIStreamDict` and `APISubscriptionDict`, respectively.+ in `APIStreamDict` and `SingleSubscription`, respectively."""expected_fields = set(Stream.API_FIELDS) | {"stream_id", "is_archived"}expected_fields -= {"id", "deactivated"}@@ -594,11 +594,11 @@ class GetSubscribersTest(ZulipTestCase):expected_fields = set(Subscription.API_FIELDS)- subscription_dict_fields = set(APISubscriptionDict.__annotations__.keys())+ subscription_dict_fields = set(SingleSubscription.model_fields)computed_fields = {"in_home_view", "email_address", "stream_weekly_traffic", "subscribers"}- # `APISubscriptionDict` is a subclass of `APIStreamDict`, therefore having all the- # fields in addition to the computed fields and `Subscription.API_FIELDS` that- # need to be excluded here.+ # `SingleSubscription` has all the fields of `APIStreamDict`, which+ # need to be excluded here in addition to the computed fields and+ # `Subscription.API_FIELDS`.self.assertEqual(subscription_dict_fields - computed_fields - stream_dict_fields,expected_fields,diff --git a/zerver/tests/test_message_move_stream.py b/zerver/tests/test_message_move_stream.pyindex 12ef989bda1..8ce3991bc1d 100644--- a/zerver/tests/test_message_move_stream.py+++ b/zerver/tests/test_message_move_stream.py@@ -15,6 +15,7 @@ from zerver.actions.streams import (do_set_stream_property,)from zerver.actions.user_groups import check_add_user_group+from zerver.lib.event_types import StreamUpdateEventfrom zerver.lib.message import has_message_accessfrom zerver.lib.streams import (can_access_stream_metadata_user_ids,@@ -2435,9 +2436,7 @@ class MessageMoveStreamTest(ZulipTestCase):m.call_args.args,(new_stream.realm,- dict(- type="stream",- op="update",+ StreamUpdateEvent(property="is_recently_active",value=False,stream_id=new_stream.id,@@ -2489,9 +2488,7 @@ class MessageMoveStreamTest(ZulipTestCase):m.call_args.args,(new_stream.realm,- dict(- type="stream",- op="update",+ StreamUpdateEvent(property="is_recently_active",value=False,stream_id=new_stream.id,