Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
slack_importer: Add cross-linking message for Slack thread.
PieterCK5f962e3d3294
diff --git a/zerver/data_import/slack.py b/zerver/data_import/slack.pyindex 941d22294e6..9ac51387bf4 100644--- a/zerver/data_import/slack.py+++ b/zerver/data_import/slack.py@@ -63,6 +63,7 @@ from zerver.lib.parallel import run_parallel_queuefrom zerver.lib.partial import partialfrom zerver.lib.storage import static_pathfrom zerver.lib.thumbnail import THUMBNAIL_ACCEPT_IMAGE_TYPES, resize_realm_icon+from zerver.lib.topic_link_util import get_stream_topic_link_syntaxfrom zerver.lib.validator import to_wild_valuefrom zerver.models import (CustomProfileField,@@ -999,6 +1000,86 @@ class MessageConversionResult:reaction_list: list[ZerverFieldsT]+@dataclass+class ThreadMetadata:+ first_thread_message_index: int+ thread_length: int+ topic_link_syntax: str+ topic_name: str+++MAIN_SLACK_IMPORT_TOPIC = "imported from Slack"+++def get_thread_key(message: ZerverFieldsT) -> str:+ thread_ts = datetime.fromtimestamp(float(message["thread_ts"]), tz=timezone.utc)+ thread_ts_str = thread_ts.strftime(r"%Y/%m/%d %H:%M:%S")+ subtype = message.get("subtype", False)+ parent_user_id = get_parent_user_id_from_thread_message(message, subtype)+ return f"{thread_ts_str}-{parent_user_id}"+++def is_slack_thread_message(convert_slack_threads: bool, message: ZerverFieldsT) -> bool:+ return convert_slack_threads and "thread_ts" in message+++def create_topic_name_for_message(+ channel_name: str | None,+ content: str,+ convert_slack_threads: bool,+ is_direct_message_type: bool,+ message: ZerverFieldsT,+ recipient_id: int,+ thread_counter: dict[str, int],+ thread_map: dict[str, ThreadMetadata],+ zerver_message_length: int,+) -> str:+ if is_direct_message_type:+ return ""++ assert channel_name is not None++ # Slack's unthreaded messages go into a single topic, while+ # threaded messages are put into separate thread topics.+ if not is_slack_thread_message(convert_slack_threads, message):+ return MAIN_SLACK_IMPORT_TOPIC++ thread_ts = datetime.fromtimestamp(float(message["thread_ts"]), tz=timezone.utc)+ message_ts = datetime.fromtimestamp(float(message["ts"]), tz=timezone.utc)+ thread_ts_str = thread_ts.strftime(r"%Y/%m/%d %H:%M:%S")+ thread_key = get_thread_key(message)++ if thread_ts == message_ts:+ # The first thread message has a `thread_ts` that matches its+ # `message_ts`. Send this message to the main import topic+ # and add a cross-linking notification message to the thread+ # topic.+ 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,+ thread_topic_name,+ ),+ topic_name=thread_topic_name,+ )+ return MAIN_SLACK_IMPORT_TOPIC+ elif thread_key in thread_map:+ # 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,+ # such as when only a slice of the chat history is imported.+ return f"{thread_ts_str} No channel message"++def channel_message_to_zerver_message(realm_id: int,users: list[ZerverFieldsT],@@ -1013,7 +1094,7 @@ def channel_message_to_zerver_message(convert_slack_threads: bool,do_download_and_export_upload_file: Callable[[UploadFileRequest], None],) -> MessageConversionResult:- zerver_message = []+ zerver_message: list[ZerverFieldsT] = []zerver_usermessage: list[ZerverFieldsT] = []uploads_list: list[UploadRecordData] = []zerver_attachment: list[ZerverFieldsT] = []@@ -1022,7 +1103,7 @@ def channel_message_to_zerver_message(total_user_messages = 0total_skipped_user_messages = 0thread_counter: dict[str, int] = defaultdict(int)- thread_map: dict[str, str] = {}+ thread_map: dict[str, ThreadMetadata] = {}for message in all_messages:slack_user_id = get_message_sending_user(message)if not slack_user_id:@@ -1056,9 +1137,11 @@ def channel_message_to_zerver_message(continuerendered_content = None+ channel_name: str | None = Noneif "channel_name" in message:is_direct_message_type = Falserecipient_id = slack_recipient_name_to_zulip_recipient_id[message["channel_name"]]+ channel_name = message["channel_name"]elif "mpim_name" in message:is_direct_message_type = Truerecipient_id = slack_recipient_name_to_zulip_recipient_id[message["mpim_name"]]@@ -1109,25 +1192,17 @@ def channel_message_to_zerver_message(has_attachment = file_info["has_attachment"]has_image = file_info["has_image"]- # Slack's unthreaded messages go into a single topic, while- # threads each generate a unique topic labeled by the date,- # a snippet of the original message and a counter if there- # are any thread with the same topic name- topic_name = "imported from Slack"- if convert_slack_threads and not is_direct_message_type and "thread_ts" in message:- thread_ts = datetime.fromtimestamp(float(message["thread_ts"]), tz=timezone.utc)- thread_ts_str = thread_ts.strftime(r"%Y/%m/%d %H:%M:%S")- parent_user_id = get_parent_user_id_from_thread_message(message, subtype)- thread_key = f"{thread_ts_str}-{parent_user_id}"-- if thread_key in thread_map:- topic_name = thread_map[thread_key]- else:- topic_name = get_zulip_thread_topic_name(content, thread_ts, thread_counter)- thread_map[thread_key] = topic_name-- if is_direct_message_type:- topic_name = ""+ topic_name = create_topic_name_for_message(+ channel_name=channel_name,+ content=content,+ convert_slack_threads=convert_slack_threads,+ is_direct_message_type=is_direct_message_type,+ message=message,+ recipient_id=recipient_id,+ thread_counter=thread_counter,+ thread_map=thread_map,+ zerver_message_length=len(zerver_message),+ )zulip_message = build_message(topic_name=topic_name,@@ -1158,6 +1233,24 @@ def channel_message_to_zerver_message(total_user_messages += num_createdtotal_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.pyindex c94d5f44e5c..6c8fd070e36 100644--- a/zerver/tests/test_slack_importer.py+++ b/zerver/tests/test_slack_importer.py@@ -35,6 +35,7 @@ from zerver.data_import.import_util import ()from zerver.data_import.sequencer import NEXT_IDfrom zerver.data_import.slack import (+ MAIN_SLACK_IMPORT_TOPIC,SLACK_IMPORT_TOKEN_SCOPES,AddedChannelsT,AddedDMsT,@@ -67,6 +68,7 @@ from zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.test_helpers import find_key_by_email, read_test_image_filefrom zerver.lib.thumbnail import THUMBNAIL_ACCEPT_IMAGE_TYPES, BadImageErrorfrom zerver.lib.topic import EXPORT_TOPIC_NAME+from zerver.lib.topic_link_util import get_stream_topic_link_syntaxfrom zerver.models import Message, PreregistrationRealm, Realm, RealmAuditLog, UserProfilefrom zerver.models.realm_audit_logs import AuditLogEventTypefrom zerver.models.realms import get_realm@@ -1462,10 +1464,20 @@ class SlackImporter(ZulipTestCase):### THREAD 1 CONVERSATION #### Test thread topic name contains message snippet- expected_thread_1_message_1_content = "message body text"expected_thread_1_topic_name = "2015-06-12 message body text"+ thread_1_topic_link_syntax = get_stream_topic_link_syntax(+ slack_recipient_name_to_zulip_recipient_id["random"],+ "random",+ expected_thread_1_topic_name,+ )+ original_thread_1_message_1_content = "message body text"+ expected_thread_1_message_1_content = f"""+{original_thread_1_message_1_content}++*1 reply in {thread_1_topic_link_syntax}*+""".strip()self.assertEqual(zerver_message[1]["content"], expected_thread_1_message_1_content)- self.assertEqual(zerver_message[1][EXPORT_TOPIC_NAME], expected_thread_1_topic_name)+ self.assertEqual(zerver_message[1][EXPORT_TOPIC_NAME], MAIN_SLACK_IMPORT_TOPIC)# Thread reply is in the correct thread topicexpected_thread_1_message_2_content = "random"@@ -1474,10 +1486,21 @@ class SlackImporter(ZulipTestCase):### THREAD 2 CONVERSATION #### Test thread topic name contains message snippet- expected_thread_2_message_1_content = "message body text"expected_thread_2_topic_name = "2015-06-12 message body text"+ thread_2_topic_link_syntax = get_stream_topic_link_syntax(+ slack_recipient_name_to_zulip_recipient_id["random"],+ "random",+ expected_thread_2_topic_name,+ )+ original_thread_2_message_1_content = "message body text"+ expected_thread_2_message_1_content = f"""+{original_thread_2_message_1_content}++*1 reply in {thread_2_topic_link_syntax}*+""".strip()+self.assertEqual(zerver_message[1]["content"], expected_thread_2_message_1_content)- self.assertEqual(zerver_message[1][EXPORT_TOPIC_NAME], expected_thread_2_topic_name)+ self.assertEqual(zerver_message[1][EXPORT_TOPIC_NAME], MAIN_SLACK_IMPORT_TOPIC)# Thread reply is in the correct thread topicexpected_thread_2_message_2_content = "random"@@ -1485,74 +1508,128 @@ class SlackImporter(ZulipTestCase):self.assertEqual(zerver_message[2][EXPORT_TOPIC_NAME], expected_thread_2_topic_name)def test_convert_thread_topic_name_cut_off(self) -> None:+ slack_recipient_name_to_zulip_recipient_id = {+ "random": 2,+ "general": 1,+ }conversion_result = self.run_channel_message_to_zerver_message_with_fixtures(["thread_with_long_topic_name"],+ slack_recipient_name_to_zulip_recipient_id=slack_recipient_name_to_zulip_recipient_id,)zerver_message = conversion_result.zerver_messageself.assert_length(zerver_message, 4)# Test thread topic name cut off.- expected_thread_1_message_1_content = (- "random message but it is too long for the thread topic name"- )expected_thread_1_topic_name = ("2015-08-18 random message but it is too long for the thread…")+ thread_1_topic_link_syntax = get_stream_topic_link_syntax(+ slack_recipient_name_to_zulip_recipient_id["random"],+ "random",+ expected_thread_1_topic_name,+ )+ original_thread_1_message_1_content = (+ "random message but it is too long for the thread topic name"+ )+ expected_thread_1_message_1_content = f"""+{original_thread_1_message_1_content}++*1 reply in {thread_1_topic_link_syntax}*+""".strip()+self.assertEqual(zerver_message[0]["content"], expected_thread_1_message_1_content)- self.assertEqual(zerver_message[0][EXPORT_TOPIC_NAME], expected_thread_1_topic_name)+ self.assertEqual(zerver_message[0][EXPORT_TOPIC_NAME], MAIN_SLACK_IMPORT_TOPIC)# Record that truncation should use the full maximum topic length.- self.assert_length(zerver_message[0][EXPORT_TOPIC_NAME], 60)+ expected_thread_1_topic_name = (+ "2015-08-18 random message but it is too long for the thread…"+ )+ self.assertEqual(zerver_message[1][EXPORT_TOPIC_NAME], expected_thread_1_topic_name)+ self.assert_length(zerver_message[1][EXPORT_TOPIC_NAME], 60)### THREAD 2 CONVERSATION ###+ self.assertEqual(zerver_message[2][EXPORT_TOPIC_NAME], MAIN_SLACK_IMPORT_TOPIC)# Test that two different thread topics, despite having unique# original topic names, will collide if their truncated names# are identical.expected_thread_2_topic_name = ("2015-08-18 random message but it is too long for the th… (2)")- self.assertEqual(zerver_message[2][EXPORT_TOPIC_NAME], expected_thread_2_topic_name)- # Record that truncation should use the full maximum topic length.- self.assert_length(zerver_message[2][EXPORT_TOPIC_NAME], 60)+ self.assertEqual(zerver_message[3][EXPORT_TOPIC_NAME], expected_thread_2_topic_name)+ self.assert_length(zerver_message[3][EXPORT_TOPIC_NAME], 60)def test_convert_colliding_thread_topic_names(self) -> None:+ slack_recipient_name_to_zulip_recipient_id = {+ "random": 2,+ "general": 1,+ }conversion_result = self.run_channel_message_to_zerver_message_with_fixtures(["threads_with_colliding_topic_names"],+ slack_recipient_name_to_zulip_recipient_id=slack_recipient_name_to_zulip_recipient_id,)zerver_message = conversion_result.zerver_messageself.assert_length(zerver_message, 6)### THREAD 1 CONVERSATION ###- expected_thread_1_message_1_content = "message body text"expected_thread_1_topic_name = "2015-06-12 message body text"+ thread_1_topic_link_syntax = get_stream_topic_link_syntax(+ slack_recipient_name_to_zulip_recipient_id["random"],+ "random",+ expected_thread_1_topic_name,+ )+ original_thread_1_message_1_content = "message body text"+ expected_thread_1_message_1_content = f"""+{original_thread_1_message_1_content}++*1 reply in {thread_1_topic_link_syntax}*+""".strip()self.assertEqual(zerver_message[0]["content"], expected_thread_1_message_1_content)- self.assertEqual(zerver_message[0][EXPORT_TOPIC_NAME], expected_thread_1_topic_name)+ self.assertEqual(zerver_message[0][EXPORT_TOPIC_NAME], MAIN_SLACK_IMPORT_TOPIC)+ self.assertEqual(zerver_message[1][EXPORT_TOPIC_NAME], expected_thread_1_topic_name)### THREAD 2 CONVERSATION #### Test thread topic name collision.expected_thread_2_topic_name = "2015-06-12 message body text (2)"- self.assertEqual(zerver_message[2][EXPORT_TOPIC_NAME], expected_thread_2_topic_name)+ self.assertEqual(zerver_message[2][EXPORT_TOPIC_NAME], MAIN_SLACK_IMPORT_TOPIC)+ self.assertEqual(zerver_message[3][EXPORT_TOPIC_NAME], expected_thread_2_topic_name)### THREAD 3 CONVERSATION #### Test two thread topic names with the same message# snippet don't collide if they're on different days.expected_thread_3_topic_name = "1974-07-27 message body text"- self.assertEqual(zerver_message[4][EXPORT_TOPIC_NAME], expected_thread_3_topic_name)+ self.assertEqual(zerver_message[4][EXPORT_TOPIC_NAME], MAIN_SLACK_IMPORT_TOPIC)+ self.assertEqual(zerver_message[5][EXPORT_TOPIC_NAME], expected_thread_3_topic_name)def test_convert_thread_topic_name_with_mention_syntax(self) -> None:+ slack_recipient_name_to_zulip_recipient_id = {+ "random": 2,+ "general": 1,+ }conversion_result = self.run_channel_message_to_zerver_message_with_fixtures(["thread_with_mention_syntax_in_topic_name"],+ slack_recipient_name_to_zulip_recipient_id=slack_recipient_name_to_zulip_recipient_id,)zerver_message = conversion_result.zerver_messageself.assert_length(zerver_message, 2)# Test mention syntax in thread topic name.- expected_thread_message_1_content = "@**Jon** please reply to this message"expected_thread_topic_name = "2015-07-17 @**Jon** please reply to this message"+ thread_1_topic_link_syntax = get_stream_topic_link_syntax(+ slack_recipient_name_to_zulip_recipient_id["random"],+ "random",+ expected_thread_topic_name,+ )+ original_thread_message_1_content = "@**Jon** please reply to this message"+ expected_thread_message_1_content = f"""+{original_thread_message_1_content}++*1 reply in {thread_1_topic_link_syntax}*+""".strip()self.assertEqual(zerver_message[0]["content"], expected_thread_message_1_content)- self.assertEqual(zerver_message[0][EXPORT_TOPIC_NAME], expected_thread_topic_name)+ self.assertEqual(zerver_message[0][EXPORT_TOPIC_NAME], MAIN_SLACK_IMPORT_TOPIC)+ self.assertEqual(zerver_message[1][EXPORT_TOPIC_NAME], expected_thread_topic_name)def test_convert_thread_topic_name_with_file_link_formatting(self) -> None:conversion_result = self.run_channel_message_to_zerver_message_with_fixtures(@@ -1568,21 +1645,41 @@ class SlackImporter(ZulipTestCase):expected_thread_message_1_content = "Look!\n[Apple](/user_uploads/"expected_thread_topic_name = "2018-09-16 Look!\n[Apple](/user_uploads/"self.assertTrue(zerver_message[0]["content"].startswith(expected_thread_message_1_content))- self.assertTrue(zerver_message[0][EXPORT_TOPIC_NAME].startswith(expected_thread_topic_name))+ self.assertEqual(zerver_message[0][EXPORT_TOPIC_NAME], MAIN_SLACK_IMPORT_TOPIC)+ self.assertTrue(zerver_message[1][EXPORT_TOPIC_NAME].startswith(expected_thread_topic_name))def test_convert_thread_topic_name_with_text_formattings(self) -> None:+ slack_recipient_name_to_zulip_recipient_id = {+ "random": 2,+ "general": 1,+ }conversion_result = self.run_channel_message_to_zerver_message_with_fixtures(["thread_with_text_formattings_in_topic_name"],+ slack_recipient_name_to_zulip_recipient_id=slack_recipient_name_to_zulip_recipient_id,)zerver_message = conversion_result.zerver_messageself.assert_length(zerver_message, 2)- # Test various formatting syntaxes in thread topic name.- expected_thread_message_1_content = "**foo** *bar* ~~baz~~ [qux](https://chat.zulip.org)"- expected_thread_topic_name = "2019-01-10 **foo** *bar* ~~baz~~ [qux](https://chat.zulip.o…"++ expected_thread_1_topic_name = (+ "2019-01-10 **foo** *bar* ~~baz~~ [qux](https://chat.zulip.o…"+ )+ thread_1_topic_link_syntax = get_stream_topic_link_syntax(+ slack_recipient_name_to_zulip_recipient_id["random"],+ "random",+ expected_thread_1_topic_name,+ )+ original_thread_message_1_content = "**foo** *bar* ~~baz~~ [qux](https://chat.zulip.org)"+ expected_thread_message_1_content = f"""+{original_thread_message_1_content}++*1 reply in {thread_1_topic_link_syntax}*+""".strip()+self.assertEqual(zerver_message[0]["content"], expected_thread_message_1_content)- self.assertEqual(zerver_message[0][EXPORT_TOPIC_NAME], expected_thread_topic_name)+ self.assertEqual(zerver_message[0][EXPORT_TOPIC_NAME], MAIN_SLACK_IMPORT_TOPIC)+ self.assertEqual(zerver_message[1][EXPORT_TOPIC_NAME], expected_thread_1_topic_name)@mock.patch("zerver.data_import.slack.build_usermessages", return_value=(2, 4))def test_channel_message_to_zerver_message_with_integration_bots(