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.

slack_importer: Fix converting cross-chunk thread messages.

PieterCK9fb884f867b8
diff --git a/zerver/data_import/slack.py b/zerver/data_import/slack.py
index 4c1d0aaf2ec..4d40eebc874 100644
--- a/zerver/data_import/slack.py
+++ b/zerver/data_import/slack.py
@@ -808,12 +808,18 @@ def convert_slack_workspace_messages(
zerver_userprofile,
)
+ thread_reply_counts = count_thread_replies(
+ get_messages_iterator(slack_data_dir, added_channels, added_mpims, added_dms),
+ convert_slack_threads,
+ )
all_messages = get_messages_iterator(slack_data_dir, added_channels, added_mpims, added_dms)
logging.info("######### IMPORTING MESSAGES STARTED #########\n")
total_reactions: list[ZerverFieldsT] = []
total_attachments: list[AttachmentRecordData] = []
total_uploads: list[UploadRecordData] = []
+ thread_counter: dict[str, int] = defaultdict(int)
+ thread_map: dict[str, ThreadMetadata] = {}
dump_file_id = 1
@@ -835,6 +841,9 @@ def convert_slack_workspace_messages(
long_term_idle,
convert_slack_threads,
do_download_and_export_upload_file,
+ thread_counter,
+ thread_map,
+ thread_reply_counts,
)
message_json = dict(
@@ -1005,8 +1014,6 @@ class MessageConversionResult:
@dataclass
class ThreadMetadata:
- first_thread_message_index: int
- thread_length: int
topic_link_syntax: str
topic_name: str
@@ -1050,6 +1057,73 @@ def is_slack_thread_message(convert_slack_threads: bool, message: ZerverFieldsT)
return convert_slack_threads and "thread_ts" in message
+def count_thread_replies(
+ all_messages: Iterator[ZerverFieldsT], convert_slack_threads: bool
+) -> dict[str, int]:
+ """`get_thread_reply_notification` creates, for each thread parent, a
+ cross-linking notification containing the number of thread replies and
+ a thread topic link, which will be appended to the thread parent message.
+ Because messages are converted and written to disk in chunks, a thread's
+ parent and its replies can land in different chunks, so the final reply
+ count isn't known when the parent message is written.
+
+ This pre-scans the whole message stream to count, per thread, how many
+ replies will be imported.
+ """
+ thread_reply_counts: dict[str, int] = defaultdict(int)
+ if not convert_slack_threads:
+ return thread_reply_counts
+
+ for message in all_messages:
+ if not is_slack_thread_message(convert_slack_threads, message):
+ continue
+ if is_message_skipped_during_conversion(message):
+ continue
+
+ # Compute the key on every thread message so the thread parent's
+ # user id is cached in thread_parent_map before its replies (which
+ # may omit parent_user_id) look it up; see get_thread_key.
+ thread_key = get_thread_key(message)
+ if not is_thread_parent_message(message):
+ thread_reply_counts[thread_key] += 1
+
+ return thread_reply_counts
+
+
+def get_thread_reply_notification(
+ convert_slack_threads: bool,
+ message: ZerverFieldsT,
+ thread_map: dict[str, ThreadMetadata],
+ thread_reply_counts: dict[str, int],
+) -> str:
+ """This creates a notification that contains a link to
+ the given message's thread topic.
+
+ e.g "*3 replies in #**channel>2023-05-23 foobar***"
+ """
+ if not is_slack_thread_message(convert_slack_threads, message):
+ return ""
+
+ if not is_thread_parent_message(message):
+ # Only the parent message carries the cross-linking notice.
+ return ""
+
+ thread_key = get_thread_key(message)
+ if thread_key not in thread_map:
+ # This could be a DM or a thread whose parent message wasn't imported.
+ return ""
+
+ number_of_replies = thread_reply_counts.get(thread_key, 0)
+ if number_of_replies < 1:
+ # This could happen if only part of the Slack workspace history was
+ # exported, or if the thread's replies were deleted.
+ return ""
+
+ reply_string = "replies" if number_of_replies > 1 else "reply"
+ # e.g "\n\n*3 replies in #**channel>2023-05-23 foobar***"
+ return f"\n\n*{number_of_replies} {reply_string} in {thread_map[thread_key].topic_link_syntax}*"
+
+
def create_topic_name_for_message(
channel_name: str | None,
content: str,
@@ -1059,7 +1133,6 @@ def create_topic_name_for_message(
recipient_id: int,
thread_counter: dict[str, int],
thread_map: dict[str, ThreadMetadata],
- zerver_message_length: int,
) -> str:
if is_direct_message_type:
return ""
@@ -1076,15 +1149,12 @@ def create_topic_name_for_message(
thread_key = get_thread_key(message)
if is_thread_parent_message(message):
- # Send the thread parent message to the main import topic
- # and add a cross-linking notification message to the thread
- # topic.
+ # Send the thread parent message to the main import topic; the
+ # cross-linking notice to the thread topic is appended by
+ # get_thread_reply_notification.
thread_topic_name = get_zulip_thread_topic_name(content, thread_ts, thread_counter)
thread_map[thread_key] = ThreadMetadata(
- first_thread_message_index=zerver_message_length,
- # Count this message as the first thread message.
- thread_length=1,
topic_link_syntax=get_stream_topic_link_syntax(
recipient_id,
channel_name,
@@ -1097,7 +1167,6 @@ def create_topic_name_for_message(
# For thread replies, send them to the thread topic.
# TODO: Make the first reply in the thread quote the thread message
# in the main topic.
- thread_map[thread_key].thread_length += 1
return thread_map[thread_key].topic_name
else:
# This can occur when the original thread message isn't imported,
@@ -1118,6 +1187,9 @@ def channel_message_to_zerver_message(
long_term_idle: set[int],
convert_slack_threads: bool,
do_download_and_export_upload_file: Callable[[UploadFileRequest], None],
+ thread_counter: dict[str, int],
+ thread_map: dict[str, ThreadMetadata],
+ thread_reply_counts: dict[str, int],
) -> MessageConversionResult:
zerver_message: list[ZerverFieldsT] = []
zerver_usermessage: list[ZerverFieldsT] = []
@@ -1127,8 +1199,6 @@ def channel_message_to_zerver_message(
total_user_messages = 0
total_skipped_user_messages = 0
- thread_counter: dict[str, int] = defaultdict(int)
- thread_map: dict[str, ThreadMetadata] = {}
for message in all_messages:
if is_message_skipped_during_conversion(message):
continue
@@ -1215,7 +1285,10 @@ def channel_message_to_zerver_message(
recipient_id=recipient_id,
thread_counter=thread_counter,
thread_map=thread_map,
- zerver_message_length=len(zerver_message),
+ )
+
+ content += get_thread_reply_notification(
+ convert_slack_threads, message, thread_map, thread_reply_counts
)
zulip_message = build_message(
@@ -1247,24 +1320,6 @@ def channel_message_to_zerver_message(
total_user_messages += num_created
total_skipped_user_messages += num_skipped
- # Link the original thread message to its branched off thread topic
- for thread_metadata in thread_map.values():
- index: int = thread_metadata.first_thread_message_index
- # Subtract the first thread message to get the number of thread replies.
- number_of_replies: int = thread_metadata.thread_length - 1
-
- if number_of_replies < 1:
- continue
-
- thread_topic_link_syntax = thread_metadata.topic_link_syntax
- reply_string = "replies" if number_of_replies > 1 else "reply"
- complete_notification_message = (
- f"\n\n*{number_of_replies} {reply_string} in {thread_topic_link_syntax}*"
- )
- # e.g "3 replies in #**channel>2023-05-23 foobar**"
-
- zerver_message[index]["content"] += complete_notification_message
-
logging.debug(
"Created %s UserMessages; deferred %s due to long-term idle",
total_user_messages,
diff --git a/zerver/tests/test_slack_importer.py b/zerver/tests/test_slack_importer.py
index dfa2b81e0db..b651e21cce3 100644
--- a/zerver/tests/test_slack_importer.py
+++ b/zerver/tests/test_slack_importer.py
@@ -3,6 +3,7 @@ import re
import shutil
import tempfile
import zipfile
+from collections import defaultdict
from collections.abc import Iterator
from io import BytesIO
from types import SimpleNamespace
@@ -48,10 +49,12 @@ from zerver.data_import.slack import (
SlackBotEmail,
SlackBotNotFoundError,
SlackTokenValidationError,
+ ThreadMetadata,
channel_message_to_zerver_message,
channels_to_zerver_stream,
check_slack_token_access,
convert_slack_workspace_messages,
+ count_thread_replies,
do_convert_zipfile,
fetch_shared_channel_users,
get_admin,
@@ -195,7 +198,7 @@ def slack_import_integrity_error(constraint_name: str) -> IntegrityError:
class SlackImporter(ZulipTestCase):
def run_channel_message_to_zerver_message_with_fixtures(
- self, fixture_names: list[str], **kwargs: dict[str, Any]
+ self, fixture_names: list[str], **kwargs: Any
) -> MessageConversionResult:
"""
This is a wrapper for `channel_message_to_zerver_message`, it
@@ -224,13 +227,17 @@ class SlackImporter(ZulipTestCase):
},
)
- all_messages = []
- for filename in fixture_names:
- all_messages.extend(
- orjson.loads(
- self.fixture_data(f"{filename}.json", type=slack_message_fixture_directory)
+ all_messages: list[dict[str, Any]]
+ if "all_messages" in kwargs:
+ all_messages = kwargs["all_messages"]
+ else:
+ all_messages = []
+ for filename in fixture_names:
+ all_messages.extend(
+ orjson.loads(
+ self.fixture_data(f"{filename}.json", type=slack_message_fixture_directory)
+ )
)
- )
added_channels: dict[str, tuple[str, int]] = kwargs.get(
"added_channels", {"random": ("c5", 1), "general": ("c6", 2)}
@@ -239,6 +246,17 @@ class SlackImporter(ZulipTestCase):
convert_slack_threads = kwargs.get("convert_slack_threads", True)
assert isinstance(convert_slack_threads, bool)
+ thread_counter: dict[str, int] = kwargs.get("thread_counter", defaultdict(int))
+ thread_map: dict[str, ThreadMetadata] = kwargs.get("thread_map", {})
+ # Callers exercising cross-chunk threads pass the counts computed over the
+ # whole conversation; otherwise derive them from this call's messages.
+
+ thread_reply_counts: dict[str, int]
+ if "thread_reply_counts" in kwargs:
+ thread_reply_counts = kwargs["thread_reply_counts"]
+ else:
+ thread_reply_counts = count_thread_replies(iter(all_messages), convert_slack_threads)
+
with mock.patch("zerver.data_import.slack.build_usermessages", return_value=(2, 4)):
return channel_message_to_zerver_message(
realm_id=1,
@@ -253,6 +271,9 @@ class SlackImporter(ZulipTestCase):
long_term_idle=set(),
convert_slack_threads=convert_slack_threads,
do_download_and_export_upload_file=lambda request: None,
+ thread_counter=thread_counter,
+ thread_map=thread_map,
+ thread_reply_counts=thread_reply_counts,
)
@responses.activate
@@ -1375,6 +1396,9 @@ class SlackImporter(ZulipTestCase):
set(),
convert_slack_threads=False,
do_download_and_export_upload_file=lambda request: None,
+ thread_counter=defaultdict(int),
+ thread_map={},
+ thread_reply_counts=count_thread_replies(iter(all_messages), False),
)
zerver_message = conversion_result.zerver_message
@@ -1535,6 +1559,105 @@ class SlackImporter(ZulipTestCase):
self.assertEqual(zerver_message[2]["content"], expected_thread_2_message_2_content)
self.assertEqual(zerver_message[2][EXPORT_TOPIC_NAME], expected_thread_2_topic_name)
+ def test_thread_cross_link_across_chunk_boundary(self) -> None:
+ # A thread's parent message and its replies are not necessarily
+ # converted in the same chunk (see convert_slack_workspace_messages).
+ # The parent must still be cross-linked with the correct reply count,
+ # which is why count_thread_replies pre-scans the whole conversation.
+ slack_recipient_name_to_zulip_recipient_id = {"random": 2, "general": 1}
+ thread_messages = orjson.loads(
+ self.fixture_data(
+ "normal_thread.json", type="slack_fixtures/exported_messages_fixtures"
+ )
+ )
+ parent_message, reply_message = thread_messages[0], thread_messages[1]
+
+ # thread_counter, thread_map, and the reply counts persist across the
+ # per-chunk calls, exactly as in convert_slack_workspace_messages.
+ thread_counter: dict[str, int] = defaultdict(int)
+ thread_map: dict[str, ThreadMetadata] = {}
+ thread_reply_counts = count_thread_replies(
+ iter([parent_message, reply_message]), convert_slack_threads=True
+ )
+
+ # First chunk holds only the parent; the reply arrives in the second.
+ first_chunk = self.run_channel_message_to_zerver_message_with_fixtures(
+ [],
+ all_messages=[parent_message],
+ slack_recipient_name_to_zulip_recipient_id=slack_recipient_name_to_zulip_recipient_id,
+ thread_counter=thread_counter,
+ thread_map=thread_map,
+ thread_reply_counts=thread_reply_counts,
+ )
+ second_chunk = self.run_channel_message_to_zerver_message_with_fixtures(
+ [],
+ all_messages=[reply_message],
+ slack_recipient_name_to_zulip_recipient_id=slack_recipient_name_to_zulip_recipient_id,
+ thread_counter=thread_counter,
+ thread_map=thread_map,
+ thread_reply_counts=thread_reply_counts,
+ )
+
+ expected_thread_topic_name = "2015-06-12 message body text"
+ thread_topic_link_syntax = get_stream_topic_link_syntax(
+ slack_recipient_name_to_zulip_recipient_id["random"],
+ "random",
+ expected_thread_topic_name,
+ )
+ expected_parent_content = f"""
+message body text
+
+*1 reply in {thread_topic_link_syntax}*
+""".strip()
+
+ # The parent, converted in the first chunk, is cross-linked with the
+ # reply that is only converted in the second chunk.
+ self.assert_length(first_chunk.zerver_message, 1)
+ self.assertEqual(first_chunk.zerver_message[0]["content"], expected_parent_content)
+ self.assertEqual(first_chunk.zerver_message[0][EXPORT_TOPIC_NAME], MAIN_SLACK_IMPORT_TOPIC)
+
+ # The reply, converted in the second chunk, is routed to the thread topic.
+ self.assert_length(second_chunk.zerver_message, 1)
+ self.assertEqual(second_chunk.zerver_message[0]["content"], "random")
+ self.assertEqual(
+ second_chunk.zerver_message[0][EXPORT_TOPIC_NAME], expected_thread_topic_name
+ )
+
+ def test_thread_cross_link_skipped_for_direct_messages(self) -> None:
+ # Direct-message threads aren't split into per-thread topics, so a
+ # DM thread's parent must not get a cross-linking notice (and looking
+ # one up must not raise, since no thread topic is recorded for it).
+ slack_recipient_name_to_zulip_recipient_id = {"random": 2, "general": 1, "dm": 3}
+ dm_thread = [
+ {
+ "text": "dm thread parent",
+ "user": "U061A5N1G",
+ "ts": "1434139102.000002",
+ "thread_ts": "1434139102.000002",
+ "pm_name": "dm",
+ },
+ {
+ "text": "dm thread reply",
+ "user": "U061A5N1G",
+ "ts": "1439868294.000007",
+ "parent_user_id": "U061A5N1G",
+ "thread_ts": "1434139102.000002",
+ "pm_name": "dm",
+ },
+ ]
+ conversion_result = self.run_channel_message_to_zerver_message_with_fixtures(
+ [],
+ all_messages=dm_thread,
+ slack_recipient_name_to_zulip_recipient_id=slack_recipient_name_to_zulip_recipient_id,
+ )
+
+ self.assert_length(conversion_result.zerver_message, 2)
+ # The content is unannotated and both messages use the DM topic.
+ self.assertEqual(conversion_result.zerver_message[0]["content"], "dm thread parent")
+ self.assertEqual(conversion_result.zerver_message[0][EXPORT_TOPIC_NAME], Message.DM_TOPIC)
+ self.assertEqual(conversion_result.zerver_message[1]["content"], "dm thread reply")
+ self.assertEqual(conversion_result.zerver_message[1][EXPORT_TOPIC_NAME], Message.DM_TOPIC)
+
def test_convert_thread_topic_name_cut_off(self) -> None:
slack_recipient_name_to_zulip_recipient_id = {
"random": 2,
@@ -1980,6 +2103,9 @@ class SlackImporter(ZulipTestCase):
set(),
convert_slack_threads=True,
do_download_and_export_upload_file=lambda request: None,
+ thread_counter=defaultdict(int),
+ thread_map={},
+ thread_reply_counts=count_thread_replies(iter(all_messages), True),
)
zerver_message = conversion_result.zerver_message