Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
upload: Return the closest-rendered thumbnail.
Alex Vandiver6c624805ce2a
diff --git a/zerver/tests/test_thumbnail.py b/zerver/tests/test_thumbnail.pyindex 9a3cb70975c..de72cbaf07c 100644--- a/zerver/tests/test_thumbnail.py+++ b/zerver/tests/test_thumbnail.py@@ -8,6 +8,7 @@ from unittest.mock import patchimport orjsonimport pyvipsfrom django.conf import settings+from django.http.request import MediaTypefrom django.test import override_settingsfrom zerver.lib.test_classes import ZulipTestCase@@ -26,6 +27,7 @@ from zerver.lib.upload import (split_thumbnail_path,)from zerver.models import Attachment, ImageAttachment+from zerver.views.upload import closest_thumbnail_formatfrom zerver.worker.thumbnail import ensure_thumbnails@@ -504,9 +506,16 @@ class TestThumbnailRetrieval(ZulipTestCase):self.assertEqual(response.status_code, 200)self.assertEqual(response.headers["Content-Type"], "image/gif")+ # Format we don't have+ response = self.client_get(f"/user_uploads/thumbnail/{path_id}/1x1.png")+ self.assertEqual(response.status_code, 404)+ self.assertEqual(response.headers["Content-Type"], "image/png")+# Exit the block, triggering the thumbnailing worker- thumbnail_response = self.client_get(f"/user_uploads/thumbnail/{path_id}/{webp_still!s}")+ thumbnail_response = self.client_get(+ f"/user_uploads/thumbnail/{path_id}/{webp_still!s}"+ )self.assertEqual(thumbnail_response.status_code, 200)self.assertEqual(thumbnail_response.headers["Content-Type"], "image/webp")self.assertLess(@@ -527,11 +536,6 @@ class TestThumbnailRetrieval(ZulipTestCase):self.assertEqual(response.status_code, 404)self.assertEqual(response.headers["Content-Type"], "image/png")- # Format we don't have- response = self.client_get(f"/user_uploads/thumbnail/{path_id}/1x1.png")- self.assertEqual(response.status_code, 404)- self.assertEqual(response.headers["Content-Type"], "image/png")-# path_id for a non-imagewith (self.captureOnCommitCallbacks(execute=True),@@ -593,14 +597,126 @@ class TestThumbnailRetrieval(ZulipTestCase):path_id = re.sub(r"/user_uploads/", "", json_response["url"])# Exit the block, triggering the thumbnailing worker- response = self.client_get(f"/user_uploads/thumbnail/{path_id}/{webp_still!s}")- self.assertEqual(response.status_code, 200)- self.assertEqual(response.headers["Content-Type"], "image/webp")+ still_response = self.client_get(f"/user_uploads/thumbnail/{path_id}/{webp_still!s}")+ self.assertEqual(still_response.status_code, 200)+ self.assertEqual(still_response.headers["Content-Type"], "image/webp")- response = self.client_get(f"/user_uploads/thumbnail/{path_id}/{webp_anim!s}")- self.assertEqual(response.status_code, 404)- self.assertEqual(response.headers["Content-Type"], "image/png")+ # We can request -anim -- we didn't render it, but we the+ # "closest we rendered" logic kicks in, and we get the+ # still webp, rather than a 404+ animated_response = self.client_get(f"/user_uploads/thumbnail/{path_id}/{webp_anim!s}")+ self.assertEqual(animated_response.status_code, 200)+ self.assertEqual(animated_response.headers["Content-Type"], "image/webp")+ # Double-check that we don't actually have the animated version, by comparing file sizes+ self.assertEqual(+ animated_response.headers["Content-Length"],+ still_response.headers["Content-Length"],+ )response = self.client_get(f"/user_uploads/thumbnail/{path_id}/{jpeg_still!s}")self.assertEqual(response.status_code, 200)self.assertEqual(response.headers["Content-Type"], "image/jpeg")++ def test_closest_format(self) -> None:+ self.login_user(self.example_user("hamlet"))++ webp_anim = ThumbnailFormat("webp", 100, 75, animated=True)+ webp_still = ThumbnailFormat("webp", 100, 75, animated=False)+ tiny_webp_still = ThumbnailFormat("webp", 10, 10, animated=False)+ gif_still = ThumbnailFormat("gif", 100, 75, animated=False)+ with (+ self.mock_formats([webp_anim, webp_still, tiny_webp_still, gif_still]),+ self.captureOnCommitCallbacks(execute=True),+ get_test_image_file("animated_img.gif") as image_file,+ ):+ json_response = self.assert_json_success(+ self.client_post("/json/user_uploads", {"file": image_file})+ )+ path_id = re.sub(r"/user_uploads/", "", json_response["url"])+ # Exit the block, triggering the thumbnailing worker++ image_attachment = ImageAttachment.objects.get(path_id=path_id)+ rendered_formats = [+ StoredThumbnailFormat(**data) for data in image_attachment.thumbnail_metadata+ ]+ accepts = [MediaType("image/webp"), MediaType("image/*"), MediaType("*/*;q=0.8")]++ # Prefer to match -animated, even though we have a .gif+ self.assertEqual(+ str(+ closest_thumbnail_format(+ ThumbnailFormat("gif", 100, 75, animated=True), accepts, rendered_formats+ )+ ),+ "100x75-anim.webp",+ )++ # Match the extension, even if we're an exact match for a different size+ self.assertEqual(+ str(+ closest_thumbnail_format(+ ThumbnailFormat("gif", 10, 10, animated=False), accepts, rendered_formats+ )+ ),+ "100x75.gif",+ )++ # If they request an extension we don't do, then we look for the formats they prefer+ self.assertEqual(+ str(+ closest_thumbnail_format(+ ThumbnailFormat("tif", 10, 10, animated=False), accepts, rendered_formats+ )+ ),+ "10x10.webp",+ )+ self.assertEqual(+ str(+ closest_thumbnail_format(+ ThumbnailFormat("tif", 10, 10, animated=False),+ [MediaType("image/webp;q=0.9"), MediaType("image/gif")],+ rendered_formats,+ )+ ),+ "100x75.gif",+ )+ self.assertEqual(+ str(+ closest_thumbnail_format(+ ThumbnailFormat("tif", 10, 10, animated=False),+ [MediaType("image/gif")],+ rendered_formats,+ )+ ),+ "100x75.gif",+ )++ # Closest width+ self.assertEqual(+ str(+ closest_thumbnail_format(+ ThumbnailFormat("webp", 20, 100, animated=False), accepts, rendered_formats+ )+ ),+ "10x10.webp",+ )+ self.assertEqual(+ str(+ closest_thumbnail_format(+ ThumbnailFormat("webp", 80, 10, animated=False), accepts, rendered_formats+ )+ ),+ "100x75.webp",+ )++ # Smallest filesize if they have no media preference+ self.assertEqual(+ str(+ closest_thumbnail_format(+ ThumbnailFormat("tif", 100, 75, animated=False),+ [MediaType("image/gif"), MediaType("image/webp")],+ rendered_formats,+ )+ ),+ "100x75.webp",+ )diff --git a/zerver/views/upload.py b/zerver/views/upload.pyindex b8fc646e6fd..e1269910644 100644--- a/zerver/views/upload.py+++ b/zerver/views/upload.py@@ -17,6 +17,7 @@ from django.http import (HttpResponseForbidden,HttpResponseNotFound,)+from django.http.request import MediaTypefrom django.shortcuts import redirectfrom django.urls import reversefrom django.utils.cache import patch_cache_control, patch_vary_headers@@ -203,6 +204,41 @@ def preferred_accept(request: HttpRequest, served_types: list[str]) -> str | Nonreturn None+def closest_thumbnail_format(+ requested_format: BaseThumbnailFormat,+ accepts: list[MediaType],+ rendered_formats: list[StoredThumbnailFormat],+) -> StoredThumbnailFormat:+ accepted_types = sorted(+ accepts,+ key=lambda e: float(e.params.get("q", "1.0")),+ reverse=True,+ )++ def q_for(content_type: str) -> float:+ for potential_type in accepted_types:+ if potential_type.match(content_type):+ return float(potential_type.params.get("q", "1.0"))+ return 0.0++ # Serve a "close" format -- preferring animated which+ # matches, followed by the format they requested, or one+ # their browser supports, in the size closest to what they+ # requested, with the minimum bytes.+ def grade_format(+ possible_format: StoredThumbnailFormat,+ ) -> tuple[bool, bool, float, int, int]:+ return (+ possible_format.animated != requested_format.animated,+ possible_format.extension != requested_format.extension,+ 1.0 - q_for(possible_format.content_type),+ abs(requested_format.max_width - possible_format.max_width),+ possible_format.byte_size,+ )++ return sorted(rendered_formats, key=grade_format)[0]++def serve_file(request: HttpRequest,maybe_user_profile: UserProfile | AnonymousUser,@@ -269,11 +305,23 @@ def serve_file(else:potential_output_formats = THUMBNAIL_OUTPUT_FORMATSif requested_format not in potential_output_formats:- if requested_format in rendered_formats:+ if rendered_formats == []:+ # We haven't rendered anything, and they requested+ # something we don't support.+ return serve_image_error(404, "images/errors/image-not-exist.png")+ elif requested_format in rendered_formats:# Not a _current_ format, but we did render it at the time, so fine to servepasselse:- return serve_image_error(404, "images/errors/image-not-exist.png")+ # Find something "close enough". This will not be a+ # common occurrence -- the client has out of date+ # information about which formats are supported, and+ # the thumbnails were generated with an even earlier+ # set, or the client is just guessing a format and+ # hoping.+ requested_format = closest_thumbnail_format(+ requested_format, request.accepted_types, rendered_formats+ )elif requested_format not in rendered_formats:# They requested a valid format, but one we've not# rendered yet. Take a lock on the row, then render every