Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
subs: Send notification when users are unsubscribed from channels.
Aadyot19bc601078a69
diff --git a/api_docs/changelog.md b/api_docs/changelog.mdindex aa38a9e72c2..345f8c9da65 100644--- a/api_docs/changelog.md+++ b/api_docs/changelog.md@@ -20,6 +20,27 @@ format used by the Zulip server that they are interacting with.## Changes in Zulip 13.0+**Feature level 515**++* [`DELETE /users/me/subscriptions`](/api/unsubscribe): Added+ `send_messages_to_removed_subscribers` boolean parameter, which+ determines whether the server should attempt to send a direct+ message, from Notification Bot, to other users who were+ unsubscribed from one or more channels by the current user.+ Previously, no notification messages were sent when a user was+ unsubscribed from a channel by another user.++* [`DELETE /users/me/subscriptions`](/api/unsubscribe): Added+ `messages_sent_to_removed_subscribers` boolean field to the response,+ which is only present if the new `send_messages_to_removed_subscribers`+ parameter was `true` in the request.++* [`POST /register`](/api/register-queue): Renamed the+ `max_bulk_new_subscription_messages` field in the response to+ `max_bulk_subscription_messages` as this limit now applies to+ notification messages sent when another user is subscribed or+ unsubscribed to one or more channels by the current user.+**Feature level 514*** [`POST /register`](/api/register-queue), [`GET /events`](/api/get-events),diff --git a/starlight_help/src/content/docs/configure-automated-notices.mdx b/starlight_help/src/content/docs/configure-automated-notices.mdxindex 474284243c8..67e1ce36f2f 100644--- a/starlight_help/src/content/docs/configure-automated-notices.mdx+++ b/starlight_help/src/content/docs/configure-automated-notices.mdx@@ -75,7 +75,8 @@ automated notices to help others understand how content was moved.## Notices about usersYou will be notified if someone [subscribes you to a-channel](/help/subscribe-users-to-a-channel), or changes your+channel](/help/subscribe-users-to-a-channel), [unsubscribes you from a+channel](/help/unsubscribe-users-from-a-channel), or changes your[group](/help/user-groups) membership.### New user announcementsdiff --git a/starlight_help/src/content/include/_UnsubscribeUserFromChannel.mdx b/starlight_help/src/content/include/_UnsubscribeUserFromChannel.mdxindex 363fc34c17a..ccb178562e2 100644--- a/starlight_help/src/content/include/_UnsubscribeUserFromChannel.mdx+++ b/starlight_help/src/content/include/_UnsubscribeUserFromChannel.mdx@@ -2,6 +2,7 @@ import {TabItem, Tabs} from "@astrojs/starlight/components";import FlattenedSteps from "../../components/FlattenedSteps.astro";import NavigationSteps from "../../components/NavigationSteps.astro";+import ZulipNote from "../../components/ZulipNote.astro";import ChannelSettingsNavbarTip from "../include/_ChannelSettingsNavbarTip.mdx";import DependsOnPermissions from "../include/_DependsOnPermissions.mdx";import RightSidebarViewProfile from "../include/_RightSidebarViewProfile.mdx";@@ -39,3 +40,8 @@ import CloseIcon from "~icons/zulip-icon/close";</FlattenedSteps></TabItem></Tabs>++<ZulipNote>+ **Note**: Unsubscribing someone else from a channel sends them an+ automated direct message from Notification Bot.+</ZulipNote>diff --git a/version.py b/version.pyindex 6eba1b6070e..d99d19da036 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 = 514+API_FEATURE_LEVEL = 515# 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. Bumpdiff --git a/web/src/state_data.ts b/web/src/state_data.tsindex f40508ea7a1..c4106199fca 100644--- a/web/src/state_data.ts+++ b/web/src/state_data.ts@@ -461,7 +461,7 @@ export const realm_schema = z.object({max_stream_description_length: z.number(),max_stream_name_length: z.number(),max_topic_length: z.number(),- max_bulk_new_subscription_messages: z.number(),+ max_bulk_subscription_messages: z.number(),password_min_guesses: z.number(),password_min_length: z.number(),password_max_length: z.number(),diff --git a/web/src/stream_edit_subscribers.ts b/web/src/stream_edit_subscribers.tsindex 20b47a40947..71e63ef68e2 100644--- a/web/src/stream_edit_subscribers.ts+++ b/web/src/stream_edit_subscribers.ts@@ -119,7 +119,7 @@ function show_stream_subscription_request_success_result({function update_notification_choice_checkbox(added_user_count: number): void {const $send_notification_checkbox = $(".send_notification_to_new_subscribers");const $send_notification_container = $(".send_notification_to_new_subscribers_container");- if (added_user_count > realm.max_bulk_new_subscription_messages) {+ if (added_user_count > realm.max_bulk_subscription_messages) {$send_notification_checkbox.prop("checked", false);$send_notification_checkbox.prop("disabled", true);$send_notification_container.addClass("control-label-disabled");diff --git a/web/src/tippyjs.ts b/web/src/tippyjs.tsindex f3f90bafb60..aaf9e0bf059 100644--- a/web/src/tippyjs.ts+++ b/web/src/tippyjs.ts@@ -1056,7 +1056,7 @@ export function initialize(): void {"Notification message cannot be sent when subscribing more than {max_users} users.",},{- max_users: realm.max_bulk_new_subscription_messages,+ max_users: realm.max_bulk_subscription_messages,},);instance.setContent(content);diff --git a/web/tests/lib/example_realm.cjs b/web/tests/lib/example_realm.cjsindex cb2e0696d28..14cf11f9efb 100644--- a/web/tests/lib/example_realm.cjs+++ b/web/tests/lib/example_realm.cjs@@ -19,7 +19,7 @@ exports.make_realm = (opts = {}) => {max_stream_description_length: 0,max_stream_name_length: 0,max_topic_length: 0,- max_bulk_new_subscription_messages: 0,+ max_bulk_subscription_messages: 0,password_min_guesses: 0,password_min_length: 0,password_max_length: 0,diff --git a/zerver/lib/events.py b/zerver/lib/events.pyindex f3869d2025c..8381ece336b 100644--- a/zerver/lib/events.py+++ b/zerver/lib/events.py@@ -596,7 +596,7 @@ def fetch_initial_state_data(state["max_stream_name_length"] = Stream.MAX_NAME_LENGTHstate["max_stream_description_length"] = Stream.MAX_DESCRIPTION_LENGTH- state["max_bulk_new_subscription_messages"] = settings.MAX_BULK_NEW_SUBSCRIPTION_MESSAGES+ state["max_bulk_subscription_messages"] = settings.MAX_BULK_SUBSCRIPTION_MESSAGESstate["max_topic_length"] = MAX_TOPIC_NAME_LENGTHstate["max_message_length"] = settings.MAX_MESSAGE_LENGTHstate["max_channel_folder_name_length"] = ChannelFolder.MAX_NAME_LENGTHdiff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex 7b02c964a19..cb89f35162b 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -13592,8 +13592,18 @@ paths:by the [`can_remove_subscribers_group`][can-remove-parameter]for the channel.- **Changes**: Before Zulip 10.0 (feature level 362),- subscriptions in archived channels could not be modified.+ When other users are removed from a channel, they may receive+ a direct message notifying them that they were unsubscribed by+ the current user; see+ [`send_messages_to_removed_subscribers`][send-notifications-param]+ below.++ **Changes**: Prior to Zulip 13.0 (feature level 515), the+ server never sent direct messages to users who were unsubscribed+ from one or more channels by the current user.++ Before Zulip 10.0 (feature level 362), subscriptions in archived+ channels could not be modified.Before Zulip 8.0 (feature level 208), if a user specified bythe [`principals`][principals-param] parameter was a@@ -13616,6 +13626,7 @@ paths:[principals-param]: /api/unsubscribe#parameter-principals[can-remove-parameter]: /api/subscribe#parameter-can_remove_subscribers_group+ [send-notifications-param]: /api/unsubscribe#parameter-send_messages_to_removed_subscribersx-curl-examples-parameters:oneOf:- type: include@@ -13648,6 +13659,21 @@ paths:example: ["Verona", "Denmark"]principals:$ref: "#/components/schemas/Principals"+ send_messages_to_removed_subscribers:+ description: |+ Whether other users unsubscribed via this request should be sent a+ direct message, from Notification Bot, notifying them that they+ were unsubscribed and by whom.++ The server will never send direct messages when the total number of+ users who were unsubscribed from channels in this request was more+ than the value of `max_bulk_subscription_messages`, which is+ available in the [`POST /register`](/api/register-queue) response.++ **Changes**: New in Zulip 13.0 (feature level 515).+ type: boolean+ default: true+ example: truerequired:- subscriptionsencoding:@@ -13655,6 +13681,8 @@ paths:contentType: application/jsonprincipals:contentType: application/json+ send_messages_to_removed_subscribers:+ contentType: application/jsonresponses:"200":description: Success.@@ -13682,8 +13710,22 @@ paths:description: |A list of the names of channels which were unsubscribed from as a resultof the query.+ messages_sent_to_removed_subscribers:+ type: boolean+ description: |+ Only present if the parameter `send_messages_to_removed_subscribers`+ in the request was `true`.++ Whether Notification Bot DMs were in fact sent to the removed+ subscribers as requested by the+ `send_messages_to_removed_subscribers` parameter. Clients may+ find this value useful to communicate with users about the+ effect of this request.++ **Changes**: New in Zulip 13.0 (feature level 515).example:{+ "messages_sent_to_removed_subscribers": true,"msg": "","not_removed": [],"removed": ["testing-help"],@@ -23129,13 +23171,21 @@ paths:Configuration for group level group permission settings.additionalProperties:$ref: "#/components/schemas/GroupPermissionSetting"- max_bulk_new_subscription_messages:+ max_bulk_subscription_messages:description: |- Maximum number of new subscribers for which the server will- respect the `send_new_subscription_messages` parameter when- [adding subscribers to a channel](/api/subscribe#parameter-send_new_subscription_messages).+ The maximum number of affected users for which the server will respect the+ [`send_new_subscription_messages` parameter][new-subs], when subscribing+ users to a channel, and the [`send_messages_to_removed_subscribers`+ parameter][removed-subs], when unsubscribing users from a channel.- **Changes**: New in Zulip 11.0 (feature level 397).+ **Changes**: Prior to Zulip 13.0 (feature level 515), this field+ was named `max_bulk_new_subscription_messages` as it only applied when+ subscribing users to a channel.++ New in Zulip 11.0 (feature level 397).++ [new-subs]: /api/subscribe#parameter-send_new_subscription_messages+ [removed-subs]: /api/unsubscribe#parameter-send_messages_to_removed_subscriberstype: numberexample: 100example:@@ -25725,7 +25775,7 @@ paths:The target message's ID.schema:type: integer- example: 47+ example: 48required: truerequestBody:required: true@@ -31393,7 +31443,7 @@ components:The server will never send direct messages when the total number of userswho were subscribed to channels in this request was more than the value- of `max_bulk_new_subscription_messages`, which is available in the [`POST+ of `max_bulk_subscription_messages`, which is available in the [`POST/register`](/api/register-queue) response.**Changes**: Before Zulip 11.0 (feature level 397), new subscribersdiff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.pyindex c9a36125655..3763b0839ff 100644--- a/zerver/tests/test_home.py+++ b/zerver/tests/test_home.py@@ -107,7 +107,7 @@ class HomeTest(ZulipTestCase):"klipy_api_key","last_event_id","max_avatar_file_size_mib",- "max_bulk_new_subscription_messages",+ "max_bulk_subscription_messages","max_channel_folder_description_length","max_channel_folder_name_length","max_file_upload_size_mib",diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.pyindex e5671037f64..0d442bf8b01 100644--- a/zerver/tests/test_subs.py+++ b/zerver/tests/test_subs.py@@ -67,7 +67,7 @@ from zerver.lib.subscription_info import (validate_user_access_to_subscribers_helper,)from zerver.lib.test_classes import ZulipTestCase, get_topic_messages-from zerver.lib.test_helpers import cache_tries_captured+from zerver.lib.test_helpers import cache_tries_captured, most_recent_messagefrom zerver.lib.types import UserGroupMembersDatafrom zerver.lib.user_groups import UserGroupMembershipDetails, get_group_setting_value_for_apifrom zerver.models import (@@ -3247,9 +3247,11 @@ class StreamAdminTest(ZulipTestCase):If you're a realm admin, you can remove people from public streams, eventhose you aren't on."""+ cordelia = self.example_user("cordelia")+ iago = self.example_user("iago")result = self.attempt_unsubscribe_of_principal(- query_count=15,- target_users=[self.example_user("cordelia")],+ query_count=38,+ target_users=[cordelia],is_realm_admin=True,is_subbed=True,invite_only=False,@@ -3259,6 +3261,14 @@ class StreamAdminTest(ZulipTestCase):self.assert_length(json["removed"], 1)self.assert_length(json["not_removed"], 0)+ msg = most_recent_message(cordelia)+ self.assertEqual(msg.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)+ self.assertEqual(msg.sender_id, self.notification_bot(cordelia.realm).id)+ self.assertEqual(+ msg.content,+ f"@_**Iago|{iago.id}** unsubscribed you from #**hümbüǵ**.",+ )+def test_realm_admin_remove_multiple_users_from_stream(self) -> None:"""If you're a realm admin, you can remove multiple users from a stream.@@ -3275,8 +3285,8 @@ class StreamAdminTest(ZulipTestCase):for name in ["cordelia", "prospero", "iago", "hamlet", "outgoing_webhook_bot"]]result = self.attempt_unsubscribe_of_principal(- query_count=22,- cache_count=12,+ query_count=59,+ cache_count=26,target_users=target_users,is_realm_admin=True,is_subbed=True,@@ -3292,9 +3302,11 @@ class StreamAdminTest(ZulipTestCase):If you're a realm admin, you can remove other people from private streams youare on."""+ cordelia = self.example_user("cordelia")+ iago = self.example_user("iago")result = self.attempt_unsubscribe_of_principal(- query_count=18,- target_users=[self.example_user("cordelia")],+ query_count=41,+ target_users=[cordelia],is_realm_admin=True,is_subbed=True,invite_only=True,@@ -3304,14 +3316,24 @@ class StreamAdminTest(ZulipTestCase):self.assert_length(json["removed"], 1)self.assert_length(json["not_removed"], 0)+ msg = most_recent_message(cordelia)+ self.assertEqual(msg.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)+ self.assertEqual(msg.sender_id, self.notification_bot(cordelia.realm).id)+ self.assertEqual(+ msg.content,+ f"@_**Iago|{iago.id}** unsubscribed you from #**hümbüǵ**.",+ )+def test_realm_admin_remove_others_from_unsubbed_private_stream(self) -> None:"""If you're a realm admin, you can remove people from privatestreams you aren't on."""+ cordelia = self.example_user("cordelia")+ iago = self.example_user("iago")result = self.attempt_unsubscribe_of_principal(- query_count=18,- target_users=[self.example_user("cordelia")],+ query_count=42,+ target_users=[cordelia],is_realm_admin=True,is_subbed=False,invite_only=True,@@ -3322,6 +3344,14 @@ class StreamAdminTest(ZulipTestCase):self.assert_length(json["removed"], 1)self.assert_length(json["not_removed"], 0)+ msg = most_recent_message(cordelia)+ self.assertEqual(msg.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)+ self.assertEqual(msg.sender_id, self.notification_bot(cordelia.realm).id)+ self.assertEqual(+ msg.content,+ f"@_**Iago|{iago.id}** unsubscribed you from #**hümbüǵ**.",+ )+def test_cant_remove_others_from_stream_legacy_emails(self) -> None:result = self.attempt_unsubscribe_of_principal(query_count=8,@@ -3335,9 +3365,11 @@ class StreamAdminTest(ZulipTestCase):self.assert_json_error(result, "Insufficient permission")def test_admin_remove_others_from_stream_legacy_emails(self) -> None:+ cordelia = self.example_user("cordelia")+ iago = self.example_user("iago")result = self.attempt_unsubscribe_of_principal(- query_count=15,- target_users=[self.example_user("cordelia")],+ query_count=38,+ target_users=[cordelia],is_realm_admin=True,is_subbed=True,invite_only=False,@@ -3348,9 +3380,17 @@ class StreamAdminTest(ZulipTestCase):self.assert_length(json["removed"], 1)self.assert_length(json["not_removed"], 0)+ msg = most_recent_message(cordelia)+ self.assertEqual(msg.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)+ self.assertEqual(msg.sender_id, self.notification_bot(cordelia.realm).id)+ self.assertEqual(+ msg.content,+ f"@_**Iago|{iago.id}** unsubscribed you from #**hümbüǵ**.",+ )+def test_admin_remove_multiple_users_from_stream_legacy_emails(self) -> None:result = self.attempt_unsubscribe_of_principal(- query_count=17,+ query_count=47,target_users=[self.example_user("cordelia"), self.example_user("prospero")],is_realm_admin=True,is_subbed=True,@@ -3503,6 +3543,346 @@ class StreamAdminTest(ZulipTestCase):).exists())+ def test_no_notification_on_self_unsubscribe(self) -> None:+ """+ When an admin unsubscribes themselves alongside other users in the+ same call, the admin should not receive a notification DM for+ their own unsubscription.+ """+ iago = self.example_user("iago")+ cordelia = self.example_user("cordelia")+ self.login_user(iago)+ stream_name = "test_self_unsub_filter"+ self.make_stream(stream_name)+ self.subscribe(iago, stream_name)+ self.subscribe(cordelia, stream_name)++ notification_bot = self.notification_bot(iago.realm)+ iago_dms_before = UserMessage.objects.filter(+ user_profile=iago,+ message__sender_id=notification_bot.id,+ ).count()+ cordelia_dms_before = UserMessage.objects.filter(+ user_profile=cordelia,+ message__sender_id=notification_bot.id,+ ).count()++ with self.captureOnCommitCallbacks(execute=True):+ result = self.client_delete(+ "/json/users/me/subscriptions",+ {+ "subscriptions": orjson.dumps([stream_name]).decode(),+ "principals": orjson.dumps([iago.id, cordelia.id]).decode(),+ },+ )+ json = self.assert_json_success(result)+ self.assert_length(json["removed"], 2)++ self.assertEqual(+ UserMessage.objects.filter(+ user_profile=cordelia,+ message__sender_id=notification_bot.id,+ ).count(),+ cordelia_dms_before + 1,+ )+ self.assertEqual(+ UserMessage.objects.filter(+ user_profile=iago,+ message__sender_id=notification_bot.id,+ ).count(),+ iago_dms_before,+ )++ def test_no_notification_for_bot_unsubscription(self) -> None:+ """+ When an admin unsubscribes a bot alongside a regular user in the+ same call, the bot should not receive a notification DM.+ """+ iago = self.example_user("iago")+ hamlet = self.example_user("hamlet")+ cordelia = self.example_user("cordelia")+ webhook_bot = self.example_user("webhook_bot")+ do_change_bot_owner(webhook_bot, bot_owner=hamlet, acting_user=hamlet)+ self.login_user(iago)+ stream_name = "test_bot_unsub_filter"+ self.make_stream(stream_name)+ self.subscribe(iago, stream_name)+ self.subscribe(cordelia, stream_name)+ self.subscribe(webhook_bot, stream_name)++ notification_bot = self.notification_bot(iago.realm)+ bot_dms_before = UserMessage.objects.filter(+ user_profile=webhook_bot,+ message__sender_id=notification_bot.id,+ ).count()+ cordelia_dms_before = UserMessage.objects.filter(+ user_profile=cordelia,+ message__sender_id=notification_bot.id,+ ).count()++ with self.captureOnCommitCallbacks(execute=True):+ result = self.client_delete(+ "/json/users/me/subscriptions",+ {+ "subscriptions": orjson.dumps([stream_name]).decode(),+ "principals": orjson.dumps([cordelia.id, webhook_bot.id]).decode(),+ },+ )+ json = self.assert_json_success(result)+ self.assert_length(json["removed"], 2)++ self.assertEqual(+ UserMessage.objects.filter(+ user_profile=cordelia,+ message__sender_id=notification_bot.id,+ ).count(),+ cordelia_dms_before + 1,+ )+ self.assertEqual(+ UserMessage.objects.filter(+ user_profile=webhook_bot,+ message__sender_id=notification_bot.id,+ ).count(),+ bot_dms_before,+ )++ def test_notification_multiple_channels_unsubscription(self) -> None:+ """+ When a user is unsubscribed from multiple channels at once, they+ receive a single DM listing all channels as a bullet list.+ """+ cordelia = self.example_user("cordelia")+ iago = self.example_user("iago")+ self.login_user(iago)++ stream_names = ["alpha_stream", "beta_stream"]+ for stream_name in stream_names:+ self.make_stream(stream_name)+ self.subscribe(iago, stream_name)+ self.subscribe(cordelia, stream_name)++ with self.captureOnCommitCallbacks(execute=True):+ result = self.client_delete(+ "/json/users/me/subscriptions",+ {+ "subscriptions": orjson.dumps(stream_names).decode(),+ "principals": orjson.dumps([cordelia.id]).decode(),+ },+ )+ json = self.assert_json_success(result)+ self.assert_length(json["removed"], 2)++ msg = most_recent_message(cordelia)+ self.assertEqual(msg.recipient.type, Recipient.DIRECT_MESSAGE_GROUP)+ self.assertEqual(msg.sender_id, self.notification_bot(cordelia.realm).id)+ self.assertEqual(+ msg.content,+ f"@_**Iago|{iago.id}** unsubscribed you from the following channels:\n\n"+ "* #**alpha_stream**\n"+ "* #**beta_stream**",+ )++ def test_no_notification_when_bulk_unsubscription_exceeds_limit(self) -> None:+ """+ When more than MAX_BULK_SUBSCRIPTION_MESSAGES users are+ unsubscribed at once, no notification DMs should be sent.+ """+ cordelia = self.example_user("cordelia")+ hamlet = self.example_user("hamlet")+ iago = self.example_user("iago")+ self.login_user(iago)+ stream_name = "test_bulk_unsub"+ self.make_stream(stream_name)+ self.subscribe(iago, stream_name)+ self.subscribe(cordelia, stream_name)+ self.subscribe(hamlet, stream_name)++ notification_bot = self.notification_bot(iago.realm)+ msg_count_before = UserMessage.objects.filter(+ user_profile__in=[cordelia, hamlet],+ message__sender_id=notification_bot.id,+ ).count()++ with (+ self.settings(MAX_BULK_SUBSCRIPTION_MESSAGES=1),+ self.captureOnCommitCallbacks(execute=True),+ ):+ result = self.client_delete(+ "/json/users/me/subscriptions",+ {+ "subscriptions": orjson.dumps([stream_name]).decode(),+ "principals": orjson.dumps([cordelia.id, hamlet.id]).decode(),+ },+ )++ json = self.assert_json_success(result)+ self.assert_length(json["removed"], 2)+ self.assertFalse(json["messages_sent_to_removed_subscribers"])++ msg_count_after = UserMessage.objects.filter(+ user_profile__in=[cordelia, hamlet],+ message__sender_id=notification_bot.id,+ ).count()+ self.assertEqual(msg_count_before, msg_count_after)++ def test_no_notification_when_send_messages_disabled(self) -> None:+ """+ When `send_messages_to_removed_subscribers=False` is passed,+ no notification DMs should be sent and the response should not+ include a `messages_sent_to_removed_subscribers` field.+ """+ iago = self.example_user("iago")+ cordelia = self.example_user("cordelia")+ self.login_user(iago)+ stream_name = "test_send_messages_false"+ self.make_stream(stream_name)+ self.subscribe(iago, stream_name)+ self.subscribe(cordelia, stream_name)++ notification_bot = self.notification_bot(iago.realm)+ cordelia_dms_before = UserMessage.objects.filter(+ user_profile=cordelia,+ message__sender_id=notification_bot.id,+ ).count()++ with self.captureOnCommitCallbacks(execute=True):+ result = self.client_delete(+ "/json/users/me/subscriptions",+ {+ "subscriptions": orjson.dumps([stream_name]).decode(),+ "principals": orjson.dumps([cordelia.id]).decode(),+ "send_messages_to_removed_subscribers": orjson.dumps(False).decode(),+ },+ )+ json = self.assert_json_success(result)+ self.assert_length(json["removed"], 1)+ self.assertNotIn("messages_sent_to_removed_subscribers", json)++ self.assertEqual(+ UserMessage.objects.filter(+ user_profile=cordelia,+ message__sender_id=notification_bot.id,+ ).count(),+ cordelia_dms_before,+ )++ def test_self_unsubscribe_reports_no_messages_sent(self) -> None:+ """+ A plain self-unsubscribe sends no DM, so the response reports+ messages_sent_to_removed_subscribers as False rather than True.+ """+ hamlet = self.example_user("hamlet")+ self.login_user(hamlet)+ stream_name = "test_self_unsub_field"+ self.make_stream(stream_name)+ self.subscribe(hamlet, stream_name)++ notification_bot = self.notification_bot(hamlet.realm)+ hamlet_dms_before = UserMessage.objects.filter(+ user_profile=hamlet,+ message__sender_id=notification_bot.id,+ ).count()++ with self.captureOnCommitCallbacks(execute=True):+ result = self.client_delete(+ "/json/users/me/subscriptions",+ {"subscriptions": orjson.dumps([stream_name]).decode()},+ )+ json = self.assert_json_success(result)+ self.assert_length(json["removed"], 1)+ self.assertFalse(json["messages_sent_to_removed_subscribers"])++ self.assertEqual(+ UserMessage.objects.filter(+ user_profile=hamlet,+ message__sender_id=notification_bot.id,+ ).count(),+ hamlet_dms_before,+ )++ def test_notification_cap_counts_only_eligible_recipients(self) -> None:+ """+ The bulk cap applies to the users who will actually be notified, so+ a self-unsubscribe and a bot removed in the same call do not count+ against it and do not block an eligible user's notification.+ """+ iago = self.example_user("iago")+ cordelia = self.example_user("cordelia")+ webhook_bot = self.example_user("webhook_bot")+ do_change_bot_owner(webhook_bot, bot_owner=iago, acting_user=iago)+ self.login_user(iago)+ stream_name = "test_cap_eligible"+ self.make_stream(stream_name)+ for user in [iago, cordelia, webhook_bot]:+ self.subscribe(user, stream_name)++ notification_bot = self.notification_bot(iago.realm)+ cordelia_dms_before = UserMessage.objects.filter(+ user_profile=cordelia,+ message__sender_id=notification_bot.id,+ ).count()++ # Three users are removed, but only cordelia is an eligible+ # recipient, so a cap of 1 must not block her notification.+ with (+ self.settings(MAX_BULK_SUBSCRIPTION_MESSAGES=1),+ self.captureOnCommitCallbacks(execute=True),+ ):+ result = self.client_delete(+ "/json/users/me/subscriptions",+ {+ "subscriptions": orjson.dumps([stream_name]).decode(),+ "principals": orjson.dumps([iago.id, cordelia.id, webhook_bot.id]).decode(),+ },+ )+ json = self.assert_json_success(result)+ self.assert_length(json["removed"], 3)+ self.assertTrue(json["messages_sent_to_removed_subscribers"])++ self.assertEqual(+ UserMessage.objects.filter(+ user_profile=cordelia,+ message__sender_id=notification_bot.id,+ ).count(),+ cordelia_dms_before + 1,+ )++ def test_unsubscriptions_query_count(self) -> None:+ """+ Test database query count when unsubscribing users via+ api/v1/users/me/subscriptions, including the DM notification.+ """+ iago = self.example_user("iago")+ cordelia = self.example_user("cordelia")+ hamlet = self.example_user("hamlet")+ self.login_user(iago)++ public_stream = "public_unsub_qc"+ self.make_stream(public_stream)+ for user in [iago, cordelia, hamlet]:+ self.subscribe(user, public_stream)+ with self.assert_database_query_count(43):+ self.client_delete(+ "/json/users/me/subscriptions",+ {+ "subscriptions": orjson.dumps([public_stream]).decode(),+ "principals": orjson.dumps([cordelia.id, hamlet.id]).decode(),+ },+ )++ private_stream = "private_unsub_qc"+ self.make_stream(private_stream, invite_only=True)+ for user in [iago, cordelia, hamlet]:+ self.subscribe(user, private_stream)+ with self.assert_database_query_count(37):+ self.client_delete(+ "/json/users/me/subscriptions",+ {+ "subscriptions": orjson.dumps([private_stream]).decode(),+ "principals": orjson.dumps([cordelia.id, hamlet.id]).decode(),+ },+ )+class SubscriptionRestApiTest(ZulipTestCase):def test_add_with_invalid_color(self) -> None:@@ -5510,7 +5890,7 @@ class SubscriptionAPITest(ZulipTestCase):now = timezone_now()test_channel = self.make_stream("test C")with (- self.settings(MAX_BULK_NEW_SUBSCRIPTION_MESSAGES=5),+ self.settings(MAX_BULK_SUBSCRIPTION_MESSAGES=5),self.assert_database_query_count(19),):response = self.subscribe_via_post(@@ -5544,7 +5924,7 @@ class SubscriptionAPITest(ZulipTestCase):# message (and no DM notifications).now = timezone_now()with (- self.settings(MAX_BULK_NEW_SUBSCRIPTION_MESSAGES=5),+ self.settings(MAX_BULK_SUBSCRIPTION_MESSAGES=5),self.assert_database_query_count(53),):response = self.subscribe_via_post(diff --git a/zerver/views/streams.py b/zerver/views/streams.pyindex 1c11c65062d..1ba649695ed 100644--- a/zerver/views/streams.py+++ b/zerver/views/streams.py@@ -576,6 +576,7 @@ def remove_subscriptions_backend(user_profile: UserProfile,*,principals: Json[list[str] | list[int]] | None = None,+ send_messages_to_removed_subscribers: Json[bool] = True,streams_raw: Annotated[Json[list[str]], ApiParamConfig("subscriptions")],) -> HttpResponse:realm = user_profile.realm@@ -600,38 +601,69 @@ def remove_subscriptions_backend(unsubscribing_others=unsubscribing_others,)- result: dict[str, list[str]] = dict(removed=[], not_removed=[])(removed, not_subscribed) = bulk_remove_subscriptions(realm, people_to_unsub, streams, acting_user=user_profile)- for subscriber, removed_stream in removed:- result["removed"].append(removed_stream.name)- for subscriber, not_subscribed_stream in not_subscribed:- result["not_removed"].append(not_subscribed_stream.name)+ result: dict[str, list[str] | bool] = dict(+ removed=[stream.name for __, stream in removed],+ not_removed=[stream.name for __, stream in not_subscribed],+ )++ if send_messages_to_removed_subscribers:+ result["messages_sent_to_removed_subscribers"] = send_user_unsubscribed_notifications(+ acting_user=user_profile,+ removed=removed,+ )return json_success(request, data=result)+def format_channel_notification_message(+ acting_user: UserProfile,+ channel_names: set[str],+ single_channel_message: str,+ multiple_channels_message: str,+) -> str:+ # The message templates are passed in already translated so that their+ # literals stay individually extractable for translation.+ channels = sorted(channel_names)+ user_full_name = silent_mention_syntax_for_user(acting_user)+ if len(channels) == 1:+ return single_channel_message.format(+ user_full_name=user_full_name,+ channel_name=f"#**{channels[0]}**",+ )++ message = multiple_channels_message.format(user_full_name=user_full_name)+ message += "\n\n"+ for channel_name in channels:+ message += f"* #**{channel_name}**\n"+ return message++def you_were_just_subscribed_message(acting_user: UserProfile, recipient_user: UserProfile, stream_names: set[str]) -> str:- subscriptions = sorted(stream_names)- if len(subscriptions) == 1:- with override_language(recipient_user.default_language):- return _("{user_full_name} subscribed you to {channel_name}.").format(- user_full_name=silent_mention_syntax_for_user(acting_user),- channel_name=f"#**{subscriptions[0]}**",- )+ with override_language(recipient_user.default_language):+ single_channel_message = _("{user_full_name} subscribed you to {channel_name}.")+ multiple_channels_message = _("{user_full_name} subscribed you to the following channels:")+ return format_channel_notification_message(+ acting_user, stream_names, single_channel_message, multiple_channels_message+ )++def you_were_just_unsubscribed_message(+ acting_user: UserProfile, recipient_user: UserProfile, channel_names: set[str]+) -> str:with override_language(recipient_user.default_language):- message = _("{user_full_name} subscribed you to the following channels:").format(- user_full_name=silent_mention_syntax_for_user(acting_user),+ single_channel_message = _("{user_full_name} unsubscribed you from {channel_name}.")+ multiple_channels_message = _(+ "{user_full_name} unsubscribed you from the following channels:")- message += "\n\n"- for channel_name in subscriptions:- message += f"* #**{channel_name}**\n"- return message+ return format_channel_notification_message(+ acting_user, channel_names, single_channel_message, multiple_channels_message+ )RETENTION_DEFAULT: str | int = "realm_default"@@ -932,7 +964,7 @@ def add_subscriptions_backend(if send_new_subscription_messages:send_user_subscribed_direct_messages = (- len(result["subscribed"]) <= settings.MAX_BULK_NEW_SUBSCRIPTION_MESSAGES+ len(result["subscribed"]) <= settings.MAX_BULK_SUBSCRIPTION_MESSAGES)result["new_subscription_messages_sent"] = send_user_subscribed_direct_messageselse:@@ -954,6 +986,57 @@ def add_subscriptions_backend(return json_success(request, data=result)+def send_user_unsubscribed_notifications(+ acting_user: UserProfile,+ removed: list[tuple[UserProfile, Stream]],+) -> bool:+ """Notifies each user unsubscribed by someone else with a Notification+ Bot direct message, and returns whether any such messages were sent.+ Self-unsubscribes and bots do not receive these notifications."""+ channels_by_user: dict[int, set[str]] = defaultdict(set)+ user_by_id: dict[int, UserProfile] = {}+ for user, channel in removed:+ if user.id == acting_user.id:+ # Don't notify users who unsubscribed themselves.+ continue+ if user.is_bot:+ # Don't send notification DMs to bots.+ continue+ channels_by_user[user.id].add(channel.name)+ user_by_id[user.id] = user++ if not channels_by_user:+ return False++ if len(channels_by_user) > settings.MAX_BULK_SUBSCRIPTION_MESSAGES:+ # Skip these DMs when a very large number of users are unsubscribed+ # at once, as sending them can be expensive and spammy.+ return False++ sender = get_system_bot(settings.NOTIFICATION_BOT, acting_user.realm_id)+ mention_backend = MentionBackend(acting_user.realm_id)+ notifications = []+ for user_id, channel_names in channels_by_user.items():+ recipient_user = user_by_id[user_id]+ msg = you_were_just_unsubscribed_message(+ acting_user=acting_user,+ recipient_user=recipient_user,+ channel_names=channel_names,+ )+ notifications.append(+ internal_prep_private_message(+ sender=sender,+ recipient_user=recipient_user,+ content=msg,+ mention_backend=mention_backend,+ acting_user=acting_user,+ )+ )++ do_send_messages(notifications)+ return True++def send_user_subscribed_and_new_channel_notifications(user_profile: UserProfile,subscribers: set[UserProfile],diff --git a/zproject/default_settings.py b/zproject/default_settings.pyindex d5a8d969923..32573bb1a72 100644--- a/zproject/default_settings.py+++ b/zproject/default_settings.py@@ -735,9 +735,10 @@ MAX_STREAM_SIZE_FOR_TYPING_NOTIFICATIONS = 100# be soft-reactivated in the case of user group mention.MAX_GROUP_SIZE_FOR_MENTION_REACTIVATION = 11-# The maximum number of newly subscribed users for which the server-# will consider sending DMs to each new subscriber.-MAX_BULK_NEW_SUBSCRIPTION_MESSAGES = 100+# The maximum number of affected users for which the server will consider+# sending DMs notifications to each user when they are subscribed to, or+# unsubscribed from, channels in bulk.+MAX_BULK_SUBSCRIPTION_MESSAGES = 100# Limiting guest access to other users via the# can_access_all_users_group setting makes presence queries much more