Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
thumbnail: Add thumbnail status polling endpoint.
santhoshkumarCodesc8d722e4dfdb
diff --git a/api_docs/changelog.md b/api_docs/changelog.mdindex 47458a56526..6b832f70812 100644--- a/api_docs/changelog.md+++ b/api_docs/changelog.md@@ -20,6 +20,12 @@ format used by the Zulip server that they are interacting with.## Changes in Zulip 12.0+**Feature level 479**++* [`GET /thumbnail/status/{realm_id_str}/{filename}`](/api/check-thumbnail-status): Added+ a new endpoint to check whether thumbnails have been generated for an+ uploaded image.+**Feature level 478*** [`POST /realm/filters`](/api/add-linkifier),diff --git a/api_docs/include/rest-endpoints.md b/api_docs/include/rest-endpoints.mdindex 50c447a542b..92dce89a326 100644--- a/api_docs/include/rest-endpoints.md+++ b/api_docs/include/rest-endpoints.md@@ -19,6 +19,7 @@* [Mark messages in a topic as read](/api/mark-topic-as-read)* [Get a message's read receipts](/api/get-read-receipts)* [Get temporary URL for an uploaded file](/api/get-file-temporary-url)+* [Check thumbnail status](/api/check-thumbnail-status)* [Report a message](/api/report-message)#### Scheduled messagesdiff --git a/version.py b/version.pyindex c37f71110f4..3541dd31317 100644--- a/version.py+++ b/version.py@@ -33,7 +33,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"# https://zulip.readthedocs.io/en/latest/documentation/api.html#step-by-step-guide# Also available at docs/documentation/api.md.-API_FEATURE_LEVEL = 478+API_FEATURE_LEVEL = 479# Bump the minor PROVISION_VERSION to indicate that folks should provision# only when going from an old version of the code to a newer version. Bumpdiff --git a/zerver/openapi/curl_param_value_generators.py b/zerver/openapi/curl_param_value_generators.pyindex c2873a4e799..86c137c8310 100644--- a/zerver/openapi/curl_param_value_generators.py+++ b/zerver/openapi/curl_param_value_generators.py@@ -21,6 +21,7 @@ from zerver.actions.realm_playgrounds import check_add_realm_playgroundfrom zerver.lib.events import do_events_registerfrom zerver.lib.initial_password import initial_passwordfrom zerver.lib.test_classes import ZulipTestCase+from zerver.lib.test_helpers import read_test_image_filefrom zerver.lib.upload import upload_message_attachmentfrom zerver.models import Client, Message, NamedUserGroup, UserPresencefrom zerver.models.channel_folders import ChannelFolder@@ -454,3 +455,18 @@ def regenerate_bot_api_key_test() -> dict[str, object]:bot = UserProfile.objects.filter(is_bot=True, realm=get_realm("zulip")).first()assert bot is not Nonereturn {"bot_id": bot.id}+++@openapi_param_value_generator(["/thumbnail/status/{realm_id_str}/{filename}:get"])+def check_thumbnail_status_for_uploaded_file() -> dict[str, object]:+ realm_id = ""+ filename = ""+ user_profile = helpers.example_user("iago")+ url = upload_message_attachment(+ "img.png", "image/png", read_test_image_file("img.png"), user_profile+ )[0]+ upload_path_parts = re.match(r"/user_uploads/(\d+)/(.*)", url)+ if upload_path_parts:+ realm_id = upload_path_parts[1]+ filename = upload_path_parts[2]+ return {"realm_id_str": realm_id, "filename": filename}diff --git a/zerver/openapi/python_examples.py b/zerver/openapi/python_examples.pyindex 908cefa3c7a..f1a6a3d84b4 100644--- a/zerver/openapi/python_examples.py+++ b/zerver/openapi/python_examples.py@@ -1722,6 +1722,30 @@ def upload_file(client: Client) -> None:validate_against_openapi_schema(result, "/user_uploads", "post", "200")+@openapi_test_function("/thumbnail/status/{realm_id_str}/{filename}:get")+def check_thumbnail_status(client: Client) -> None:+ path_to_file = os.path.join(ZULIP_DIR, "zerver", "tests", "images", "img.jpg")+ with open(path_to_file, "rb") as fp:+ result = client.upload_file(fp)++ uri = result["uri"]+ parts = uri.split("/")+ realm_id_str = parts[2]+ filename = "/".join(parts[3:])++ # {code_example|start}+ # Check thumbnail status.+ result = client.call_endpoint(+ url=f"/thumbnail/status/{realm_id_str}/{filename}",+ method="GET",+ )+ # {code_example|end}+ assert_success_response(result)+ validate_against_openapi_schema(+ result, "/thumbnail/status/{realm_id_str}/{filename}", "get", "200"+ )++@openapi_test_function("/users/me/{stream_id}/topics:get")def get_stream_topics(client: Client, stream_id: int) -> None:# {code_example|start}@@ -2080,6 +2104,7 @@ def test_invalid_stream_error(client: Client) -> None:def test_messages(client: Client, nonadmin_client: Client) -> None:+ check_thumbnail_status(client)render_message(client)message_id, content = send_message(client)set_message_edit_typing_status(client, message_id)diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex f0fa5f15bec..3e4d18d3333 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -10626,6 +10626,59 @@ paths:"url": "/user_uploads/1/4e/m2A3MSqFnWRLUf9SaPzQ0Up_/zulip.txt","filename": "zulip.txt",}+ /thumbnail/status/{realm_id_str}/{filename}:+ get:+ operationId: check-thumbnail-status+ summary: Check thumbnail status+ tags: ["messages"]+ description: |+ Check whether a thumbnail exists for a specific file uploaded by a user.+ This endpoint is intended to be polled by clients to determine when+ thumbnail generation is complete.++ **Changes**: New in Zulip 12.0 (feature level 479).+ parameters:+ - name: realm_id_str+ in: path+ description: |+ The realm ID component of the file's `path_id`. If the `path_id` is+ `1/4e/m2A3MSqFnWRLUf9SaPzQ0Up_/zulip.txt`, the `realm_id_str` would be `1`.+ schema:+ type: integer+ example: 1+ required: true+ - name: filename+ in: path+ description: |+ The file path component of the file's `path_id` (everything+ after the first `/`). If the `path_id` is+ `1/4e/m2A3MSqFnWRLUf9SaPzQ0Up_/zulip.txt`, the `filename`+ would be `4e/m2A3MSqFnWRLUf9SaPzQ0Up_/zulip.txt`.+ schema:+ type: string+ example: 4e/m2A3MSqFnWRLUf9SaPzQ0Up_/zulip.txt+ required: true+ responses:+ "200":+ description: Success.+ content:+ application/json:+ schema:+ allOf:+ - $ref: "#/components/schemas/JsonSuccessBase"+ - additionalProperties: false+ properties:+ result: {}+ msg: {}+ ignored_parameters_unsupported: {}+ has_thumbnail:+ type: boolean+ description: |+ A boolean indicating whether the thumbnail exists.+ required:+ - has_thumbnail+ example:+ {"msg": "", "result": "success", "has_thumbnail": true}/user_uploads/{realm_id_str}/{filename}:get:operationId: get-file-temporary-urldiff --git a/zerver/tests/test_thumbnail.py b/zerver/tests/test_thumbnail.pyindex e512d8c7498..e2c2802cb9d 100644--- a/zerver/tests/test_thumbnail.py+++ b/zerver/tests/test_thumbnail.py@@ -1004,3 +1004,72 @@ class TestThumbnailRetrieval(ZulipTestCase):),"100x75.webp",)+++class ThumbnailStatusEndpointTest(ZulipTestCase):+ def test_thumbnail_status_with_ready_thumbnails(self) -> None:+ hamlet = self.example_user("hamlet")+ self.login_user(hamlet)++ with self.thumbnail_formats(ThumbnailFormat("webp", 100, 75, animated=True)):+ with self.captureOnCommitCallbacks(execute=True):+ with get_test_image_file("animated_unequal_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"])++ result = self.client_get(f"/json/thumbnail/status/{path_id}")+ self.assert_json_success(result)+ self.assertEqual(result.json()["has_thumbnail"], True)++ def test_thumbnail_status_without_ready_thumbnails(self) -> None:+ hamlet = self.example_user("hamlet")+ self.login_user(hamlet)++ with self.thumbnail_formats(ThumbnailFormat("webp", 100, 75, animated=True)):+ # Don't execute callbacks, so thumbnails aren't generated+ with get_test_image_file("animated_unequal_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"])++ result = self.client_get(f"/json/thumbnail/status/{path_id}")+ self.assert_json_success(result)+ self.assertEqual(result.json()["has_thumbnail"], False)++ def test_thumbnail_status_for_non_image_file(self) -> None:+ hamlet = self.example_user("hamlet")+ self.login_user(hamlet)++ fp = StringIO("zulip text file!")+ fp.name = "zulip.txt"++ json_response = self.assert_json_success(+ self.client_post("/json/user_uploads", {"file": fp})+ )+ path_id = re.sub(r"/user_uploads/", "", json_response["url"])++ result = self.client_get(f"/json/thumbnail/status/{path_id}")+ self.assert_json_error(result, "Invalid attachment")++ def test_thumbnail_status_nonexistent_file(self) -> None:+ hamlet = self.example_user("hamlet")+ self.login_user(hamlet)++ result = self.client_get("/json/thumbnail/status/2/nonexistent/fake.gif")+ self.assert_json_error(result, "Invalid attachment")++ def test_thumbnail_status_without_access(self) -> None:+ hamlet = self.example_user("hamlet")+ iago = self.example_user("iago")++ path_id = f"{hamlet.realm_id}/31/4CBjtTLYZhk66pZrF8hnYGwc/img.gif"+ create_attachment("img.gif", path_id, "image/gif", b"gif_content", hamlet, hamlet.realm)++ # Iago is not a recipient of the uploaded file so they+ # should not be able to query its thumbnail status.+ self.login_user(iago)+ result = self.client_get(f"/json/thumbnail/status/{path_id}")+ self.assert_json_error(result, "Invalid attachment")diff --git a/zerver/views/thumbnail.py b/zerver/views/thumbnail.pyindex bd6e930e4a3..921243d1524 100644--- a/zerver/views/thumbnail.py+++ b/zerver/views/thumbnail.py@@ -2,9 +2,14 @@ import refrom django.contrib.auth.models import AnonymousUserfrom django.http import HttpRequest, HttpResponseBase, HttpResponseForbidden+from django.utils.translation import gettext as _-from zerver.lib.typed_endpoint import typed_endpoint-from zerver.models import UserProfile+from zerver.lib.attachments import validate_attachment_request+from zerver.lib.exceptions import JsonableError+from zerver.lib.response import json_success+from zerver.lib.thumbnail import missing_thumbnails+from zerver.lib.typed_endpoint import PathOnly, typed_endpoint+from zerver.models import ImageAttachment, UserProfilefrom zerver.views.upload import serve_file@@ -34,3 +39,32 @@ def backend_serve_thumbnail(# we cannot serve a "new" thumbnail for these requests; serve the# full-size file.return serve_file(request, maybe_user_profile, realm_id_str, path_id)+++@typed_endpoint+def check_thumbnail_status(+ request: HttpRequest,+ user_profile: UserProfile,+ *,+ realm_id_str: PathOnly[str],+ filename: PathOnly[str],+) -> HttpResponseBase:+ path_id = f"{realm_id_str}/{filename}"++ if not validate_attachment_request(user_profile, path_id)[0]:+ # Technically, there are 2 cases here:+ # * The user put something in their compose box that has the form+ # of an upload URL, but does not actually correspond to a previously+ # uploaded file. validate_attachment_request will return None.+ # * The user is polling thumbnail status for a file they don't have+ # permission to access. validate_attachment_request will return False.+ raise JsonableError(_("Invalid attachment"))++ try:+ image_attachment = ImageAttachment.objects.get(path_id=path_id)+ except ImageAttachment.DoesNotExist:+ raise JsonableError(_("Invalid attachment"))++ needed_thumbnails = missing_thumbnails(image_attachment)++ return json_success(request, data={"has_thumbnail": len(needed_thumbnails) == 0})diff --git a/zproject/urls.py b/zproject/urls.pyindex 21b4d244ab5..1598445da59 100644--- a/zproject/urls.py+++ b/zproject/urls.py@@ -206,7 +206,7 @@ from zerver.views.streams import (update_subscriptions_property,)from zerver.views.submessage import process_submessage-from zerver.views.thumbnail import backend_serve_thumbnail+from zerver.views.thumbnail import backend_serve_thumbnail, check_thumbnail_statusfrom zerver.views.tusd import handle_tusd_hookfrom zerver.views.typing import send_message_edit_notification_backend, send_notification_backendfrom zerver.views.unsubscribe import email_unsubscribe@@ -455,6 +455,11 @@ v1_api_and_json_patterns = [rest_path("typing", POST=send_notification_backend),# POST sends a message edit typing notificationrest_path("messages/<int:message_id>/typing", POST=send_message_edit_notification_backend),+ # Thumbnail metadata API+ rest_path(+ "thumbnail/status/<realm_id_str>/<path:filename>",+ GET=check_thumbnail_status,+ ),# user_uploads -> zerver.views.uploadrest_path("user_uploads", POST=upload_file_backend),rest_path(