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_converter: Further reduce rich_text related conversion loss.

PieterCK13b4274412b6
diff --git a/zerver/data_import/slack_message_conversion.py b/zerver/data_import/slack_message_conversion.py
index cc162eb5923..99785befe49 100644
--- a/zerver/data_import/slack_message_conversion.py
+++ b/zerver/data_import/slack_message_conversion.py
@@ -1,3 +1,4 @@
+import contextlib
import re
from datetime import datetime, timezone
from itertools import zip_longest
@@ -253,7 +254,14 @@ def convert_to_zulip_markdown(
return text, mentioned_users_id, message_has_link
+class LossyConversionError(Exception):
+ pass
+
+
def render_block(block: WildValue) -> str:
+ """
+ Raises `LossyConversionError` if it's a rich_text block type.
+ """
# https://api.slack.com/reference/block-kit/blocks
supported_types = {
"context",
@@ -283,18 +291,18 @@ def render_block(block: WildValue) -> str:
known_types = {
*supported_types,
*unhandled_types,
- # All user-sent messages contain at least a "block" component with a
- # "rich_text" block. This block contains the same string as the "text"
- # field. We're skipping this because the Slack import tool already
- # handles the "text" field and the Slack incoming integration
- # overrides it.
- # https://docs.slack.dev/reference/block-kit/blocks/rich-text-block/
+ # rich_text is a special case. It probably composes the bulk of a message
+ # body since it's responsible for very basic text formatting--such as
+ # plain text, bold, italic, etc. Our current Slack text conversion module
+ # can't process this block since this is not formatted in Markdown.
"rich_text",
}
block_type = block["type"].tame(check_string_in(known_types))
if block_type in unhandled_types:
return ""
+ elif block_type == "rich_text":
+ raise LossyConversionError
elif block_type == "context" and block.get("elements"):
pieces = []
# Slack renders these pieces left-to-right, packed in as
@@ -425,7 +433,14 @@ def render_attachment(attachment: WildValue) -> str:
fields.append(f"{value}")
pieces.append("\n".join(fields))
if attachment.get("blocks"):
- pieces += map(render_block, attachment["blocks"])
+ for block in attachment["blocks"]:
+ # rich_text blocks in "attachments" elements don't have a
+ # corresponding raw value in the "text" field, so we can't
+ # fallback to the "text" field in this case like we can do
+ # with rich_text in message "blocks".
+ # TODO: We should use the raw rich_text strings instead.
+ with contextlib.suppress(LossyConversionError): # nocoverage
+ pieces.append(render_block(block))
if image_url_wv := attachment.get("image_url"):
try:
image_url = image_url_wv.tame(check_url)
@@ -465,7 +480,13 @@ def process_slack_block_and_attachment(message: WildValue) -> str:
raw_text = message["text"].tame(check_string)
if message.get("blocks"):
- pieces += map(render_block, message["blocks"])
+ try:
+ pieces += map(render_block, message["blocks"])
+ except LossyConversionError:
+ # render_block doesn't yet handle the "rich_text" block, which is used
+ # for very basic text formatting. To avoid message content loss, process
+ # the message["text"] field instead if rich_text is used.
+ pieces.append(raw_text)
if set(pieces) in ({""}, set()):
pieces.append(raw_text)
diff --git a/zerver/tests/test_slack_importer.py b/zerver/tests/test_slack_importer.py
index 18386a0bcec..4f658fe9638 100644
--- a/zerver/tests/test_slack_importer.py
+++ b/zerver/tests/test_slack_importer.py
@@ -2124,6 +2124,104 @@ class SlackImporter(ZulipTestCase):
"app_id": "A3G4A68V9",
"channel_name": "general",
},
+ {
+ "subtype": "bot_message",
+ "text": "`render_block` will delete me, help!\nHello, `render_block` recognizes me.",
+ "username": "ClickUp",
+ "attachments": [
+ {
+ "id": 1,
+ "blocks": [
+ {
+ "type": "section",
+ "block_id": "bZ4XB",
+ "text": {
+ "type": "mrkdwn",
+ "text": "*<https://app.clickup.com/t/25567147/86cw30wf2|asd>*",
+ "verbatim": False,
+ },
+ },
+ {
+ "type": "context",
+ "block_id": "TEfLM",
+ "elements": [
+ {
+ "type": "image",
+ "image_url": "https://search.clickup-au.com/media/app-icons/clickup/logo_alpha.png",
+ "alt_text": "Cookie / The Goodiest of Cstdddddsdd / dds",
+ },
+ {"type": "mrkdwn", "text": "in dds", "verbatim": False},
+ {
+ "type": "image",
+ "image_url": "https://search.clickup-au.com/media/app-icons/clickup/status.png",
+ "alt_text": "Status",
+ },
+ {"type": "mrkdwn", "text": "To Do", "verbatim": False},
+ ],
+ },
+ {
+ "type": "actions",
+ "block_id": "cg8fg",
+ "elements": [
+ {
+ "type": "button",
+ "action_id": "NOOP",
+ "text": {
+ "type": "plain_text",
+ "text": "View task",
+ "emoji": False,
+ },
+ "url": "https://app.clickup.com/t/25567147/86cw30wf2",
+ },
+ {
+ "type": "button",
+ "action_id": "EDIT_TASK_ACTION",
+ "text": {
+ "type": "plain_text",
+ "text": "Edit task",
+ "emoji": False,
+ },
+ "value": '{"taskID":"86cw30wf2","teamID":"25567147","taskUrl":"https://app.clickup.com/t/25567147/86cw30wf2"}',
+ },
+ ],
+ },
+ ],
+ "color": "#656f7d",
+ "fallback": "[no preview available]",
+ }
+ ],
+ "type": "message",
+ "ts": "1723609070.703489",
+ "bot_id": "B06NWMNUQ3W",
+ "app_id": "A3G4A68V9",
+ "blocks": [
+ {
+ "type": "rich_text",
+ "elements": [
+ {
+ "type": "rich_text_section",
+ "elements": [
+ {
+ "type": "text",
+ "text": "`render_block` will delete me, help!",
+ }
+ ],
+ }
+ ],
+ },
+ {
+ "type": "section",
+ "text": {
+ "type": "plain_text",
+ "text": "Hello, `render_block` recognizes me.",
+ "emoji": True,
+ },
+ },
+ ],
+ "channel": "C06P6T3QGD7",
+ "event_ts": "1723609070.703489",
+ "channel_type": "channel",
+ },
]
slack_recipient_name_to_zulip_recipient_id = {
@@ -2160,7 +2258,7 @@ class SlackImporter(ZulipTestCase):
# functioning already tested in helper function
self.assertEqual(zerver_usermessage, [])
# subtype: channel_join is filtered
- self.assert_length(zerver_message, 4)
+ self.assert_length(zerver_message, 5)
self.assertEqual(uploads, [])
self.assertEqual(attachment, [])
@@ -2207,6 +2305,22 @@ by Pieter
self.assertEqual(zerver_message[3]["content"], expected_message_block_3)
self.assertEqual(zerver_message[3]["sender"], slack_user_id_to_zulip_user_id["B06NWMNUQ3W"])
+ expected_message_block_4 = """
+`render_block` will delete me, help!
+Hello, `render_block` recognizes me.
+**[asd](https://app.clickup.com/t/25567147/86cw30wf2)**
+
+[Cookie / The Goodiest of Cstdddddsdd / dds](https://search.clickup-au.com/media/app-icons/clickup/logo_alpha.png)
+
+in dds
+
+[Status](https://search.clickup-au.com/media/app-icons/clickup/status.png)
+
+To Do
+""".strip()
+ self.assertEqual(zerver_message[4]["content"], expected_message_block_4)
+ self.assertEqual(zerver_message[4]["sender"], slack_user_id_to_zulip_user_id["B06NWMNUQ3W"])
+
@mock.patch("zerver.data_import.slack.channel_message_to_zerver_message")
@mock.patch("zerver.data_import.slack.get_messages_iterator")
def test_convert_slack_workspace_messages(
diff --git a/zerver/webhooks/slack_incoming/view.py b/zerver/webhooks/slack_incoming/view.py
index 5fb3099f5b8..9953ca3af34 100644
--- a/zerver/webhooks/slack_incoming/view.py
+++ b/zerver/webhooks/slack_incoming/view.py
@@ -9,6 +9,7 @@ from django.utils.translation import gettext as _
from typing_extensions import ParamSpec
from zerver.data_import.slack_message_conversion import (
+ LossyConversionError,
convert_slack_formatting,
render_attachment,
render_block,
@@ -84,7 +85,10 @@ def api_slack_incoming_webhook(
pieces: list[str] = []
if payload.get("blocks"):
- pieces += map(render_block, payload["blocks"])
+ try:
+ pieces += map(render_block, payload["blocks"])
+ except LossyConversionError: # nocoverage
+ pieces.append(payload.get("text", "").tame(check_string))
if payload.get("attachments"):
pieces += map(render_attachment, payload["attachments"])