Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
digest: Exclude muted topics from hot conversations.
Aman Agrawal12ecdbe4a6d5
diff --git a/zerver/lib/digest.py b/zerver/lib/digest.pyindex fe6cdc5beef..80dc2edda2f 100644--- a/zerver/lib/digest.py+++ b/zerver/lib/digest.py@@ -37,6 +37,7 @@ from zerver.models import (UserActivityInterval,UserMessage,UserProfile,+ UserTopic,)from zerver.models.realm_audit_logs import AuditLogEventTypefrom zerver.models.streams import get_active_streams@@ -68,6 +69,9 @@ class DigestTopic:# topic_key is (stream_id, topic_name)return self.topic_key[0]+ def topic_name(self) -> str:+ return self.topic_key[1]+def add_message(self, message: Message) -> None:if len(self.sample_messages) < 2:self.sample_messages.append(message)@@ -356,6 +360,21 @@ def get_user_stream_map(user_ids: list[int], cutoff_date: datetime) -> dict[int,return dct+def get_user_muted_topics_map(user_ids: list[int]) -> dict[int, set[tuple[int, str]]]:+ # maps user_id -> {(stream_id, lowercased topic_name), ...};+ # topic names are matched case-insensitively.+ rows = UserTopic.objects.filter(+ user_profile_id__in=user_ids,+ visibility_policy=UserTopic.VisibilityPolicy.MUTED,+ ).values("user_profile_id", "stream_id", "topic_name")++ dct: dict[int, set[tuple[int, str]]] = defaultdict(set)+ for row in rows:+ dct[row["user_profile_id"]].add((row["stream_id"], row["topic_name"].lower()))++ return dct++def get_slim_stream_id_map(stream_ids: set[int]) -> dict[int, Stream]:# "slim" because it only fetches the names of the stream objects,# suitable for passing into build_message_list.@@ -383,6 +402,7 @@ def bulk_get_digest_context(user_stream_map = get_user_stream_map(user_ids, cutoff_date)stream_ids = set().union(*user_stream_map.values())stream_id_map = get_slim_stream_id_map(stream_ids)+ user_muted_topics_map = get_user_muted_topics_map(user_ids)for user in users:context = common_context(user)@@ -414,9 +434,17 @@ def bulk_get_digest_context(else:# Otherwise, get context data for hot conversations.stream_ids = user_stream_map[user.id]+ muted_topics = user_muted_topics_map[user.id]recent_topics = []for stream_id in stream_ids:- recent_topics += get_recent_topics(realm.id, stream_id, cutoff_date)+ recent_topics += [+ digest_topic+ for digest_topic in get_recent_topics(realm.id, stream_id, cutoff_date)+ # Topics the user has muted should not be featured+ # in their digest.+ if (digest_topic.stream_id(), digest_topic.topic_name().lower())+ not in muted_topics+ ]hot_topics = get_hot_topics(recent_topics, stream_ids)context["hot_conversations"] = [diff --git a/zerver/tests/test_digest.py b/zerver/tests/test_digest.pyindex ee8d553f903..3c07a00d5e2 100644--- a/zerver/tests/test_digest.py+++ b/zerver/tests/test_digest.py@@ -10,6 +10,7 @@ from confirmation.models import one_click_unsubscribe_linkfrom zerver.actions.create_user import do_create_userfrom zerver.actions.realm_settings import do_set_realm_propertyfrom zerver.actions.streams import do_deactivate_stream+from zerver.actions.user_topics import do_set_user_topic_visibility_policyfrom zerver.actions.users import do_deactivate_userfrom zerver.lib.digest import (DigestTopic,@@ -28,7 +29,15 @@ from zerver.lib.email_notifications import get_channel_privacy_iconfrom zerver.lib.message import get_last_message_idfrom zerver.lib.streams import create_stream_if_neededfrom zerver.lib.test_classes import ZulipTestCase-from zerver.models import Message, Realm, RealmAuditLog, Stream, UserActivityInterval, UserProfile+from zerver.models import (+ Message,+ Realm,+ RealmAuditLog,+ Stream,+ UserActivityInterval,+ UserProfile,+ UserTopic,+)from zerver.models.realm_audit_logs import AuditLogEventTypefrom zerver.models.realms import get_realmfrom zerver.models.streams import get_stream@@ -64,7 +73,7 @@ class TestDigestEmailMessages(ZulipTestCase):# Clear the LRU cache on the stream topicsget_recent_topics.cache_clear()- with self.assert_database_query_count(10):+ with self.assert_database_query_count(11):bulk_handle_digest_email([othello.id], cutoff)self.assertEqual(mock_send_future_email.call_count, 1)@@ -85,7 +94,7 @@ class TestDigestEmailMessages(ZulipTestCase):# are 3 reused streams and one new one, for a net of two fewer# than before.iago = self.example_user("iago")- with self.assert_database_query_count(10):+ with self.assert_database_query_count(11):bulk_handle_digest_email([iago.id], cutoff)self.assertEqual(get_recent_topics.cache_info().hits, 3)self.assertEqual(get_recent_topics.cache_info().currsize, 6)@@ -94,17 +103,60 @@ class TestDigestEmailMessages(ZulipTestCase):# the above.cordelia = self.example_user("cordelia")prospero = self.example_user("prospero")- with self.assert_database_query_count(9):+ with self.assert_database_query_count(10):bulk_handle_digest_email([cordelia.id, prospero.id], cutoff)self.assertEqual(get_recent_topics.cache_info().hits, 7)self.assertEqual(get_recent_topics.cache_info().currsize, 7)# If we use a different cutoff, it clears the cache.- with self.assert_database_query_count(12):+ with self.assert_database_query_count(13):bulk_handle_digest_email([cordelia.id, prospero.id], cutoff + 1)self.assertEqual(get_recent_topics.cache_info().hits, 1)self.assertEqual(get_recent_topics.cache_info().currsize, 4)+ @mock.patch("zerver.lib.digest.enough_traffic", return_value=True)+ @mock.patch("zerver.lib.digest.send_future_email")+ def test_muted_topics_excluded(+ self, mock_send_future_email: mock.MagicMock, mock_enough_traffic: mock.MagicMock+ ) -> None:+ othello = self.example_user("othello")+ iago = self.example_user("iago")+ self.subscribe(othello, "Verona")+ self.subscribe(iago, "Verona")++ one_day_ago = timezone_now() - timedelta(days=1)+ Message.objects.all().update(date_sent=one_day_ago)+ one_hour_ago = timezone_now() - timedelta(seconds=3600)+ cutoff = time.mktime(one_hour_ago.timetuple())++ senders = ["hamlet", "cordelia", "iago", "prospero", "ZOE"]+ self.simulate_stream_conversation("Verona", senders)++ # Othello mutes the topic (matched case-insensitively); it must+ # not be featured in his digest, while other users' digests are+ # unaffected.+ verona = get_stream("Verona", othello.realm)+ do_set_user_topic_visibility_policy(+ othello, verona, "TEST", visibility_policy=UserTopic.VisibilityPolicy.MUTED+ )++ # On a freshly provisioned database the subscription+ # RealmAuditLog rows are newer than the cutoff, so+ # get_user_stream_map would exclude Verona as a just-subscribed+ # stream and both digests would be empty for the wrong reason.+ RealmAuditLog.objects.all().delete()++ get_recent_topics.cache_clear()+ bulk_handle_digest_email([othello.id, iago.id], cutoff)++ self.assertEqual(mock_send_future_email.call_count, 2)+ digests = {+ call_args[1]["to_user_ids"][0]: call_args[1]["context"]["hot_conversations"]+ for call_args in mock_send_future_email.call_args_list+ }+ self.assertEqual(digests[othello.id], [])+ self.assertNotEqual(digests[iago.id], [])+def test_bulk_handle_digest_email_skips_deactivated_users(self) -> None:"""A user id may be added to the queue before the user is deactivated. In such a case,@@ -199,7 +251,7 @@ class TestDigestEmailMessages(ZulipTestCase):# To trigger this, we call the one_click_unsubscribe_link function below.one_click_unsubscribe_link(polonius, "digest")get_recent_topics.cache_clear()- with self.assert_database_query_count(9):+ with self.assert_database_query_count(10):bulk_handle_digest_email([polonius.id], cutoff)self.assertEqual(mock_send_future_email.call_count, 1)@@ -261,7 +313,7 @@ class TestDigestEmailMessages(ZulipTestCase):digest_user_ids = [user.id for user in digest_users]get_recent_topics.cache_clear()- with self.assert_database_query_count(16), self.assert_memcached_count(0):+ with self.assert_database_query_count(17), self.assert_memcached_count(0):bulk_handle_digest_email(digest_user_ids, cutoff)self.assert_length(digest_users, mock_send_future_email.call_count)@@ -608,7 +660,7 @@ class TestDigestEmailMessages(ZulipTestCase):one_click_unsubscribe_link(othello, "digest")# Clear the LRU cache on the stream topicsget_recent_topics.cache_clear()- with self.assert_database_query_count(8):+ with self.assert_database_query_count(9):bulk_handle_digest_email([othello.id], cutoff)self.assertEqual(mock_send_future_email.call_count, 1)@@ -621,7 +673,7 @@ class TestDigestEmailMessages(ZulipTestCase):stream.date_created = timezone_now() - timedelta(days=3)stream.save()- with self.assert_database_query_count(8):+ with self.assert_database_query_count(9):bulk_handle_digest_email([othello.id], cutoff)self.assertEqual(mock_send_future_email.call_count, 2)