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.

events: Merge group-dm with personal recipients.

Alex Vandivercefc7a746f60
diff --git a/zerver/lib/events.py b/zerver/lib/events.py
index 97e308911d5..d058f6096f1 100644
--- a/zerver/lib/events.py
+++ b/zerver/lib/events.py
@@ -45,7 +45,6 @@ from zerver.lib.message import (
apply_unread_message_event,
extract_unread_data_from_um_rows,
get_raw_unread_data,
- get_recent_conversations_recipient_id,
get_recent_private_conversations,
get_starred_message_ids,
remove_message_id_from_unread_mgs,
@@ -821,9 +820,9 @@ def fetch_initial_state_data(
# to self).
#
# Note that raw_recent_private_conversations is an
- # intermediate form as a dictionary keyed by recipient_id,
- # which is more efficient to update, and is rewritten to the
- # final format in post_process_state.
+ # intermediate form as a dictionary keyed by frozenset of
+ # other-user-ids, which is more efficient to update, and is
+ # rewritten to the final format in post_process_state.
state["raw_recent_private_conversations"] = (
{} if user_profile is None else get_recent_private_conversations(user_profile)
)
@@ -1034,19 +1033,13 @@ def apply_event(
if "raw_recent_private_conversations" in state:
# Handle maintaining the recent_private_conversations data structure.
conversations = state["raw_recent_private_conversations"]
- recipient_id = get_recent_conversations_recipient_id(
- user_profile, event["message"]["recipient_id"], event["message"]["sender_id"]
+ userset = frozenset(
+ user_dict["id"]
+ for user_dict in event["message"]["display_recipient"]
+ if user_dict["id"] != user_profile.id
)
- if recipient_id not in conversations:
- conversations[recipient_id] = dict(
- user_ids=sorted(
- user_dict["id"]
- for user_dict in event["message"]["display_recipient"]
- if user_dict["id"] != user_profile.id
- ),
- )
- conversations[recipient_id]["max_message_id"] = event["message"]["id"]
+ conversations[userset] = event["message"]["id"]
return
# Below, we handle maintaining first_message_id.
@@ -2282,10 +2275,8 @@ def post_process_state(
# Reformat recent_private_conversations to be a list of dictionaries, rather than a dict.
ret["recent_private_conversations"] = sorted(
(
- dict(
- **value,
- )
- for (recipient_id, value) in ret["raw_recent_private_conversations"].items()
+ {"user_ids": sorted(user_id_set), "max_message_id": value}
+ for (user_id_set, value) in ret["raw_recent_private_conversations"].items()
),
key=lambda x: -x["max_message_id"],
)
diff --git a/zerver/lib/message.py b/zerver/lib/message.py
index 273fdb87090..e823a7c09d7 100644
--- a/zerver/lib/message.py
+++ b/zerver/lib/message.py
@@ -1,4 +1,5 @@
import re
+from collections import defaultdict
from collections.abc import Callable, Collection, Mapping, Sequence
from dataclasses import dataclass, field
from datetime import datetime, timedelta
@@ -1431,19 +1432,6 @@ def get_last_message_id() -> int:
return last_id
-def get_recent_conversations_recipient_id(
- user_profile: UserProfile, recipient_id: int, sender_id: int
-) -> int:
- """Helper for doing lookups of the recipient_id that
- get_recent_private_conversations would have used to record that
- message in its data structure.
- """
- my_recipient_id = user_profile.recipient_id
- if recipient_id == my_recipient_id:
- return UserProfile.objects.values_list("recipient_id", flat=True).get(id=sender_id)
- return recipient_id
-
-
def _get_recent_conversations_via_legacy_personal_recipient(
user_profile_id: int, recipient_id: int
) -> list[tuple[int, int]]:
@@ -1543,39 +1531,46 @@ def _get_recent_conversations_via_direct_message_group(
)
-def get_recent_private_conversations(user_profile: UserProfile) -> dict[int, dict[str, Any]]:
+def get_recent_private_conversations(user_profile: UserProfile) -> dict[frozenset[int], int]:
"""
We return a dictionary structure for convenient modification
below; this structure is converted into its final form by
post_process.
"""
# Step 1: Collect recent message info
+ direct_recipient_conversations = []
if user_profile.recipient_id is not None:
- recent_conversations = _get_recent_conversations_via_legacy_personal_recipient(
+ direct_recipient_conversations = _get_recent_conversations_via_legacy_personal_recipient(
user_profile.id, user_profile.recipient_id
)
- else:
- recent_conversations = _get_recent_conversations_via_direct_message_group(user_profile.id)
- recipient_map: dict[int, dict[str, Any]] = {
- recipient_id: {"max_message_id": max_message_id, "user_ids": []}
- for recipient_id, max_message_id in recent_conversations
- }
+ recent_conversations = _get_recent_conversations_via_direct_message_group(user_profile.id)
+
+ all_recipients = {recipient_id for recipient_id, _ in direct_recipient_conversations}
+ all_recipients.update(recipient_id for recipient_id, _ in recent_conversations)
# Now we need to map all the recipient_id objects to lists of user IDs
+ recipient_map = defaultdict(list)
subscriptions = (
- Subscription.objects.filter(recipient_id__in=recipient_map.keys())
+ Subscription.objects.filter(recipient_id__in=all_recipients)
.exclude(user_profile_id=user_profile.id)
.values_list("recipient_id", "user_profile_id")
)
for recipient_id, user_profile_id in subscriptions:
- recipient_map[recipient_id]["user_ids"].append(user_profile_id)
-
- # Sort to prevent test flakes and client bugs.
- for rec in recipient_map.values():
- rec["user_ids"].sort()
+ recipient_map[recipient_id].append(user_profile_id)
+
+ # Merge the two sets of conversations
+ merged_conversations: dict[frozenset[int], int] = {}
+ for recipient_id, max_message_id in direct_recipient_conversations + recent_conversations:
+ user_id_set = frozenset(recipient_map[recipient_id])
+ if user_id_set in merged_conversations:
+ merged_conversations[user_id_set] = max(
+ max_message_id, merged_conversations[user_id_set]
+ )
+ else:
+ merged_conversations[user_id_set] = max_message_id
- return recipient_map
+ return merged_conversations
def can_mention_many_users(sender: UserProfile) -> bool:
diff --git a/zerver/tests/test_event_system.py b/zerver/tests/test_event_system.py
index 8796cf5a6f8..76d09c3a12f 100644
--- a/zerver/tests/test_event_system.py
+++ b/zerver/tests/test_event_system.py
@@ -1279,7 +1279,7 @@ class FetchQueriesTest(ZulipTestCase):
self.login_user(user)
with (
- self.assert_database_query_count(48),
+ self.assert_database_query_count(49),
mock.patch("zerver.lib.events.always_want") as want_mock,
):
fetch_initial_state_data(user, realm=user.realm)
@@ -1317,7 +1317,7 @@ class FetchQueriesTest(ZulipTestCase):
realm_user=4,
realm_user_groups=2,
realm_user_settings_defaults=1,
- recent_private_conversations=1,
+ recent_private_conversations=2,
reminders=1,
saved_snippets=1,
scheduled_messages=1,
diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.py
index 9cc8a1c446f..a266755cad0 100644
--- a/zerver/tests/test_home.py
+++ b/zerver/tests/test_home.py
@@ -304,7 +304,7 @@ class HomeTest(ZulipTestCase):
# Verify succeeds once logged-in
with (
- self.assert_database_query_count(58),
+ self.assert_database_query_count(59),
patch("zerver.lib.cache.cache_set") as cache_mock,
):
result = self._get_home_page(stream="Denmark")
@@ -615,7 +615,7 @@ class HomeTest(ZulipTestCase):
# Verify number of queries for Realm admin isn't much higher than for normal users.
self.login("iago")
with (
- self.assert_database_query_count(57),
+ self.assert_database_query_count(58),
patch("zerver.lib.cache.cache_set") as cache_mock,
):
result = self._get_home_page()
@@ -647,7 +647,7 @@ class HomeTest(ZulipTestCase):
self._get_home_page()
# Then for the second page load, measure the number of queries.
- with self.assert_database_query_count(53):
+ with self.assert_database_query_count(54):
result = self._get_home_page()
# Do a sanity check that our new streams were in the payload.
diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.py
index 5f8120babb7..9df4fdbedbb 100644
--- a/zerver/tests/test_message_send.py
+++ b/zerver/tests/test_message_send.py
@@ -873,9 +873,10 @@ class MessagePOSTTest(ZulipTestCase):
message_id = orjson.loads(result.content)["id"]
recent_conversations = get_recent_private_conversations(user_profile)
- [(recipient_id, recent_conversation)] = recent_conversations.items()
- self.assertEqual(set(recent_conversation["user_ids"]), {othello.id})
- self.assertEqual(recent_conversation["max_message_id"], message_id)
+ self.assert_length(recent_conversations, 1)
+ user_id_set = next(iter(recent_conversations))
+ self.assertEqual(user_id_set, {othello.id})
+ self.assertEqual(recent_conversations[user_id_set], message_id)
# Now send a message to yourself and see how that interacts with the data structure
result = self.client_post(
@@ -891,15 +892,10 @@ class MessagePOSTTest(ZulipTestCase):
recent_conversations = get_recent_private_conversations(user_profile)
self.assert_length(recent_conversations, 2)
- recent_conversation = recent_conversations[recipient_id]
- self.assertEqual(set(recent_conversation["user_ids"]), {othello.id})
- self.assertEqual(recent_conversation["max_message_id"], message_id)
+ self.assertEqual(recent_conversations[frozenset([othello.id])], message_id)
# Now verify we have the appropriate self-pm data structure
- del recent_conversations[recipient_id]
- [(recipient_id, recent_conversation)] = recent_conversations.items()
- self.assertEqual(set(recent_conversation["user_ids"]), set())
- self.assertEqual(recent_conversation["max_message_id"], self_message_id)
+ self.assertEqual(recent_conversations[frozenset()], self_message_id)
def test_personal_message_by_id(self) -> None:
"""
@@ -2664,11 +2660,8 @@ class StreamMessagesTest(ZulipTestCase):
self.assert_length(msg_data["huddle_dict"].keys(), 2)
recent_conversations = get_recent_private_conversations(users[1])
- [recent_conversation] = recent_conversations.values()
- self.assertEqual(
- set(recent_conversation["user_ids"]), {user.id for user in users if user != users[1]}
- )
- self.assertEqual(recent_conversation["max_message_id"], message2_id)
+ user_set = frozenset(user.id for user in users if user != users[1])
+ self.assertEqual(recent_conversations[user_set], message2_id)
def test_get_raw_unread_data_for_1_to_1_dms_using_group_direct_message(self) -> None:
sender = self.example_user("hamlet")
@@ -2688,9 +2681,7 @@ class StreamMessagesTest(ZulipTestCase):
self.assertIn(message2_id, msg_data["pm_dict"].keys())
recent_conversations = get_recent_private_conversations(receiver)
- [recent_conversation] = recent_conversations.values()
- self.assertEqual(set(recent_conversation["user_ids"]), {sender.id})
- self.assertEqual(recent_conversation["max_message_id"], message2_id)
+ self.assertEqual(recent_conversations[frozenset([sender.id])], message2_id)
def test_stream_becomes_active_on_message_send(self) -> None:
# Mark a stream as inactive