Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
subscription_info: Add option to get partial subscribers.
Evy Kassirer1405dd630fb0
diff --git a/zerver/lib/events.py b/zerver/lib/events.pyindex 024192c0a71..aa8c35edf37 100644--- a/zerver/lib/events.py+++ b/zerver/lib/events.py@@ -4,7 +4,7 @@ import copyimport loggingimport timefrom collections.abc import Callable, Collection, Iterable, Sequence-from typing import Any+from typing import Any, Literalfrom django.conf import settingsfrom django.utils.translation import gettext as _@@ -157,7 +157,7 @@ def fetch_initial_state_data(slim_presence: bool = False,presence_last_update_id_fetched_by_client: int | None = None,presence_history_limit_days: int | None = None,- include_subscribers: bool = True,+ include_subscribers: bool | Literal["partial"] = True,include_streams: bool = True,spectator_requested_language: str | None = None,pronouns_field_type_supported: bool = True,@@ -1894,7 +1894,7 @@ def do_events_register(event_types: Sequence[str] | None = None,queue_lifespan_secs: int = 0,all_public_streams: bool = False,- include_subscribers: bool = True,+ include_subscribers: bool | Literal["partial"] = True,include_streams: bool = True,client_capabilities: ClientCapabilities = DEFAULT_CLIENT_CAPABILITIES,narrow: Collection[NeverNegatedNarrowTerm] = [],@@ -2024,7 +2024,7 @@ def do_events_register(fetch_event_types=fetch_event_types,client_gravatar=client_gravatar,slim_presence=slim_presence,- include_subscribers=include_subscribers,+ include_subscribers=True if include_subscribers == "partial" else include_subscribers,linkifier_url_template=linkifier_url_template,user_list_incomplete=user_list_incomplete,include_deactivated_groups=include_deactivated_groups,diff --git a/zerver/lib/home.py b/zerver/lib/home.pyindex 346a5b1a44f..a20a65953c7 100644--- a/zerver/lib/home.py+++ b/zerver/lib/home.py@@ -1,4 +1,5 @@import calendar+import osimport timefrom dataclasses import dataclass@@ -108,6 +109,7 @@ def build_page_params_for_home_page_load(if user_profile is not None:client = RequestNotes.get_notes(request).clientassert client is not None+ partial_subscribers = os.environ.get("PARTIAL_SUBSCRIBERS") is not Nonestate_data = do_events_register(user_profile,realm,@@ -120,6 +122,7 @@ def build_page_params_for_home_page_load(client_capabilities=client_capabilities,narrow=narrow,include_streams=False,+ include_subscribers="partial" if partial_subscribers else True,)queue_id = state_data["queue_id"]default_language = state_data["user_settings"]["default_language"]diff --git a/zerver/lib/subscription_info.py b/zerver/lib/subscription_info.pyindex cf4941659e6..a62371b9e7a 100644--- a/zerver/lib/subscription_info.py+++ b/zerver/lib/subscription_info.py@@ -1,7 +1,7 @@import itertoolsfrom collections.abc import Callable, Collection, Iterable, Mappingfrom operator import itemgetter-from typing import Any+from typing import Any, Literalfrom django.core.exceptions import ValidationErrorfrom django.db import connection@@ -466,6 +466,7 @@ def bulk_get_subscriber_user_ids(stream_dicts: Collection[Mapping[str, Any]],user_profile: UserProfile,subscribed_stream_ids: set[int],+ partial_subscribers: bool = False,) -> dict[int, list[int]]:"""sub_dict maps stream_id => whether the user is subscribed to that stream."""target_stream_dicts = []@@ -533,6 +534,20 @@ def bulk_get_subscriber_user_ids(stream_id = recip_to_stream_id[recip_id]result[stream_id] = list(user_profile_ids)+ # Eventually this will return (at minimum):+ # (1) if we’re in a channel view, which users are subscribed to the+ # current channel+ # (2) subscriptions for all bots+ #+ # For now, we're only doing (2).+ if partial_subscribers:+ bot_users = set(+ UserProfile.objects.filter(+ is_bot=True, realm=user_profile.realm, is_active=True+ ).values_list("id", flat=True)+ )+ for stream_id, users in result.items():+ result[stream_id] = [user_id for user_id in users if user_id in bot_users]return result@@ -647,7 +662,7 @@ def has_metadata_access_to_previously_subscribed_stream(# subscriptions, so it's worth optimizing.def gather_subscriptions_helper(user_profile: UserProfile,- include_subscribers: bool = True,+ include_subscribers: bool | Literal["partial"] = True,include_archived_channels: bool = False,anonymous_group_membership: dict[int, UserGroupMembersData] | None = None,) -> SubscriptionInfo:@@ -809,6 +824,7 @@ def gather_subscriptions_helper(all_stream_dicts,user_profile,subscribed_stream_ids,+ include_subscribers == "partial",)for lst in [subscribed, unsubscribed]:diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.pyindex 30fa082008b..16612d1d061 100644--- a/zerver/tests/test_subs.py+++ b/zerver/tests/test_subs.py@@ -7678,6 +7678,7 @@ class GetSubscribersTest(ZulipTestCase):cordelia = self.example_user("cordelia")othello = self.example_user("othello")polonius = self.example_user("polonius")+ bot = self.create_test_bot("bot", cordelia, "Foo Bot")realm = hamlet.realmstream_names = [f"stream_{i}" for i in range(10)]@@ -7688,6 +7689,7 @@ class GetSubscribersTest(ZulipTestCase):othello.id,cordelia.id,polonius.id,+ bot.id,]with self.assert_database_query_count(50):@@ -7772,6 +7774,17 @@ class GetSubscribersTest(ZulipTestCase):acting_user=hamlet,)+ # Test partial subscribers+ with self.assert_database_query_count(10):+ sub_data = gather_subscriptions_helper(self.user_profile, include_subscribers="partial")+ subscribed_streams = sub_data.subscriptions+ self.assertGreaterEqual(len(subscribed_streams), 11)+ for sub in subscribed_streams:+ if not sub["name"].startswith("stream_"):+ continue+ # Just the bot+ self.assert_length(sub["subscribers"], 1)+with self.assert_database_query_count(9):subscribed_streams, _ = gather_subscriptions(self.user_profile, include_subscribers=True