slack_incoming: Use Slack text reformatters from data import.

This commit updates the Slack incoming webhook endpoint to use the same
Slack reformatting functions (`convert_to_zulip_markdown` and
`replace_links`) that are used for Slack data import and cleaning up any
duplicative functions.

This was previously not possible because the Slack reformatting regex in
`slack_message_conversion.py` could not handle these cases:

- Formatting applied to non-ASCII characters (e.g., emoji).

- Formatted strings separated by exactly one character.

- Formatted strings appearing immediately after a new line.

Fixes part of #31162.
This commit is contained in:
PieterCK
2024-11-19 14:16:08 +07:00
committed by Tim Abbott
parent c018911c5b
commit a228699108
2 changed files with 13 additions and 15 deletions

View File

@@ -383,3 +383,9 @@ def render_attachment(attachment: WildValue) -> str:
pieces.append(f"<time:{time}>")
return "\n\n".join(piece.strip() for piece in pieces if piece.strip() != "")
def replace_links(text: str) -> str:
text, _ = convert_link_format(text)
text, _ = convert_mailto_format(text)
return text

View File

@@ -8,7 +8,12 @@ from django.http import HttpRequest, HttpResponse, JsonResponse
from django.utils.translation import gettext as _
from typing_extensions import ParamSpec
from zerver.data_import.slack_message_conversion import render_attachment, render_block
from zerver.data_import.slack_message_conversion import (
convert_slack_formatting,
render_attachment,
render_block,
replace_links,
)
from zerver.decorator import webhook_view
from zerver.lib.exceptions import JsonableError
from zerver.lib.request import RequestVariableMissingError
@@ -93,19 +98,6 @@ def api_slack_incoming_webhook(
body = body.strip()
if body != "":
body = replace_formatting(replace_links(body).strip())
body = convert_slack_formatting(replace_links(body).strip())
check_send_webhook_message(request, user_profile, user_specified_topic, body)
return json_success(request, data={"ok": True})
def replace_links(text: str) -> str:
return re.sub(r"<(\w+?:\/\/.*?)\|(.*?)>", r"[\2](\1)", text)
def replace_formatting(text: str) -> str:
# Slack uses *text* for bold, whereas Zulip interprets that as italics
text = re.sub(r"([^\w]|^)\*(?!\s+)([^\*\n]+)(?<!\s)\*((?=[^\w])|$)", r"\1**\2**\3", text)
# Slack uses _text_ for emphasis, whereas Zulip interprets that as nothing
text = re.sub(r"([^\w]|^)[_](?!\s+)([^\_\n]+)(?<!\s)[_]((?=[^\w])|$)", r"\1*\2*\3", text)
return text