Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
refactor: Extract method to process inline images to thumbnails.
Rohan Gudimetlae9f7e580723b
diff --git a/zerver/lib/thumbnail.py b/zerver/lib/thumbnail.pyindex cb0e8fbc7be..fc5176b875e 100644--- a/zerver/lib/thumbnail.py+++ b/zerver/lib/thumbnail.py@@ -4,9 +4,11 @@ import refrom collections.abc import Iteratorfrom contextlib import contextmanagerfrom dataclasses import dataclass+from typing import castimport pyvipsfrom bs4 import BeautifulSoup+from bs4.element import Tagfrom bs4.formatter import EntitySubstitution, HTMLFormatterfrom django.utils.translation import gettext as _from typing_extensions import Self, override@@ -535,6 +537,111 @@ html_formatter = HTMLFormatter()+def process_inline_images_to_thumbnails(+ image_tag: Tag | None,+ image_src: str,+ path_id: str,+ image_data: MarkdownImageMetadata | None,+ to_delete: set[str] | None,+ inline_image_div: Tag,+ image_link: Tag,+) -> tuple[bool, str | None]:+ changed = False+ remaining_thumbnails_to_add = None++ if image_tag is None:+ image_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,+ # 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_to_add = path_id+ 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.+ pass+ return changed, remaining_thumbnails_to_add++ 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" or the "image"+ # element, since it's not going be renderable by clients+ # either.+ inline_image_div.decompose()+ changed = True+ return changed, remaining_thumbnails_to_add++ 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.+ remaining_thumbnails_to_add = path_id+ elif image_data.url is None:+ # We're re-rendering the whole message, so fetched all of+ # the image metadata rows; this is one of the images we+ # about, but is not thumbnailed yet.+ remaining_thumbnails_to_add = path_id+ else:+ changed = True+ del image_tag["class"]+ image_tag["src"] = image_data.url+ image_tag["data-original-dimensions"] = (+ f"{image_data.original_width_px}x{image_data.original_height_px}"+ )+ if image_data.original_content_type is not None:+ image_tag["data-original-content-type"] = image_data.original_content_type+ if image_data.is_animated:+ image_tag["data-animated"] = "true"+ if image_data.transcoded_image is not None:+ image_tag["data-transcoded-image"] = str(image_data.transcoded_image)++ return changed, remaining_thumbnails_to_add+++def process_traditional_inline_images_to_thumbnails(+ images: dict[str, MarkdownImageMetadata],+ to_delete: set[str] | None,+ inline_image_div: Tag,+) -> tuple[bool, str | None] | None:+ image_link = inline_image_div.find("a")+ if (+ not isinstance(image_link, Tag)+ or image_link.get("href") is None+ or not isinstance(image_link["href"], str)+ or not image_link["href"].startswith("/user_uploads/")+ ):+ # This is not an inline image generated by the markdown+ # processor for a locally-uploaded image.+ return None++ path_id = image_link["href"].removeprefix("/user_uploads/")+ image_data = images.get(path_id)+ image_tag = image_link.find("img", class_="image-loading-placeholder")++ assert image_tag is None or isinstance(image_tag, Tag)++ return process_inline_images_to_thumbnails(+ image_tag,+ image_link["href"],+ path_id,+ image_data,+ to_delete,+ inline_image_div,+ image_link,+ )++def rewrite_thumbnailed_images(rendered_content: str,images: dict[str, MarkdownImageMetadata],@@ -548,73 +655,19 @@ def rewrite_thumbnailed_images(changed = Falsefor inline_image_div in parsed_message.find_all("div", class_="message_inline_image"):- image_link = inline_image_div.find("a")- if (- image_link is None- or image_link["href"] is None- or not image_link["href"].startswith("/user_uploads/")- ):- # This is not an inline image generated by the markdown- # processor for a locally-uploaded image.- continue+ processed_results = process_traditional_inline_images_to_thumbnails(+ images, to_delete, inline_image_div+ )- 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:- 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-- 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- # it's not going be renderable by clients either.- inline_image_div.decompose()- changed = True+ if processed_results is None:continue- 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.- remaining_thumbnails.add(path_id)- elif image_data.url is None:- # We're re-rendering the whole message, so fetched all of- # the image metadata rows; this is one of the images we- # about, but is not thumbnailed yet.- remaining_thumbnails.add(path_id)- else:- changed = True- del image_tag["class"]- image_tag["src"] = image_data.url- image_tag["data-original-dimensions"] = (- f"{image_data.original_width_px}x{image_data.original_height_px}"- )- image_tag["data-original-content-type"] = image_data.original_content_type- if image_data.is_animated:- image_tag["data-animated"] = "true"- if image_data.transcoded_image is not None:- image_tag["data-transcoded-image"] = str(image_data.transcoded_image)+ image_changed, remaining_thumbnails_to_add = processed_results++ changed |= image_changed++ if remaining_thumbnails_to_add is not None:+ remaining_thumbnails.add(remaining_thumbnails_to_add)if changed:return (