Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
markdown: Add support for `` syntax for inline images.
Rohan Gudimetla48fac910b5dd
diff --git a/zerver/lib/markdown/__init__.py b/zerver/lib/markdown/__init__.pyindex e4f0a07aa63..fcc511592e1 100644--- a/zerver/lib/markdown/__init__.py+++ b/zerver/lib/markdown/__init__.py@@ -2122,6 +2122,77 @@ class AudioInlineProcessor(markdown.inlinepatterns.LinkInlineProcessor):return None, None, None+class ImageInlineProcessor(markdown.inlinepatterns.ImageInlineProcessor):+ def __init__(self, pattern: str, zmd: "ZulipMarkdown") -> None:+ super().__init__(pattern, zmd)+ self.zmd = zmd++ def zulip_specific_src_changes(self, img: Element) -> None | Element:+ # function partially copied from LinkInlineProcessor.zulip_specific_link_changes+ src = img.get("src")+ assert src is not None++ # Sanitize URL or don't parse image. See linkify_tests in markdown_test_cases for banned syntax.+ src = sanitize_url(self.unescape(src.strip()))+ if src is None:+ return None # no-op; the image is not processed.++ # Rewrite local links to be relative+ db_data: DbData | None = self.zmd.zulip_db_data+ src = rewrite_local_links_to_relative(db_data, src)+ maybe_add_attachment_path_id(src, self.zmd)+ img.set("data-original-src", src)++ # We try to use image thumbnails for previews of the user+ # upload images rather than original images when available.+ if src.startswith("/user_uploads/") and db_data:+ path_id = src[len("/user_uploads/") :]++ # We should have pulled the preview data for this image+ # (even if that's "no preview yet") from the database+ # before rendering; Else, its header didn't parse as+ # a valid image type which libvips handles.+ if path_id not in db_data.user_upload_previews.image_metadata:+ return None+ else:+ assert path_id in db_data.user_upload_previews.image_metadata+ metadata = db_data.user_upload_previews.image_metadata[path_id]++ # Insert a placeholder image spinner. We post-process+ # this content (see rewrite_thumbnailed_images in+ # zerver.lib.thumbnail), looking specifically for this+ # tag, and may re-write it into the thumbnail URL if it+ # already exists when the message is sent.+ img.set("class", "inline-image image-loading-placeholder")+ img.set("src", "/static/images/loading/loader-black.svg")+ img.set(+ "data-original-dimensions",+ f"{metadata.original_width_px}x{metadata.original_height_px}",+ )+ if metadata.original_content_type:+ img.set(+ "data-original-content-type",+ metadata.original_content_type,+ )+ else:+ img.set("src", src)++ return img++ @override+ def handleMatch( # type: ignore[override] # https://github.com/python/mypy/issues/10197+ self, m: Match[str], data: str+ ) -> tuple[Element | str | None, int | None, int | None]:+ ret = super().handleMatch(m, data)+ if ret[0] is not None:+ img, match_start, index = ret+ assert isinstance(img, Element)+ img = self.zulip_specific_src_changes(img)+ if img is not None:+ return img, match_start, index+ return None, None, None++def get_sub_registry(r: markdown.util.Registry[T], keys: list[str]) -> markdown.util.Registry[T]:# Registry is a new class added by Python-Markdown to replace OrderedDict.# Since Registry doesn't support .keys(), it is easier to make a new@@ -2283,7 +2354,10 @@ class ZulipMarkdown(markdown.Markdown):UserGroupMentionPattern(mention.USER_GROUP_MENTIONS_RE, self), "usergroupmention", 65)reg.register(LinkInlineProcessor(markdown.inlinepatterns.LINK_RE, self), "link", 60)- reg.register(AudioInlineProcessor(markdown.inlinepatterns.IMAGE_LINK_RE, self), "audio", 57)+ # We register higher priority on audio patterns, as the processing logic will pass things+ # onto image patterns in the absence of a supported audio type+ reg.register(AudioInlineProcessor(markdown.inlinepatterns.IMAGE_LINK_RE, self), "audio", 58)+ reg.register(ImageInlineProcessor(markdown.inlinepatterns.IMAGE_LINK_RE, self), "image", 57)reg.register(AutoLink(get_web_link_regex(), self), "autolink", 55)# Reserve priority 45-54 for linkifiersreg = self.register_linkifiers(reg)diff --git a/zerver/lib/thumbnail.py b/zerver/lib/thumbnail.pyindex fc5176b875e..bfd54031e3d 100644--- a/zerver/lib/thumbnail.py+++ b/zerver/lib/thumbnail.py@@ -543,13 +543,14 @@ def process_inline_images_to_thumbnails(path_id: str,image_data: MarkdownImageMetadata | None,to_delete: set[str] | None,- inline_image_div: Tag,- image_link: Tag,+ inline_image_div: Tag | None = None,+ image_link: Tag | None = None,) -> tuple[bool, str | None]:changed = Falseremaining_thumbnails_to_add = Noneif image_tag is None:+ assert image_link is not Noneimage_tag = cast(Tag | None, image_link.find("img", src=image_link["href"]))if image_tag and image_data is not None:# The <img> element has the same src as the link,@@ -579,7 +580,12 @@ def process_inline_images_to_thumbnails(# Trim out the whole "message_inline_image" or the "image"# element, since it's not going be renderable by clients# either.- inline_image_div.decompose()+ if inline_image_div is not None:+ inline_image_div.decompose()+ else:+ assert image_tag is not None+ image_tag.decompose()+changed = Truereturn changed, remaining_thumbnails_to_add@@ -595,6 +601,10 @@ def process_inline_images_to_thumbnails(else:changed = Truedel image_tag["class"]++ if inline_image_div is None:+ image_tag["class"] = "inline-image"+image_tag["src"] = image_data.urlimage_tag["data-original-dimensions"] = (f"{image_data.original_width_px}x{image_data.original_height_px}"@@ -654,6 +664,8 @@ def rewrite_thumbnailed_images(parsed_message = BeautifulSoup(rendered_content, "html.parser")changed = False++ # Loading placeholder images for previews of linked images use this code path.for inline_image_div in parsed_message.find_all("div", class_="message_inline_image"):processed_results = process_traditional_inline_images_to_thumbnails(images, to_delete, inline_image_div@@ -669,6 +681,26 @@ def rewrite_thumbnailed_images(if remaining_thumbnails_to_add is not None:remaining_thumbnails.add(remaining_thumbnails_to_add)+ # Loading placeholder images for modern Markdown images use this code path.+ for inline_image in parsed_message.find_all(+ "img", class_="inline-image image-loading-placeholder"+ ):+ image_src = inline_image.get("data-original-src")++ assert image_src is not None++ path_id = image_src.removeprefix("/user_uploads/")+ image_data = images.get(path_id)++ image_changed, remaining_thumbnails_to_add = process_inline_images_to_thumbnails(+ inline_image, image_src, path_id, image_data, to_delete+ )++ changed |= image_changed++ if remaining_thumbnails_to_add is not None:+ remaining_thumbnails.add(remaining_thumbnails_to_add)+if changed:return (parsed_message.encode(formatter=html_formatter).decode().strip(),diff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.pyindex 92402920a67..3c31b1463ad 100644--- a/zerver/tests/test_markdown.py+++ b/zerver/tests/test_markdown.py@@ -831,6 +831,29 @@ class MarkdownEmbedsTest(ZulipTestCase):f"""<p><a href="http://www.youtube.com/watch_videos?video_ids=nOJgD4fcZhI,i96UO8-GFvw">http://www.youtube.com/watch_videos?video_ids=nOJgD4fcZhI,i96UO8-GFvw</a></p>\n<div class="youtube-video message_inline_image"><a data-id="nOJgD4fcZhI" href="http://www.youtube.com/watch_videos?video_ids=nOJgD4fcZhI,i96UO8-GFvw"><img src="{get_camo_url("https://i.ytimg.com/vi/nOJgD4fcZhI/mqdefault.jpg")}"></a></div>""",)+ def test_inline_image(self) -> None:+ image_url = "https://www.google.com/images/srpr/logo4w.png"+ msg = f"The Google logo looks like this:  and..."+ converted = markdown_convert_wrapper(msg)+ self.assertEqual(+ converted,+ f"""<p>The Google logo looks like this: <img alt="Google logo" data-original-src="{image_url}" src="{get_camo_url(image_url)}"> and...</p>""",+ )++ msg = ''+ converted = markdown_convert_wrapper(msg)+ self.assertEqual(+ converted,+ '<p><img alt="foo" data-original-src="/url" src="/url" title="the title"></p>',+ )++ msg = ""+ converted = markdown_convert_wrapper(msg)+ self.assertEqual(+ converted,+ '<p><img alt="" data-original-src="/url" src="/url"></p>',+ )+def test_inline_image_preview(self) -> None:url = "http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg"camo_url = get_camo_url(url)diff --git a/zerver/tests/test_markdown_thumbnail.py b/zerver/tests/test_markdown_thumbnail.pyindex 95a6806bcba..1b08f34cc16 100644--- a/zerver/tests/test_markdown_thumbnail.py+++ b/zerver/tests/test_markdown_thumbnail.py@@ -145,6 +145,32 @@ class MarkdownThumbnailTest(ZulipTestCase):)self.assert_message_content_is(message_id, expected)+ def test_inline_image_thumbnail_after_send(self) -> None:+ with self.captureOnCommitCallbacks(execute=True):+ path_id = self.upload_image("img.png")+ content = f""+ expected = (+ '<p><img alt="image"'+ ' class="inline-image image-loading-placeholder"'+ ' data-original-content-type="image/png"'+ ' data-original-dimensions="128x128"'+ f' data-original-src="/user_uploads/{path_id}"'+ ' src="/static/images/loading/loader-black.svg"></p>'+ )++ message_id = self.send_message_content(content)+ self.assert_message_content_is(message_id, expected)++ # Exit the block and run thumbnailing+ expected = (+ '<p><img alt="image" class="inline-image"'+ ' data-original-content-type="image/png"'+ ' data-original-dimensions="128x128"'+ f' data-original-src="/user_uploads/{path_id}"'+ f' src="/user_uploads/thumbnail/{path_id}/840x560.webp"></p>'+ )+ self.assert_message_content_is(message_id, expected)+def test_thumbnail_escaping(self) -> None:self.login("othello")with self.captureOnCommitCallbacks(execute=True):@@ -326,6 +352,28 @@ class MarkdownThumbnailTest(ZulipTestCase):message_id, f'<p><a href="/user_uploads/{path_id}">image</a></p>')+ def test_thumbnail_bad_inline_image(self) -> None:+ """Test what happens if the file looks fine, but resizing later fails"""+ path_id = self.upload_image("img.png")+ message_id = self.send_message_content(f"Testing ")+ self.assert_length(ImageAttachment.objects.get(path_id=path_id).thumbnail_metadata, 0)++ # If the image is found to be bad, we remove all trace of the preview+ with (+ patch.object(+ pyvips.Image, "thumbnail_buffer", side_effect=pyvips.Error("some bad error")+ ) as thumb_mock,+ self.assertLogs("zerver.worker.thumbnail", "ERROR") as thumbnail_logs,+ ):+ ensure_thumbnails(ImageAttachment.objects.get(path_id=path_id))+ thumb_mock.assert_called_once()+ self.assert_length(thumbnail_logs.output, 1)+ self.assertTrue(+ thumbnail_logs.output[0].startswith("ERROR:zerver.worker.thumbnail:some bad error")+ )+ self.assertFalse(ImageAttachment.objects.filter(path_id=path_id).exists())+ self.assert_message_content_is(message_id, "<p>Testing </p>")+def test_thumbnail_multiple_messages(self) -> None:sender_user_profile = self.example_user("othello")path_id = self.upload_image("img.png")