From 4bfde3f3ca2e283cb0b2fda495303f0d92dcf4de Mon Sep 17 00:00:00 2001 From: bedo Date: Thu, 10 Oct 2024 09:07:28 +0300 Subject: [PATCH] thumbnailing: Add non-image form for empty-title image. Fixes #31007 Add non-image form, in case an image with no title fails to thumbnail. --- zerver/lib/thumbnail.py | 11 +++++++++++ zerver/tests/test_markdown_thumbnail.py | 24 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/zerver/lib/thumbnail.py b/zerver/lib/thumbnail.py index 4bba1ee9dd..c4b5be681e 100644 --- a/zerver/lib/thumbnail.py +++ b/zerver/lib/thumbnail.py @@ -455,7 +455,18 @@ def rewrite_thumbnailed_images( # This was not a valid thumbnail target, for some reason. # Trim out the whole "message_inline_image" element, since # it's not going be renderable by clients either. + image_href = image_link["href"] inline_image_div.decompose() + + if not parsed_message.text.strip(): + # If for some reason (e.g. image has empty title []) the message renderd_content + # becomes empty, insert a non-image form. + soup = BeautifulSoup("", "html.parser") + a_tag = soup.new_tag("a", href=image_href) + p_tag = soup.new_tag("p") + a_tag.string = image_href + p_tag.append(a_tag) + parsed_message.append(p_tag) changed = True continue diff --git a/zerver/tests/test_markdown_thumbnail.py b/zerver/tests/test_markdown_thumbnail.py index 07ac40d598..5efcf077e3 100644 --- a/zerver/tests/test_markdown_thumbnail.py +++ b/zerver/tests/test_markdown_thumbnail.py @@ -292,6 +292,30 @@ class MarkdownThumbnailTest(ZulipTestCase): message_id, f'

image

' ) + def test_thumbnail_bad_image_with_empty_title(self) -> None: + """Test what happens a file with empty title fine, but resizing later fails""" + path_id = self.upload_image("img.png") + message_id = self.send_message_content(f"[](/user_uploads/{path_id})") + self.assert_length(ImageAttachment.objects.get(path_id=path_id).thumbnail_metadata, 0) + + 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()) + # We remove all trace of the preview (since the image was bad) and replaced it with a plain link. + self.assert_message_content_is( + message_id, f'

/user_uploads/{path_id}

' + ) + def test_thumbnail_multiple_messages(self) -> None: sender_user_profile = self.example_user("othello") path_id = self.upload_image("img.png")