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.

streams: Support per-stream default for push notifications.

Aadyot1eef8e878115b
diff --git a/api_docs/unmerged.d/ZF-a71492.md b/api_docs/unmerged.d/ZF-a71492.md
index 837a0c500d2..e9b776d10dc 100644
--- a/api_docs/unmerged.d/ZF-a71492.md
+++ b/api_docs/unmerged.d/ZF-a71492.md
@@ -1,3 +1,14 @@
+* [`POST /users/me/subscriptions`](/api/subscribe),
+ [`POST /channels/create`](/api/create-channel),
+ [`PATCH /streams/{stream_id}`](/api/update-stream): Added
+ `default_push_notifications` boolean parameter that controls whether
+ mobile push notifications are enabled by default when a user first
+ subscribes to the channel, potentially overriding the user's [default
+ mobile notification
+ setting](/help/channel-notifications#configure-default-notifications-for-all-channels)
+ for channel messages. Only organization administrators can set or
+ modify this parameter.
+
* [`POST /register`](/api/register-queue), [`GET /events`](/api/get-events),
[`GET /streams`](/api/get-streams),
[`GET /streams/{stream_id}`](/api/get-stream-by-id): Added
diff --git a/zerver/actions/streams.py b/zerver/actions/streams.py
index 9800dc4993c..8e37fbfcc7f 100644
--- a/zerver/actions/streams.py
+++ b/zerver/actions/streams.py
@@ -833,6 +833,12 @@ def bulk_add_subscriptions(
color=color,
recipient_id=recipient_id,
)
+ # The channel default only applies to brand-new subscriptions.
+ # Users who previously unsubscribed and are being resubscribed
+ # (subs_to_activate) keep the push notification preference stored
+ # on their existing subscription.
+ if stream.default_push_notifications:
+ sub.push_notifications = True
sub_info = SubInfo(user_profile, sub, stream)
subs_to_add.append(sub_info)
@@ -1751,6 +1757,9 @@ def do_set_stream_property(stream: Stream, name: str, value: Any, acting_user: U
send_event_on_commit(stream.realm, event, can_access_stream_metadata_user_ids(stream))
+ if name != "topics_policy":
+ return
+
sender = get_system_bot(settings.NOTIFICATION_BOT, stream.realm_id)
empty_topic_display_name = get_topic_display_name("", stream.realm.default_language)
diff --git a/zerver/lib/event_schema.py b/zerver/lib/event_schema.py
index 9bc441d9426..9619dc2789f 100644
--- a/zerver/lib/event_schema.py
+++ b/zerver/lib/event_schema.py
@@ -645,6 +645,9 @@ def check_stream_update(
elif prop == "folder_id":
assert extra_keys == set()
assert value is None or isinstance(value, int)
+ elif prop == "default_push_notifications":
+ assert extra_keys == set()
+ assert isinstance(value, bool)
else:
raise AssertionError(f"Unknown property: {prop}")
diff --git a/zerver/lib/event_types.py b/zerver/lib/event_types.py
index ebc2d5e32d7..8ab9b636bd4 100644
--- a/zerver/lib/event_types.py
+++ b/zerver/lib/event_types.py
@@ -971,6 +971,7 @@ class SingleSubscription(BaseModel):
can_send_message_group: int | UserGroupMembersDict
creator_id: int | None
date_created: int
+ default_push_notifications: bool
description: str
first_message_id: int | None
is_recently_active: bool
diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yaml
index f7455db38f7..a6be318e273 100644
--- a/zerver/openapi/zulip.yaml
+++ b/zerver/openapi/zulip.yaml
@@ -13197,6 +13197,8 @@ paths:
$ref: "#/components/schemas/HistoryPublicToSubscribers"
message_retention_days:
$ref: "#/components/schemas/MessageRetentionDays"
+ default_push_notifications:
+ $ref: "#/components/schemas/DefaultPushNotifications"
topics_policy:
$ref: "#/components/schemas/TopicsPolicy"
can_add_subscribers_group:
@@ -13250,6 +13252,8 @@ paths:
contentType: application/json
history_public_to_subscribers:
contentType: application/json
+ default_push_notifications:
+ contentType: application/json
topics_policy:
contentType: application/json
can_add_subscribers_group:
@@ -24562,6 +24566,8 @@ paths:
example: false
message_retention_days:
$ref: "#/components/schemas/MessageRetentionDays"
+ default_push_notifications:
+ $ref: "#/components/schemas/DefaultPushNotifications"
is_archived:
description: |
A boolean indicating whether the channel is
@@ -25488,12 +25494,16 @@ paths:
$ref: "#/components/schemas/CanSubscribeGroup"
can_resolve_topics_group:
$ref: "#/components/schemas/CanResolveTopicsGroup"
+ default_push_notifications:
+ $ref: "#/components/schemas/DefaultPushNotifications"
required:
- name
- subscribers
encoding:
announce:
contentType: application/json
+ default_push_notifications:
+ contentType: application/json
can_add_subscribers_group:
contentType: application/json
can_create_topic_group:
diff --git a/zerver/tests/test_channel_creation.py b/zerver/tests/test_channel_creation.py
index a9d79f9f4b4..8315ce67b28 100644
--- a/zerver/tests/test_channel_creation.py
+++ b/zerver/tests/test_channel_creation.py
@@ -1307,3 +1307,44 @@ class TestCreateStreams(ZulipTestCase):
self.assertNotEqual(
stream_1.can_add_subscribers_group_id, stream_2.can_add_subscribers_group_id
)
+
+ def test_create_stream_with_default_push_notifications(self) -> None:
+ """An admin can set default_push_notifications=True when creating a stream.
+ A non-admin cannot."""
+ admin = self.example_user("iago")
+ non_admin = self.example_user("hamlet")
+ realm = admin.realm
+
+ result = self.subscribe_via_post(
+ non_admin,
+ ["push_create_nonadmin"],
+ extra_post_data={"default_push_notifications": orjson.dumps(True).decode()},
+ allow_fail=True,
+ )
+ self.assert_json_error(result, "Insufficient permission")
+
+ # Same guard on /channels/create.
+ result = self.create_channel_via_post(
+ non_admin,
+ name="push_create_nonadmin_v2",
+ extra_post_data={"default_push_notifications": orjson.dumps(True).decode()},
+ )
+ self.assert_json_error(result, "Insufficient permission")
+
+ self.subscribe_via_post(
+ admin,
+ ["push_create_admin"],
+ extra_post_data={"default_push_notifications": orjson.dumps(True).decode()},
+ )
+ stream = get_stream("push_create_admin", realm)
+ self.assertTrue(stream.default_push_notifications)
+
+ # Verify the /channels/create endpoint also persists the field for admins.
+ result = self.create_channel_via_post(
+ admin,
+ name="push_create_via_channels_api",
+ extra_post_data={"default_push_notifications": orjson.dumps(True).decode()},
+ )
+ self.assert_json_success(result)
+ stream = get_stream("push_create_via_channels_api", realm)
+ self.assertTrue(stream.default_push_notifications)
diff --git a/zerver/tests/test_channel_permissions.py b/zerver/tests/test_channel_permissions.py
index d353d0f3943..3e0ad286d38 100644
--- a/zerver/tests/test_channel_permissions.py
+++ b/zerver/tests/test_channel_permissions.py
@@ -18,10 +18,19 @@ from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import get_subscription
from zerver.lib.types import UserGroupMembersData
from zerver.lib.user_groups import get_group_setting_value_for_api
-from zerver.models import NamedUserGroup, Recipient, Stream, Subscription, UserProfile
+from zerver.models import (
+ NamedUserGroup,
+ RealmAuditLog,
+ Recipient,
+ Stream,
+ Subscription,
+ UserProfile,
+)
from zerver.models.groups import SystemGroups
+from zerver.models.realm_audit_logs import AuditLogEventType
from zerver.models.realms import get_realm
from zerver.models.streams import StreamTopicsPolicyEnum, get_stream
+from zerver.models.users import active_non_guest_user_ids
class ChannelSubscriptionPermissionTest(ZulipTestCase):
@@ -1474,3 +1483,74 @@ class ChannelAdministerPermissionTest(ZulipTestCase):
},
)
self.assert_json_success(result)
+
+ def test_update_stream_default_push_notifications(self) -> None:
+ """Only admins can change default_push_notifications; the update
+ fires a stream event and persists the value."""
+ admin = self.example_user("iago")
+ non_admin = self.example_user("hamlet")
+ self.login_user(admin)
+ stream = self.subscribe(admin, "test_push_stream")
+ self.subscribe(non_admin, "test_push_stream")
+ realm = admin.realm
+
+ # Non-admin without channel-admin rights fails the channel-admin check first.
+ self.login_user(non_admin)
+ result = self.client_patch(
+ f"/json/streams/{stream.id}",
+ {"default_push_notifications": orjson.dumps(True).decode()},
+ )
+ self.assert_json_error(result, "You do not have permission to administer this channel.")
+
+ # Channel admin passes the channel-admin check but not the realm-admin check.
+ do_change_stream_group_based_setting(
+ stream,
+ "can_administer_channel_group",
+ UserGroupMembersData(direct_members=[non_admin.id], direct_subgroups=[]),
+ acting_user=admin,
+ )
+ self.login_user(non_admin)
+ result = self.client_patch(
+ f"/json/streams/{stream.id}",
+ {"default_push_notifications": orjson.dumps(True).decode()},
+ )
+ self.assert_json_error(result, "Insufficient permission")
+
+ self.login_user(admin)
+ with self.capture_send_event_calls(expected_num_events=1) as events:
+ result = self.client_patch(
+ f"/json/streams/{stream.id}",
+ {"default_push_notifications": orjson.dumps(True).decode()},
+ )
+ self.assert_json_success(result)
+ stream = get_stream("test_push_stream", realm)
+ self.assertTrue(stream.default_push_notifications)
+
+ event = events[0]["event"]
+ self.assertEqual(
+ event,
+ dict(
+ op="update",
+ type="stream",
+ property="default_push_notifications",
+ value=True,
+ stream_id=stream.id,
+ name="test_push_stream",
+ ),
+ )
+ notified_user_ids = set(events[0]["users"])
+ self.assertEqual(notified_user_ids, set(active_non_guest_user_ids(realm.id)))
+
+ audit_log = RealmAuditLog.objects.filter(
+ event_type=AuditLogEventType.CHANNEL_PROPERTY_CHANGED,
+ modified_stream=stream,
+ ).last()
+ assert audit_log is not None
+ self.assertEqual(
+ audit_log.extra_data,
+ {
+ RealmAuditLog.OLD_VALUE: False,
+ RealmAuditLog.NEW_VALUE: True,
+ "property": "default_push_notifications",
+ },
+ )
diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py
index 2ae5c3ceb1b..771afe36371 100644
--- a/zerver/tests/test_events.py
+++ b/zerver/tests/test_events.py
@@ -5358,6 +5358,15 @@ class SubscribeActionTest(BaseAction):
)
check_stream_update("events[0]", events[0])
+ with self.verify_action(include_subscribers=include_subscribers, num_events=1) as events:
+ do_set_stream_property(
+ stream,
+ "default_push_notifications",
+ True,
+ iago,
+ )
+ check_stream_update("events[0]", events[0])
+
for setting_name in Stream.stream_permission_group_settings:
self.do_test_subscribe_events_for_stream_permission_group_setting(
setting_name, stream, iago, include_subscribers
diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.py
index c938d339902..a9b532f3f3e 100644
--- a/zerver/tests/test_subs.py
+++ b/zerver/tests/test_subs.py
@@ -30,6 +30,7 @@ from zerver.actions.streams import (
deactivated_streams_by_old_name,
do_change_stream_group_based_setting,
do_change_stream_permission,
+ do_change_subscription_property,
do_deactivate_stream,
do_set_stream_property,
do_unarchive_stream,
@@ -2467,6 +2468,94 @@ class StreamAdminTest(ZulipTestCase):
)
self.assert_json_error(result, "Bad value for 'message_retention_days': 0")
+ def test_stream_default_push_notifications_default_value(self) -> None:
+ """New streams default to default_push_notifications=False."""
+ user_profile = self.example_user("iago")
+ self.login_user(user_profile)
+ stream = self.subscribe(user_profile, "test_push_default")
+ self.assertFalse(stream.default_push_notifications)
+
+ def test_new_subscription_gets_push_notifications_from_stream(self) -> None:
+ """When a stream has default_push_notifications=True, brand-new
+ subscriptions get push_notifications=True, overriding the user default."""
+ admin = self.example_user("iago")
+ hamlet = self.example_user("hamlet")
+ self.login_user(admin)
+
+ stream = self.subscribe(admin, "push_default_stream")
+ result = self.client_patch(
+ f"/json/streams/{stream.id}",
+ {"default_push_notifications": orjson.dumps(True).decode()},
+ )
+ self.assert_json_success(result)
+ stream.refresh_from_db()
+ self.assertTrue(stream.default_push_notifications)
+
+ # hamlet's account default is off, so push_notifications=True below
+ # must come from the stream override.
+ self.assertFalse(hamlet.enable_stream_push_notifications)
+
+ self.login_user(hamlet)
+ result = self.client_post(
+ "/json/users/me/subscriptions",
+ {"subscriptions": orjson.dumps([{"name": "push_default_stream"}]).decode()},
+ )
+ self.assert_json_success(result)
+ sub = Subscription.objects.get(
+ user_profile=hamlet,
+ recipient=stream.recipient,
+ )
+ self.assertTrue(sub.push_notifications)
+
+ def test_resubscription_preserves_push_notifications_preference(self) -> None:
+ """Re-subscribing a previously unsubscribed user does not overwrite
+ the stored push_notifications preference they had before."""
+ admin = self.example_user("iago")
+ hamlet = self.example_user("hamlet")
+ self.login_user(admin)
+
+ stream = self.subscribe(admin, "resubscribe_stream")
+ result = self.client_patch(
+ f"/json/streams/{stream.id}",
+ {"default_push_notifications": orjson.dumps(True).decode()},
+ )
+ self.assert_json_success(result)
+ stream.refresh_from_db()
+
+ self.login_user(hamlet)
+ result = self.client_post(
+ "/json/users/me/subscriptions",
+ {"subscriptions": orjson.dumps([{"name": "resubscribe_stream"}]).decode()},
+ )
+ self.assert_json_success(result)
+ sub = Subscription.objects.get(user_profile=hamlet, recipient=stream.recipient)
+ self.assertTrue(sub.push_notifications)
+
+ # Turn off push notifications for this subscription.
+ do_change_subscription_property(
+ hamlet, sub, stream, "push_notifications", False, acting_user=hamlet
+ )
+ sub.refresh_from_db()
+ self.assertFalse(sub.push_notifications)
+
+ # Unsubscribe and re-subscribe; stored preference must survive the round-trip.
+ self.client_delete(
+ "/json/users/me/subscriptions",
+ {"subscriptions": orjson.dumps(["resubscribe_stream"]).decode()},
+ )
+ sub.refresh_from_db()
+ self.assertFalse(sub.active)
+
+ result = self.client_post(
+ "/json/users/me/subscriptions",
+ {"subscriptions": orjson.dumps([{"name": "resubscribe_stream"}]).decode()},
+ )
+ self.assert_json_success(result)
+ sub.refresh_from_db()
+ self.assertTrue(sub.active)
+ # push_notifications should remain False, not be reset to True.
+ self.assertFalse(sub.push_notifications)
+
def do_test_change_stream_permission_setting(self, setting_name: str) -> None:
user_profile = self.example_user("iago")
realm = user_profile.realm
diff --git a/zerver/views/streams.py b/zerver/views/streams.py
index 51b42541fc5..a9e521e4694 100644
--- a/zerver/views/streams.py
+++ b/zerver/views/streams.py
@@ -302,6 +302,7 @@ def update_stream_backend(
can_resolve_topics_group: Json[GroupSettingChangeRequest] | None = None,
can_send_message_group: Json[GroupSettingChangeRequest] | None = None,
can_subscribe_group: Json[GroupSettingChangeRequest] | None = None,
+ default_push_notifications: Json[bool] | None = None,
description: ChannelDescription = None,
folder_id: Json[int | None] | MissingType = Missing,
history_public_to_subscribers: Json[bool] | None = None,
@@ -440,6 +441,13 @@ def update_stream_backend(
stream, user_profile, new_message_retention_days_value
)
+ if default_push_notifications is not None:
+ if not user_profile.is_realm_admin:
+ raise JsonableError(_("Insufficient permission"))
+ do_set_stream_property(
+ stream, "default_push_notifications", default_push_notifications, user_profile
+ )
+
if is_archived is not None and not is_archived:
do_unarchive_stream(stream, stream.name, acting_user=user_profile)
@@ -691,6 +699,7 @@ def create_channel(
can_resolve_topics_group: Json[int | UserGroupMembersData] | None = None,
can_send_message_group: Json[int | UserGroupMembersData] | None = None,
can_subscribe_group: Json[int | UserGroupMembersData] | None = None,
+ default_push_notifications: Json[bool] = False,
description: ChannelDescription = None,
folder_id: Json[int] | None = None,
history_public_to_subscribers: Json[bool] | None = None,
@@ -744,6 +753,9 @@ def create_channel(
)
)
+ if default_push_notifications and not user_profile.is_realm_admin:
+ raise JsonableError(_("Insufficient permission"))
+
group_settings_map = stream_group_settings_map[name]
new_channel, created = create_stream_if_needed(
realm,
@@ -753,6 +765,7 @@ def create_channel(
history_public_to_subscribers=history_public_to_subscribers,
is_web_public=is_web_public,
message_retention_days=parsed_message_retention_days,
+ default_push_notifications=default_push_notifications,
anonymous_group_membership=anonymous_group_membership,
acting_user=user_profile,
can_add_subscribers_group=group_settings_map["can_add_subscribers_group"],
@@ -824,6 +837,7 @@ def add_subscriptions_backend(
can_resolve_topics_group: Json[int | UserGroupMembersData] | None = None,
can_send_message_group: Json[int | UserGroupMembersData] | None = None,
can_subscribe_group: Json[int | UserGroupMembersData] | None = None,
+ default_push_notifications: Json[bool] = False,
folder_id: Json[int] | None = None,
history_public_to_subscribers: Json[bool] | None = None,
invite_only: Json[bool] = False,
@@ -848,6 +862,9 @@ def add_subscriptions_backend(
if folder_id is not None:
folder = get_channel_folder_by_id(folder_id, realm)
+ if default_push_notifications and not user_profile.is_realm_admin:
+ raise JsonableError(_("Insufficient permission"))
+
for stream_obj in streams_raw:
# 'color' field is optional
# check for its presence in the streams_raw first
@@ -870,6 +887,7 @@ def add_subscriptions_backend(
if validated_topics_policy is not None:
stream_dict_copy["topics_policy"] = validated_topics_policy.value
stream_dict_copy["folder"] = folder
+ stream_dict_copy["default_push_notifications"] = default_push_notifications
stream_dicts.append(stream_dict_copy)