Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
slack_incoming: Support more syntax.
Alex Vandiverbc25f016fca8
diff --git a/zerver/webhooks/slack_incoming/fixtures/attachment_blocks.json b/zerver/webhooks/slack_incoming/fixtures/attachment_blocks.jsonnew file mode 100644index 00000000000..0729bfad944--- /dev/null+++ b/zerver/webhooks/slack_incoming/fixtures/attachment_blocks.json@@ -0,0 +1,67 @@+{+ "attachments": [+ {+ "blocks": [+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": "This is a section block with an accessory image."+ },+ "accessory": {+ "type": "image",+ "image_url": "https://pbs.twimg.com/profile_images/625633822235693056/lNGUneLX_400x400.jpg",+ "alt_text": "cute cat"+ }+ },+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": "This is a section block with a button."+ },+ "accessory": {+ "type": "button",+ "text": {+ "type": "plain_text",+ "text": "Click Me",+ "emoji": true+ },+ "value": "click_me_123",+ "action_id": "button-action"+ }+ },+ {+ "type": "section",+ "fields": [+ {+ "type": "plain_text",+ "text": "one",+ "emoji": true+ },+ {+ "type": "plain_text",+ "text": "two",+ "emoji": true+ },+ {+ "type": "plain_text",+ "text": "three",+ "emoji": true+ },+ {+ "type": "plain_text",+ "text": "four",+ "emoji": true+ },+ {+ "type": "plain_text",+ "text": "five",+ "emoji": true+ }+ ]+ }+ ]+ }+ ]+}diff --git a/zerver/webhooks/slack_incoming/fixtures/attachment_fields.json b/zerver/webhooks/slack_incoming/fixtures/attachment_fields.jsonnew file mode 100644index 00000000000..173da6bd128--- /dev/null+++ b/zerver/webhooks/slack_incoming/fixtures/attachment_fields.json@@ -0,0 +1,29 @@+{+ "attachments": [+ {+ "color": "good",+ "fields": [+ {+ "title": "Requested by",+ "value": "Some user",+ "short": true+ },+ {+ "title": "Duration",+ "value": "00:02:03",+ "short": true+ },+ {+ "title": "Build pipeline",+ "value": "ConsumerAddressModule",+ "short": true+ }+ ],+ "pretext": "Build bla bla succeeded",+ "mrkdwn_in": [+ "pretext"+ ],+ "fallback": "Build ConsumerAddressModule_20150407.2 succeeded"+ }+ ]+}diff --git a/zerver/webhooks/slack_incoming/fixtures/attachment_pieces.json b/zerver/webhooks/slack_incoming/fixtures/attachment_pieces.jsonnew file mode 100644index 00000000000..0f6818c6459--- /dev/null+++ b/zerver/webhooks/slack_incoming/fixtures/attachment_pieces.json@@ -0,0 +1,9 @@+{+ "attachments": [+ {+ "title": "Test",+ "image_url": "https://pbs.twimg.com/profile_images/625633822235693056/lNGUneLX_400x400.jpg",+ "ts": 1655945306+ }+ ]+}diff --git a/zerver/webhooks/slack_incoming/fixtures/complicated.json b/zerver/webhooks/slack_incoming/fixtures/complicated.jsonnew file mode 100644index 00000000000..033ecc4f357--- /dev/null+++ b/zerver/webhooks/slack_incoming/fixtures/complicated.json@@ -0,0 +1,91 @@+{+ "blocks": [+ {+ "type": "header",+ "text": {+ "type": "plain_text",+ "text": "Hello from TaskBot",+ "emoji": true+ }+ },+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": "Hey there 👋 I'm TaskBot. I'm here to help you create and manage tasks in Slack.\nThere are two ways to quickly create tasks:"+ }+ },+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": "*1️⃣ Use the `/task` command*. Type `/task` followed by a short description of your tasks and I'll ask for a due date (if applicable). Try it out by using the `/task` command in this channel."+ }+ },+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": "*2️⃣ Use the _Create a Task_ action.* If you want to create a task from a message, select `Create a Task` in a message's context menu. Try it out by selecting the _Create a Task_ action for this message (shown below)."+ }+ },+ {+ "type": "image",+ "title": {+ "type": "plain_text",+ "text": "image1",+ "emoji": true+ },+ "image_url": "https://api.slack.com/img/blocks/bkb_template_images/onboardingComplex.jpg",+ "alt_text": "image1"+ },+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": "➕ To start tracking your team's tasks, *add me to a channel* and I'll introduce myself. I'm usually added to a team or project channel. Type `/invite @TaskBot` from the channel or pick a channel on the right."+ },+ "accessory": {+ "type": "conversations_select",+ "placeholder": {+ "type": "plain_text",+ "text": "Select a channel...",+ "emoji": true+ }+ }+ },+ {+ "type": "input",+ "element": {+ "type": "plain_text_input",+ "action_id": "plain_text_input-action"+ },+ "label": {+ "type": "plain_text",+ "text": "Try writing some task in here:",+ "emoji": true+ }+ },+ {+ "type": "divider"+ },+ {+ "type": "context",+ "elements": [+ {+ "type": "image",+ "image_url": "https://pbs.twimg.com/profile_images/625633822235693056/lNGUneLX_400x400.jpg",+ "alt_text": "cute cat"+ },+ {+ "type": "mrkdwn",+ "text": "👀 View all tasks with `/task list`"+ },+ {+ "type": "mrkdwn",+ "text": "❓Get help at any time with:\n- `/task help`, or\n- type *help* in a DM with me"+ }+ ]+ }+ ]+}diff --git a/zerver/webhooks/slack_incoming/tests.py b/zerver/webhooks/slack_incoming/tests.pyindex acc52cee2c7..ea00310c648 100644--- a/zerver/webhooks/slack_incoming/tests.py+++ b/zerver/webhooks/slack_incoming/tests.py@@ -52,6 +52,7 @@ Hello, world.Danny Torrence left the following *review* for your property:[Overlook Hotel](https://google.com) \n :star: \n Doors had too many axe holes, guest in room 237 was far too rowdy, whole place felt stuck in the 1920s.+[Haunted hotel image](https://is5-ssl.mzstatic.com/image/thumb/Purple3/v4/d3/72/5c/d3725c8f-c642-5d69-1904-aa36e4297885/source/256x256bb.jpg)""".strip()@@ -67,6 +68,7 @@ Danny Torrence left the following *review* for your property:Danny Torrence left the following review for your property:[Overlook Hotel](https://example.com) \n :star: \n Doors had too many axe holes, guest in room 237 was far too rowdy, whole place felt stuck in the 1920s.+[Haunted hotel image](https://is5-ssl.mzstatic.com/image/thumb/Purple3/v4/d3/72/5c/d3725c8f-c642-5d69-1904-aa36e4297885/source/256x256bb.jpg)""".strip()@@ -79,7 +81,8 @@ Danny Torrence left the following review for your property:def test_message_with_attachment(self) -> None:expected_topic = "prometheus-alerts"expected_message = """-[[FIRING:2] InstanceDown for api-server (env="prod", severity="critical")](https://alertmanager.local//#/alerts?receiver=default)+## [[FIRING:2] InstanceDown for api-server (env="prod", severity="critical")](https://alertmanager.local//#/alerts?receiver=default)+:chart_with_upwards_trend: **[Graph](http://generator.local/1)** :notebook: **[Runbook](https://runbook.local/1)****Alert details**:@@ -106,6 +109,92 @@ Danny Torrence left the following review for your property:expected_message,)+ def test_complicated(self) -> None:+ # Paste the JSON into+ # https://api.slack.com/tools/block-kit-builder to see how it+ # is rendered in Slack+ expected_topic = "(no topic)"+ expected_message = """+## Hello from TaskBot++Hey there 👋 I'm TaskBot. I'm here to help you create and manage tasks in Slack.+There are two ways to quickly create tasks:++**1️⃣ Use the `/task` command**. Type `/task` followed by a short description of your tasks and I'll ask for a due date (if applicable). Try it out by using the `/task` command in this channel.++**2️⃣ Use the *Create a Task* action.** If you want to create a task from a message, select `Create a Task` in a message's context menu. Try it out by selecting the *Create a Task* action for this message (shown below).++[image1](https://api.slack.com/img/blocks/bkb_template_images/onboardingComplex.jpg)++➕ To start tracking your team's tasks, **add me to a channel** and I'll introduce myself. I'm usually added to a team or project channel. Type `/invite @TaskBot` from the channel or pick a channel on the right.++----++[cute cat](https://pbs.twimg.com/profile_images/625633822235693056/lNGUneLX_400x400.jpg)++👀 View all tasks with `/task list`++❓Get help at any time with:+- `/task help`, or+- type **help** in a DM with me+ """.strip()++ self.check_webhook(+ "complicated",+ expected_topic,+ expected_message,+ )++ def test_attachment_blocks(self) -> None:+ # On https://api.slack.com/tools/block-kit-builder choose+ # "Attachment preview" and paste the JSON in.+ expected_topic = "(no topic)"+ expected_message = """+This is a section block with an accessory image.++[cute cat](https://pbs.twimg.com/profile_images/625633822235693056/lNGUneLX_400x400.jpg)++This is a section block with a button.+ """.strip()++ self.check_webhook(+ "attachment_blocks",+ expected_topic,+ expected_message,+ )++ def test_attachment_fields(self) -> None:+ expected_topic = "(no topic)"+ expected_message = """+Build bla bla succeeded++**Requested by**: Some user+**Duration**: 00:02:03+**Build pipeline**: ConsumerAddressModule+ """.strip()++ self.check_webhook(+ "attachment_fields",+ expected_topic,+ expected_message,+ )++ def test_attachment_pieces(self) -> None:+ expected_topic = "(no topic)"+ expected_message = """+## Test++[](https://pbs.twimg.com/profile_images/625633822235693056/lNGUneLX_400x400.jpg)++<time:1655945306>+ """.strip()++ self.check_webhook(+ "attachment_pieces",+ expected_topic,+ expected_message,+ )+def get_body(self, fixture_name: str) -> str:if "urlencoded" in fixture_name:file_type = "txt"diff --git a/zerver/webhooks/slack_incoming/view.py b/zerver/webhooks/slack_incoming/view.pyindex bb97ad90068..10901dc2766 100644--- a/zerver/webhooks/slack_incoming/view.py+++ b/zerver/webhooks/slack_incoming/view.py@@ -9,7 +9,16 @@ from zerver.decorator import webhook_viewfrom zerver.lib.exceptions import JsonableErrorfrom zerver.lib.request import REQ, RequestVariableMissingError, has_request_variablesfrom zerver.lib.response import json_success-from zerver.lib.validator import WildValue, WildValueDict, check_string, check_url, to_wild_value+from zerver.lib.types import Validator+from zerver.lib.validator import (+ WildValue,+ check_dict,+ check_int,+ check_string,+ check_string_in,+ check_url,+ to_wild_value,+)from zerver.lib.webhooks.common import check_send_webhook_messagefrom zerver.models import UserProfile@@ -72,38 +81,131 @@ def api_slack_incoming_webhook(def render_block(block: WildValue) -> str:- block_type = block["type"].tame(check_string)- if block_type == "section":- body = ""+ # https://api.slack.com/reference/block-kit/blocks+ block_type = block["type"].tame(+ check_string_in(["actions", "context", "divider", "header", "image", "input", "section"])+ )+ if block_type == "actions":+ # Unhandled+ return ""+ elif block_type == "context" and block.get("elements"):+ pieces = []+ # Slack renders these pieces left-to-right, packed in as+ # closely as possible. We just render them above each other,+ # for simplicity.+ for element in block["elements"]:+ element_type = element["type"].tame(check_string_in(["image", "plain_text", "mrkdwn"]))+ if element_type == "image":+ pieces.append(render_block_element(element))+ else:+ pieces.append(element.tame(check_text_block()))+ return "\n\n".join(piece.strip() for piece in pieces if piece.strip() != "")+ elif block_type == "divider":+ return "----"+ elif block_type == "header":+ return "## " + block["text"].tame(check_text_block(plain_text_only=True))+ elif block_type == "image":+ image_url = block["image_url"].tame(check_url)+ alt_text = block["alt_text"].tame(check_string)+ if "title" in block:+ alt_text = block["title"].tame(check_text_block(plain_text_only=True))+ return f"[{alt_text}]({image_url})"+ elif block_type == "input":+ # Unhandled+ pass+ elif block_type == "section":+ pieces = []if "text" in block:- text = block["text"]- while isinstance(text, WildValueDict):- text = text["text"]- body += "\n\n" + text.tame(check_string)+ pieces.append(block["text"].tame(check_text_block()))if "accessory" in block:- accessory = block["accessory"]- accessory_type = accessory["type"].tame(check_string)- if accessory_type == "image":- # This should become  once proper Markdown images are supported- alt_text = accessory["alt_text"].tame(check_string)- image_url = accessory["image_url"].tame(check_url)- body += f"\n[{alt_text}]({image_url})"- return body+ pieces.append(render_block_element(block["accessory"]))++ if "fields" in block:+ # TODO -- these should be rendered in two columns,+ # left-to-right. We could render them sequentially,+ # except some may be Title1 / Title2 / value1 / value2,+ # which would be nonsensical when rendered sequentially.+ pass++ return "\n\n".join(piece.strip() for piece in pieces if piece.strip() != "")return ""+def check_text_block(plain_text_only: bool = False) -> Validator[str]:+ if plain_text_only:+ type_validator = check_string_in(["plain_text"])+ else:+ type_validator = check_string++ def f(var_name: str, val: object) -> str:+ block = check_dict(+ [+ ("type", type_validator),+ ("text", check_string),+ ],+ )(var_name, val)++ # We can't use `value_validator=check_string` above to let+ # mypy know this is a str, because there's an optional boolean+ # `emoji` key which can appear -- hence the assert.+ text = block["text"]+ assert isinstance(text, str)++ # Ideally we would escape the content if it was plain text,+ # but out flavor of Markdown doesn't support escapes. :(+ return text++ return f+++def render_block_element(element: WildValue) -> str:+ # https://api.slack.com/reference/block-kit/block-elements+ # Zulip doesn't support interactive elements, so we only render images here+ element_type = element["type"].tame(check_string)+ if element_type == "image":+ image_url = element["image_url"].tame(check_url)+ alt_text = element["alt_text"].tame(check_string)+ return f"[{alt_text}]({image_url})"+ else:+ # Unsupported+ return ""++def render_attachment(attachment: WildValue) -> str:- attachment_body = ""- if "title" in attachment and "title_link" in attachment:+ # https://api.slack.com/reference/messaging/attachments+ pieces = []+ if "title" in attachment:title = attachment["title"].tame(check_string)- title_link = attachment["title_link"].tame(check_string)- attachment_body += f"[{title}]({title_link})\n"+ if "title_link" in attachment:+ title_link = attachment["title_link"].tame(check_url)+ pieces.append(f"## [{title}]({title_link})")+ else:+ pieces.append(f"## {title}")+ if "pretext" in attachment:+ pieces.append(attachment["pretext"].tame(check_string))if "text" in attachment:- attachment_body += attachment["text"].tame(check_string)-- return attachment_body+ pieces.append(attachment["text"].tame(check_string))+ if "fields" in attachment:+ fields = []+ for field in attachment["fields"]:+ title = field["title"].tame(check_string)+ value = field["value"].tame(check_string)+ fields.append(f"*{title}*: {value}")+ pieces.append("\n".join(fields))+ if "blocks" in attachment and attachment["blocks"]:+ for block in attachment["blocks"]:+ pieces.append(render_block(block))+ if "image_url" in attachment:+ pieces.append("[]({})".format(attachment["image_url"].tame(check_url)))+ if "footer" in attachment:+ pieces.append(attachment["footer"].tame(check_string))+ if "ts" in attachment:+ time = attachment["ts"].tame(check_int)+ pieces.append(f"<time:{time}>")++ return "\n\n".join(piece.strip() for piece in pieces if piece.strip() != "")def replace_links(text: str) -> str: