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.

notifications: Don't enqueue notifications for bots.

Abhijeet Prasad Bodas15e871784725
diff --git a/zerver/lib/actions.py b/zerver/lib/actions.py
index a976c545b9f..9f628d8c421 100644
--- a/zerver/lib/actions.py
+++ b/zerver/lib/actions.py
@@ -1539,6 +1539,7 @@ class RecipientInfoResult(TypedDict):
long_term_idle_user_ids: Set[int]
default_bot_user_ids: Set[int]
service_bot_tuples: List[Tuple[int, int]]
+ all_bot_user_ids: Set[int]
def get_recipient_info(
@@ -1720,7 +1721,7 @@ def get_recipient_info(
lambda r: r["long_term_idle"],
)
- # These two bot data structures need to filter from the full set
+ # These three bot data structures need to filter from the full set
# of users who either are receiving the message or might have been
# mentioned in it, and so can't use get_ids_for.
#
@@ -1736,6 +1737,11 @@ def get_recipient_info(
service_bot_tuples = [(row["id"], row["bot_type"]) for row in rows if is_service_bot(row)]
+ # We also need the user IDs of all bots, to avoid trying to send push/email
+ # notifications to them. This set will be directly sent to the event queue code
+ # where we determine notifiability of the message for users.
+ all_bot_user_ids = {row["id"] for row in rows if row["is_bot"]}
+
info: RecipientInfoResult = dict(
active_user_ids=active_user_ids,
online_push_user_ids=online_push_user_ids,
@@ -1749,6 +1755,7 @@ def get_recipient_info(
long_term_idle_user_ids=long_term_idle_user_ids,
default_bot_user_ids=default_bot_user_ids,
service_bot_tuples=service_bot_tuples,
+ all_bot_user_ids=all_bot_user_ids,
)
return info
@@ -1957,6 +1964,7 @@ def build_message_send_dict(
long_term_idle_user_ids=info["long_term_idle_user_ids"],
default_bot_user_ids=info["default_bot_user_ids"],
service_bot_tuples=info["service_bot_tuples"],
+ all_bot_user_ids=info["all_bot_user_ids"],
wildcard_mention_user_ids=wildcard_mention_user_ids,
links_for_embed=links_for_embed,
widget_content=widget_content_dict,
@@ -2113,6 +2121,7 @@ def do_send_messages(
stream_email_user_ids=send_request.stream_email_user_ids,
wildcard_mention_user_ids=send_request.wildcard_mention_user_ids,
muted_sender_user_ids=send_request.muted_sender_user_ids,
+ all_bot_user_ids=send_request.all_bot_user_ids,
),
)
for user_id in send_request.active_user_ids
@@ -2138,6 +2147,7 @@ def do_send_messages(
stream_email_user_ids=list(send_request.stream_email_user_ids),
wildcard_mention_user_ids=list(send_request.wildcard_mention_user_ids),
muted_sender_user_ids=list(send_request.muted_sender_user_ids),
+ all_bot_user_ids=list(send_request.all_bot_user_ids),
)
if send_request.message.is_stream_message():
@@ -6449,6 +6459,7 @@ def do_update_message(
event["muted_sender_user_ids"] = list(info["muted_sender_user_ids"])
event["prior_mention_user_ids"] = list(prior_mention_user_ids)
event["presence_idle_user_ids"] = filter_presence_idle_user_ids(info["active_user_ids"])
+ event["all_bot_user_ids"] = list(info["all_bot_user_ids"])
if rendering_result.mentions_wildcard:
event["wildcard_mention_user_ids"] = list(info["wildcard_mention_user_ids"])
else:
diff --git a/zerver/lib/email_notifications.py b/zerver/lib/email_notifications.py
index 658bf3abaad..23b30db459b 100644
--- a/zerver/lib/email_notifications.py
+++ b/zerver/lib/email_notifications.py
@@ -1,5 +1,6 @@
# See https://zulip.readthedocs.io/en/latest/subsystems/notifications.html
+import logging
import math
import re
from collections import defaultdict
@@ -43,6 +44,8 @@ from zerver.models import (
get_user_profile_by_id,
)
+logger = logging.getLogger(__name__)
+
def relative_to_full_url(fragment: lxml.html.HtmlElement, base_url: str) -> None:
# We handle narrow URLs separately because of two reasons:
@@ -569,8 +572,13 @@ def handle_missedmessage_emails(
}
user_profile = get_user_profile_by_id(user_profile_id)
- if user_profile.is_bot: # nocoverage # TODO -- needs a test.
- # Never email bot users.
+ if user_profile.is_bot: # nocoverage
+ # We don't expect to reach here for bot users. However, this code exists
+ # to find and throw away any pre-existing events in the queue while
+ # upgrading from versions before our notifiability logic was implemented.
+ # TODO/compatibility: This block can be removed when one can no longer
+ # upgrade from versions <= 4.0 to versions >= 5.0
+ logger.warning("Send-email event found for bot user %s. Skipping.", user_profile_id)
return
if not user_profile.enable_offline_email_notifications:
diff --git a/zerver/lib/message.py b/zerver/lib/message.py
index fb557cdc2f7..887885085ba 100644
--- a/zerver/lib/message.py
+++ b/zerver/lib/message.py
@@ -119,6 +119,7 @@ class SendMessageRequest:
long_term_idle_user_ids: Set[int]
default_bot_user_ids: Set[int]
service_bot_tuples: List[Tuple[int, int]]
+ all_bot_user_ids: Set[int]
wildcard_mention_user_ids: Set[int]
links_for_embed: Set[str]
widget_content: Optional[Dict[str, Any]]
diff --git a/zerver/lib/notification_data.py b/zerver/lib/notification_data.py
index 92d35d88c78..a789fc768a7 100644
--- a/zerver/lib/notification_data.py
+++ b/zerver/lib/notification_data.py
@@ -41,8 +41,25 @@ class UserMessageNotificationsData:
stream_email_user_ids: Set[int],
wildcard_mention_user_ids: Set[int],
muted_sender_user_ids: Set[int],
+ all_bot_user_ids: Set[int],
) -> "UserMessageNotificationsData":
+ if user_id in all_bot_user_ids:
+ # Don't send any notifications to bots
+ return cls(
+ user_id=user_id,
+ pm_email_notify=False,
+ mention_email_notify=False,
+ wildcard_mention_email_notify=False,
+ pm_push_notify=False,
+ mention_push_notify=False,
+ wildcard_mention_push_notify=False,
+ online_push_enabled=False,
+ stream_push_notify=False,
+ stream_email_notify=False,
+ sender_is_muted=False,
+ )
+
# `wildcard_mention_user_ids` are those user IDs for whom wildcard mentions should
# obey notification settings of personal mentions. Hence, it isn't an independent
# notification setting and acts as a wrapper.
diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.py
index 384bb8c8620..747abd52694 100644
--- a/zerver/lib/push_notifications.py
+++ b/zerver/lib/push_notifications.py
@@ -948,9 +948,16 @@ def handle_push_notification(user_profile_id: int, missed_message: Dict[str, Any
return
user_profile = get_user_profile_by_id(user_profile_id)
- if user_profile.is_bot:
- # BUG: Investigate why it's possible to get here.
- return # nocoverage
+ if user_profile.is_bot: # nocoverage
+ # We don't expect to reach here for bot users. However, this code exists
+ # to find and throw away any pre-existing events in the queue while
+ # upgrading from versions before our notifiability logic was implemented.
+ # TODO/compatibility: This block can be removed when one can no longer
+ # upgrade from versions <= 4.0 to versions >= 5.0
+ logger.warning(
+ "Send-push-notification event found for bot user %s. Skipping.", user_profile_id
+ )
+ return
if not (
user_profile.enable_offline_push_notifications
diff --git a/zerver/tests/test_event_queue.py b/zerver/tests/test_event_queue.py
index 559ce90799c..d2a0c8ac6d3 100644
--- a/zerver/tests/test_event_queue.py
+++ b/zerver/tests/test_event_queue.py
@@ -575,6 +575,32 @@ class MissedMessageNotificationsTest(ZulipTestCase):
result = self.api_delete(user_profile, f"/api/v1/users/me/muted_users/{iago.id}")
self.assert_json_success(result)
+ # Test that bots don't receive any notifications
+ bot_info = {
+ "full_name": "The Bot of Hamlet",
+ "short_name": "hambot",
+ "bot_type": "1",
+ }
+ result = self.client_post("/json/bots", bot_info)
+ self.assert_json_success(result)
+ hambot = UserProfile.objects.get(id=result.json()["user_id"])
+ client_descriptor = allocate_event_queue(hambot)
+ self.assertTrue(client_descriptor.event_queue.empty())
+ msg_id = self.send_personal_message(iago, hambot)
+ with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue:
+ missedmessage_hook(hambot.id, client_descriptor, True)
+ mock_enqueue.assert_called_once()
+ args_dict = mock_enqueue.call_args_list[0][1]
+
+ # Defaults are all False
+ assert_maybe_enqueue_notifications_call_args(
+ user_id=hambot.id,
+ args_dict=args_dict,
+ message_id=msg_id,
+ )
+ destroy_event_queue(hambot, client_descriptor.event_queue.id)
+ self.assert_json_success(result)
+
class FileReloadLogicTest(ZulipTestCase):
def test_persistent_queue_filename(self) -> None:
diff --git a/zerver/tests/test_notification_data.py b/zerver/tests/test_notification_data.py
index 79926a3457b..e55abd236ee 100644
--- a/zerver/tests/test_notification_data.py
+++ b/zerver/tests/test_notification_data.py
@@ -1,10 +1,15 @@
from zerver.lib.mention import MentionBackend, MentionData
-from zerver.lib.notification_data import get_user_group_mentions_data
+from zerver.lib.notification_data import UserMessageNotificationsData, get_user_group_mentions_data
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.user_groups import create_user_group
class TestNotificationData(ZulipTestCase):
+ """
+ Because the `UserMessageNotificationsData` does not do any database queries, all user IDs
+ used in the following tests are arbitrary, and do not represent real users.
+ """
+
def test_is_push_notifiable(self) -> None:
user_id = self.example_user("hamlet").id
acting_user_id = self.example_user("cordelia").id
@@ -212,6 +217,24 @@ class TestNotificationData(ZulipTestCase):
user_data = self.create_user_notifications_data_object(user_id=user_id, pm_push_notify=True)
self.assertTrue(user_data.is_notifiable(acting_user_id=acting_user_id, idle=True))
+ def test_bot_user_notifiability(self) -> None:
+ # Non-bot user (`user_id=9`) should get notified, while bot user (`user_id=10`) shouldn't
+ for user_id, notifiable in [(9, True), (10, False)]:
+ user_data = UserMessageNotificationsData.from_user_id_sets(
+ user_id=user_id,
+ flags=["mentioned"],
+ private_message=True,
+ online_push_user_ids=set(),
+ pm_mention_email_disabled_user_ids=set(),
+ pm_mention_push_disabled_user_ids=set(),
+ all_bot_user_ids={10, 11, 12},
+ muted_sender_user_ids=set(),
+ stream_email_user_ids=set(),
+ stream_push_user_ids=set(),
+ wildcard_mention_user_ids=set(),
+ )
+ self.assertEqual(user_data.is_notifiable(acting_user_id=1000, idle=True), notifiable)
+
def test_user_group_mentions_map(self) -> None:
hamlet = self.example_user("hamlet")
cordelia = self.example_user("cordelia")
diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py
index 23198d2e77a..fa4d6961da7 100644
--- a/zerver/tests/test_users.py
+++ b/zerver/tests/test_users.py
@@ -1586,6 +1586,7 @@ class RecipientInfoTest(ZulipTestCase):
long_term_idle_user_ids=set(),
default_bot_user_ids=set(),
service_bot_tuples=[],
+ all_bot_user_ids=set(),
)
self.assertEqual(info, expected_info)
@@ -1767,6 +1768,7 @@ class RecipientInfoTest(ZulipTestCase):
possibly_mentioned_user_ids={service_bot.id, normal_bot.id},
)
self.assertEqual(info["default_bot_user_ids"], {normal_bot.id})
+ self.assertEqual(info["all_bot_user_ids"], {normal_bot.id, service_bot.id})
def test_get_recipient_info_invalid_recipient_type(self) -> None:
hamlet = self.example_user("hamlet")
diff --git a/zerver/tornado/event_queue.py b/zerver/tornado/event_queue.py
index 93697aac22c..e191ff88048 100644
--- a/zerver/tornado/event_queue.py
+++ b/zerver/tornado/event_queue.py
@@ -920,6 +920,7 @@ def process_message_event(
stream_email_user_ids = set(event_template.get("stream_email_user_ids", []))
wildcard_mention_user_ids = set(event_template.get("wildcard_mention_user_ids", []))
muted_sender_user_ids = set(event_template.get("muted_sender_user_ids", []))
+ all_bot_user_ids = set(event_template.get("all_bot_user_ids", []))
wide_dict: Dict[str, Any] = event_template["message_dict"]
@@ -967,6 +968,7 @@ def process_message_event(
stream_email_user_ids=stream_email_user_ids,
wildcard_mention_user_ids=wildcard_mention_user_ids,
muted_sender_user_ids=muted_sender_user_ids,
+ all_bot_user_ids=all_bot_user_ids,
)
internal_data = asdict(user_notifications_data)
@@ -1113,6 +1115,7 @@ def process_message_update_event(
stream_email_user_ids = set(event_template.pop("stream_email_user_ids", []))
wildcard_mention_user_ids = set(event_template.pop("wildcard_mention_user_ids", []))
muted_sender_user_ids = set(event_template.pop("muted_sender_user_ids", []))
+ all_bot_user_ids = set(event_template.pop("all_bot_user_ids", []))
# TODO/compatibility: Translation code for the rename of
# `push_notify_user_ids` to `online_push_user_ids`. Remove this
@@ -1159,6 +1162,7 @@ def process_message_update_event(
stream_email_user_ids=stream_email_user_ids,
wildcard_mention_user_ids=wildcard_mention_user_ids,
muted_sender_user_ids=muted_sender_user_ids,
+ all_bot_user_ids=all_bot_user_ids,
)
maybe_enqueue_notifications_for_message_update(