Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
thumbnail: Add a tool to re-thumbnail spinners, or process old images.
Alex Vandiver49d2c1010a6f
diff --git a/zerver/actions/message_edit.py b/zerver/actions/message_edit.pyindex be4dd47873b..b1d5bde2a80 100644--- a/zerver/actions/message_edit.py+++ b/zerver/actions/message_edit.py@@ -58,6 +58,7 @@ from zerver.lib.streams import (notify_stream_is_recently_active_update,)from zerver.lib.string_validation import check_stream_topic+from zerver.lib.thumbnail import get_user_upload_previews, rewrite_thumbnailed_imagesfrom zerver.lib.timestamp import datetime_to_timestampfrom zerver.lib.topic import (ORIG_TOPIC,@@ -78,6 +79,7 @@ from zerver.lib.user_topics import get_users_with_user_topic_visibility_policyfrom zerver.lib.widget import is_widget_messagefrom zerver.models import (ArchivedAttachment,+ ArchivedMessage,Attachment,Message,Reaction,@@ -1573,3 +1575,31 @@ def check_update_message(notify_stream_is_recently_active_update(new_stream, is_stream_active)return updated_message_result++[email protected](durable=True)+def re_thumbnail(+ message_class: type[Message] | type[ArchivedMessage], message_id: int, enqueue: bool+) -> None:+ message = message_class.objects.select_for_update().get(id=message_id)+ assert message.rendered_content is not None+ image_metadata = get_user_upload_previews(+ message.realm_id,+ message.rendered_content,+ enqueue=enqueue,+ lock=True,+ )++ new_content, _ = rewrite_thumbnailed_images(+ message.rendered_content,+ image_metadata,+ )++ if new_content is None:+ pass+ elif isinstance(message, Message):+ do_update_embedded_data(message.sender, message, new_content)+ else:+ assert isinstance(message, ArchivedMessage)+ message.rendered_content = new_content+ message.save(update_fields=["rendered_content"])diff --git a/zerver/lib/thumbnail.py b/zerver/lib/thumbnail.pyindex f4e0137dc5c..0f8f6f108a9 100644--- a/zerver/lib/thumbnail.py+++ b/zerver/lib/thumbnail.py@@ -534,15 +534,35 @@ def rewrite_thumbnailed_images(# This is not an inline image generated by the markdown# processor for a locally-uploaded image.continue++ path_id = image_link["href"].removeprefix("/user_uploads/")+ image_data = images.get(path_id)+image_tag = image_link.find("img", class_="image-loading-placeholder")if image_tag is None:- # The placeholder was already replaced -- for instance,- # this is expected if multiple images are included in the- # same message. The second time this is run, for the- # second image, the first image will have no placeholder.- continue+ image_tag = 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,+ # which means this is an older, non-thumbnailed+ # version. Let's replace the image with a spinner,+ # and mark it as a pending thumbnail.+ changed = True+ image_tag["src"] = "/static/images/loading/loader-black.svg"+ image_tag["class"] = "image-loading-placeholder"+ image_tag["data-original-dimensions"] = (+ f"{image_data.original_width_px}x{image_data.original_height_px}"+ )+ if image_data.original_content_type:+ image_tag["data-original-content-type"] = image_data.original_content_type+ remaining_thumbnails.add(path_id)+ continue+ else:+ # The placeholder was already replaced -- for instance,+ # this is expected if multiple images are included in the+ # same message. The second time this is run, for the+ # second image, the first image will have no placeholder.+ continue- path_id = image_link["href"].removeprefix("/user_uploads/")if to_delete and path_id in to_delete:# This was not a valid thumbnail target, for some reason.# Trim out the whole "message_inline_image" element, since@@ -551,7 +571,6 @@ def rewrite_thumbnailed_images(changed = Truecontinue- image_data = images.get(path_id)if image_data is None:# The message has multiple images, and we're updating just# one image, and it's not this one. Leave this one as-is.diff --git a/zerver/management/commands/thumbnail.py b/zerver/management/commands/thumbnail.pynew file mode 100644index 00000000000..603ff0a27b0--- /dev/null+++ b/zerver/management/commands/thumbnail.py@@ -0,0 +1,64 @@+from datetime import timedelta+from typing import Any++from django.core.management.base import CommandParser+from django.utils.timezone import now as timezone_now+from typing_extensions import override++from zerver.actions.message_edit import re_thumbnail+from zerver.lib.management import ZulipBaseCommand+from zerver.models import ArchivedMessage, Message+++class Command(ZulipBaseCommand):+ help = """Manages thumbnailing in messages."""++ @override+ def add_arguments(self, parser: CommandParser) -> None:+ self.add_realm_args(parser, required=True)+ mode = parser.add_mutually_exclusive_group(required=True)+ mode.add_argument(+ "--stuck-spinners",+ action="store_true",+ help="Attempt to re-render messages with stuck spinners",+ )+ mode.add_argument(+ "--old-images", action="store_true", help="Generate thumbnails of old images"+ )+ parser.add_argument(+ "--cutoff",+ help="Only process messages sent less than this many days ago",+ type=int,+ default=100,+ )++ @override+ def handle(self, *args: Any, **options: Any) -> None:+ realm = self.get_realm(options)+ assert realm is not None++ for message_class in (Message, ArchivedMessage):+ messages = message_class.objects.filter(+ realm_id=realm.id,+ has_image=True,+ date_sent__gt=timezone_now() - timedelta(days=options["cutoff"]),+ )+ if options.get("stuck_spinners"):+ messages = messages.filter(+ rendered_content__contains='class="image-loading-placeholder"',+ date_sent__lt=timezone_now() - timedelta(seconds=60),+ )+ else:+ messages = messages.filter(+ rendered_content__contains='<img src="/user_uploads/',+ ).exclude(+ rendered_content__contains='<img src="/user_uploads/thumbnail/',+ )++ message_ids = list(messages.values_list("id", flat=True))+ print(f"Processing {len(message_ids)} {message_class.__name__} objects")+ for i, message_id in enumerate(message_ids):+ re_thumbnail(message_class, message_id, enqueue=options["old_images"])++ if (i + 1) % 100 == 0:+ print(f"Processed {i + 1}/{len(message_ids)} {message_class.__name__} objects")diff --git a/zerver/tests/test_markdown_thumbnail.py b/zerver/tests/test_markdown_thumbnail.pyindex 8ba520e1630..95a6806bcba 100644--- a/zerver/tests/test_markdown_thumbnail.py+++ b/zerver/tests/test_markdown_thumbnail.py@@ -5,6 +5,7 @@ import pyvipsfrom typing_extensions import overridefrom zerver.actions.message_delete import do_delete_messages+from zerver.actions.message_edit import re_thumbnailfrom zerver.actions.message_send import check_message, do_send_messagesfrom zerver.lib.addressee import Addresseefrom zerver.lib.camo import get_camo_url@@ -22,6 +23,7 @@ from zerver.models import (Message,)from zerver.models.clients import get_client+from zerver.models.realms import get_realmfrom zerver.worker.thumbnail import ensure_thumbnails@@ -478,3 +480,189 @@ class MarkdownThumbnailTest(ZulipTestCase):f' src="/user_uploads/thumbnail/{path_id}/840x560.webp"></a></div>')self.assert_message_content_is(message_id, expected)++ def test_re_thumbnail_stuck(self) -> None:+ # For the case when we generated a thumbnail, but there was a+ # race condition in updating the message, which left it with a+ # permanent spinner. No new thumbnailing is enqueued.+ with self.captureOnCommitCallbacks(execute=True):+ path_id = self.upload_image("img.png")+ content = f"[image](/user_uploads/{path_id})"+ expected = (+ f'<p><a href="/user_uploads/{path_id}">image</a></p>\n'+ f'<div class="message_inline_image"><a href="/user_uploads/{path_id}" title="image">'+ '<img class="image-loading-placeholder"'+ ' data-original-content-type="image/png"'+ ' data-original-dimensions="128x128"'+ ' src="/static/images/loading/loader-black.svg"></a></div>'+ )++ message_id = self.send_message_content(content)+ self.assert_message_content_is(message_id, expected)++ # Exit the block and run thumbnailing++ # Set the rendered content back to the spinner version, so+ # simulate one of the race condition bugs we have had in the+ # past+ self.assertEqual(+ Message.objects.filter(+ realm_id=get_realm("zulip").id,+ has_image=True,+ rendered_content__contains='class="image-loading-placeholder"',+ ).count(),+ 0,+ )+ message = Message.objects.get(id=message_id)+ message.rendered_content = expected+ message.save()+ self.assertEqual(+ Message.objects.filter(+ realm_id=get_realm("zulip").id,+ has_image=True,+ rendered_content__contains='class="image-loading-placeholder"',+ ).count(),+ 1,+ )++ # Trigger the re-thumbnailing codepath+ re_thumbnail(Message, message_id, enqueue=False)++ expected = (+ f'<p><a href="/user_uploads/{path_id}">image</a></p>\n'+ f'<div class="message_inline_image"><a href="/user_uploads/{path_id}" title="image">'+ "<img"+ ' data-original-content-type="image/png"'+ ' data-original-dimensions="128x128"'+ f' src="/user_uploads/thumbnail/{path_id}/840x560.webp"></a></div>'+ )+ self.assert_message_content_is(message_id, expected)++ def test_re_thumbnail_historical(self) -> None:+ # Note that this is all outside the captureOnCommitCallbacks,+ # so we don't actually run thumbnailing for it. This results+ # in a ImageAttachment row but no thumbnails, which matches+ # the state of backfilled previously-uploaded images.+ path_id = self.upload_image("img.png")++ # We don't execute callbacks at all, to drop thumbnailing+ # which would have been done+ content = f"[image](/user_uploads/{path_id})"+ expected = (+ f'<p><a href="/user_uploads/{path_id}">image</a></p>\n'+ f'<div class="message_inline_image"><a href="/user_uploads/{path_id}" title="image">'+ '<img class="image-loading-placeholder"'+ ' data-original-content-type="image/png"'+ ' data-original-dimensions="128x128"'+ ' src="/static/images/loading/loader-black.svg"></a></div>'+ )++ message_id = self.send_message_content(content)+ self.assert_message_content_is(message_id, expected)++ # Force-update to the version without thumbnails+ self.assertEqual(+ Message.objects.filter(+ realm_id=get_realm("zulip").id,+ has_image=True,+ rendered_content__contains='<img src="/user_uploads/',+ )+ .exclude(rendered_content__contains='<img src="/user_uploads/thumbnail/')+ .count(),+ 0,+ )+ message = Message.objects.get(id=message_id)+ message.rendered_content = (+ f'<p><a href="/user_uploads/{path_id}">image</a></p>\n'+ f'<div class="message_inline_image"><a href="/user_uploads/{path_id}" title="image">'+ f'<img src="/user_uploads/{path_id}"></a></div>'+ )+ message.save()+ self.assertEqual(+ Message.objects.filter(+ realm_id=get_realm("zulip").id,+ has_image=True,+ rendered_content__contains='<img src="/user_uploads/',+ )+ .exclude(rendered_content__contains='<img src="/user_uploads/thumbnail/')+ .count(),+ 1,+ )++ with self.captureOnCommitCallbacks(execute=True):+ # Trigger the re-thumbnailing codepath+ re_thumbnail(Message, message_id, enqueue=True)++ # It should have a spinner+ self.assert_message_content_is(message_id, expected)++ # ...and exiting the block should trigger the thumbnailing worker++ expected = (+ f'<p><a href="/user_uploads/{path_id}">image</a></p>\n'+ f'<div class="message_inline_image"><a href="/user_uploads/{path_id}" title="image">'+ "<img"+ ' data-original-content-type="image/png"'+ ' data-original-dimensions="128x128"'+ f' src="/user_uploads/thumbnail/{path_id}/840x560.webp"></a></div>'+ )+ self.assert_message_content_is(message_id, expected)++ # Calling re_thumbnail on the message does nothing if it has a thumbnail+ with self.captureOnCommitCallbacks(execute=True):+ re_thumbnail(Message, message_id, enqueue=True)+ self.assert_message_content_is(message_id, expected)+ self.assert_message_content_is(message_id, expected)++ def test_re_thumbnail_historical_archivedmessage(self) -> None:+ # As above, no worker is run, so we get no thumbnails.+ path_id = self.upload_image("img.png")+ message_id = self.send_message_content(f"[image](/user_uploads/{path_id})")++ # Force-update to the version without thumbnails+ sender_user_profile = self.example_user("othello")+ message = Message.objects.get(id=message_id)+ message.rendered_content = (+ f'<p><a href="/user_uploads/{path_id}">image</a></p>\n'+ f'<div class="message_inline_image"><a href="/user_uploads/{path_id}" title="image">'+ f'<img src="/user_uploads/{path_id}"></a></div>'+ )+ message.save()++ # Delete the message+ do_delete_messages(+ sender_user_profile.realm, [Message.objects.get(id=message_id)], acting_user=None+ )++ with self.captureOnCommitCallbacks(execute=True):+ # Trigger the re-thumbnailing codepath+ re_thumbnail(ArchivedMessage, message_id, enqueue=True)++ # It should have a spinner+ expected = (+ f'<p><a href="/user_uploads/{path_id}">image</a></p>\n'+ f'<div class="message_inline_image"><a href="/user_uploads/{path_id}" title="image">'+ '<img class="image-loading-placeholder"'+ ' data-original-content-type="image/png"'+ ' data-original-dimensions="128x128"'+ ' src="/static/images/loading/loader-black.svg"></a></div>'+ )+ self.assertEqual(+ ArchivedMessage.objects.get(id=message_id).rendered_content,+ expected,+ )++ # ...and exiting the block should trigger the thumbnailing worker++ expected = (+ f'<p><a href="/user_uploads/{path_id}">image</a></p>\n'+ f'<div class="message_inline_image"><a href="/user_uploads/{path_id}" title="image">'+ "<img"+ ' data-original-content-type="image/png"'+ ' data-original-dimensions="128x128"'+ f' src="/user_uploads/thumbnail/{path_id}/840x560.webp"></a></div>'+ )+ self.assertEqual(+ ArchivedMessage.objects.get(id=message_id).rendered_content,+ expected,+ )