Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

upload: Removing attachments removes thumbnails and .info files.

Alex Vandiver5cbbc7c05c7b
diff --git a/zerver/lib/upload/base.py b/zerver/lib/upload/base.py
index a4a0e69d096..6c9276766d4 100644
--- a/zerver/lib/upload/base.py
+++ b/zerver/lib/upload/base.py
@@ -48,6 +48,7 @@ class ZulipUploadBackend:
raise NotImplementedError
def delete_message_attachment(self, path_id: str) -> None:
+ """This must delete the attachment, any adjacent .info files, and any thumbnails."""
raise NotImplementedError
def delete_message_attachments(self, path_ids: list[str]) -> None:
diff --git a/zerver/lib/upload/local.py b/zerver/lib/upload/local.py
index 9fead6517bd..a3bfb833aec 100644
--- a/zerver/lib/upload/local.py
+++ b/zerver/lib/upload/local.py
@@ -48,23 +48,28 @@ def read_local_file(type: Literal["avatars", "files"], path: str) -> Iterator[by
yield from iter(lambda: f.read(4 * 1024 * 1024), b"")
-def delete_local_file(type: Literal["avatars", "files"], path: str) -> None:
+def delete_local_file(
+ type: Literal["avatars", "files"], path: str, *, directory: bool = False
+) -> None:
file_path = os.path.join(assert_is_not_none(settings.LOCAL_UPLOADS_DIR), type, path)
assert_is_local_storage_path(type, file_path)
- if not os.path.isfile(file_path):
- return
+ def prune_empty_dirs(file_path: str) -> None:
+ # Remove as many directories up the tree as are now empty
+ directory = os.path.dirname(file_path)
+ while directory != settings.LOCAL_UPLOADS_DIR:
+ try:
+ os.rmdir(directory)
+ directory = os.path.dirname(directory)
+ except OSError:
+ break
- os.remove(file_path)
-
- # Remove as many directories up the tree as are now empty
- directory = os.path.dirname(file_path)
- while directory != settings.LOCAL_UPLOADS_DIR:
- try:
- os.rmdir(directory)
- directory = os.path.dirname(directory)
- except OSError:
- break
+ if directory and os.path.isdir(file_path):
+ shutil.rmtree(file_path)
+ prune_empty_dirs(os.path.dirname(file_path))
+ elif os.path.isfile(file_path):
+ os.remove(file_path)
+ prune_empty_dirs(file_path)
class LocalUploadBackend(ZulipUploadBackend):
@@ -115,6 +120,8 @@ class LocalUploadBackend(ZulipUploadBackend):
@override
def delete_message_attachment(self, path_id: str) -> None:
delete_local_file("files", path_id)
+ delete_local_file("files", f"{path_id}.info")
+ delete_local_file("files", f"thumbnail/{path_id}/", directory=True)
@override
def all_message_attachments(
diff --git a/zerver/lib/upload/s3.py b/zerver/lib/upload/s3.py
index f580d68e424..f83c0e488aa 100644
--- a/zerver/lib/upload/s3.py
+++ b/zerver/lib/upload/s3.py
@@ -290,12 +290,21 @@ class S3UploadBackend(ZulipUploadBackend):
@override
def delete_message_attachment(self, path_id: str) -> None:
- self.delete_file_from_s3(path_id, self.uploads_bucket)
+ self.delete_message_attachments([path_id])
@override
def delete_message_attachments(self, path_ids: list[str]) -> None:
+ all_paths = path_ids.copy()
+ for path_id in path_ids:
+ all_paths.append(f"{path_id}.info")
+ all_paths += [
+ thumb_path
+ for thumb_path, _ in self.all_message_attachments(
+ include_thumbnails=True, prefix=f"thumbnail/{path_id}/"
+ )
+ ]
self.uploads_bucket.delete_objects(
- Delete={"Objects": [{"Key": path_id} for path_id in path_ids]}
+ Delete={"Objects": [{"Key": path_id} for path_id in all_paths], "Quiet": True},
)
@override
diff --git a/zerver/tests/test_delete_unclaimed_attachments.py b/zerver/tests/test_delete_unclaimed_attachments.py
index 4e12100cda5..83aa726c303 100644
--- a/zerver/tests/test_delete_unclaimed_attachments.py
+++ b/zerver/tests/test_delete_unclaimed_attachments.py
@@ -3,6 +3,7 @@ import re
from datetime import datetime, timedelta
from unittest.mock import patch
+import orjson
import time_machine
from django.conf import settings
from django.utils.timezone import now as timezone_now
@@ -109,6 +110,20 @@ class UnclaimedAttachmentTest(UploadSerializeMixin, ZulipTestCase):
)
)
+ def test_delete_info_file(self) -> None:
+ attachment = self.make_attachment("text.txt")
+ assert settings.LOCAL_FILES_DIR
+ info_file = os.path.join(settings.LOCAL_FILES_DIR, attachment.path_id + ".info")
+ with open(info_file, "wb") as f:
+ f.write(orjson.dumps({"id": attachment.path_id}))
+ self.assertTrue(os.path.isfile(info_file))
+
+ do_delete_old_unclaimed_attachments(3)
+ self.assertTrue(os.path.isfile(info_file))
+
+ do_delete_old_unclaimed_attachments(1)
+ self.assertFalse(os.path.isfile(info_file))
+
def test_delete_unused_upload(self) -> None:
unused_attachment = self.make_attachment("text.txt")
self.assert_exists(
diff --git a/zerver/tests/test_upload_local.py b/zerver/tests/test_upload_local.py
index bd3027bf607..2d6ee55128b 100644
--- a/zerver/tests/test_upload_local.py
+++ b/zerver/tests/test_upload_local.py
@@ -1,6 +1,6 @@
import os
import re
-from io import BytesIO, StringIO
+from io import BytesIO
from urllib.parse import urlsplit
import pyvips
@@ -10,7 +10,12 @@ import zerver.lib.upload
from zerver.lib.avatar_hash import user_avatar_path
from zerver.lib.test_classes import UploadSerializeMixin, ZulipTestCase
from zerver.lib.test_helpers import get_test_image_file, read_test_image_file
-from zerver.lib.thumbnail import DEFAULT_EMOJI_SIZE, MEDIUM_AVATAR_SIZE, resize_avatar
+from zerver.lib.thumbnail import (
+ DEFAULT_EMOJI_SIZE,
+ MEDIUM_AVATAR_SIZE,
+ ThumbnailFormat,
+ resize_avatar,
+)
from zerver.lib.upload import (
all_message_attachments,
attachment_source,
@@ -87,20 +92,36 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
def test_delete_message_attachment(self) -> None:
self.login("hamlet")
- fp = StringIO("zulip!")
- fp.name = "zulip.txt"
- result = self.client_post("/json/user_uploads", {"file": fp})
- response_dict = self.assert_json_success(result)
- self.assertEqual(response_dict["uri"], response_dict["url"])
- path_id = re.sub(r"/user_uploads/", "", response_dict["url"])
+ # Upload an image which will generate multiple thumbnails
+ webp_anim = ThumbnailFormat("webp", 100, 75, animated=True)
+ webp_still = ThumbnailFormat("webp", 100, 75, animated=False)
+ with (
+ self.thumbnail_formats(webp_anim, webp_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
assert settings.LOCAL_FILES_DIR is not None
file_path = os.path.join(settings.LOCAL_FILES_DIR, path_id)
+ thumbnail_base = os.path.join(settings.LOCAL_FILES_DIR, "thumbnail", path_id)
+ thumbnail_anim = os.path.join(thumbnail_base, str(webp_anim))
+ thumbnail_still = os.path.join(thumbnail_base, str(webp_still))
self.assertTrue(os.path.isfile(file_path))
+ self.assertTrue(os.path.isdir(thumbnail_base))
+ self.assertTrue(os.path.isfile(thumbnail_anim))
+ self.assertTrue(os.path.isfile(thumbnail_still))
delete_message_attachment(path_id)
self.assertFalse(os.path.isfile(file_path))
+ self.assertFalse(os.path.isdir(thumbnail_base))
+ self.assertFalse(os.path.isfile(thumbnail_anim))
+ self.assertFalse(os.path.isfile(thumbnail_still))
def test_delete_message_attachments(self) -> None:
assert settings.LOCAL_UPLOADS_DIR is not None
diff --git a/zerver/tests/test_upload_s3.py b/zerver/tests/test_upload_s3.py
index 2802f70ae23..dbf00fe2b9e 100644
--- a/zerver/tests/test_upload_s3.py
+++ b/zerver/tests/test_upload_s3.py
@@ -152,14 +152,31 @@ class S3Test(ZulipTestCase):
def test_delete_message_attachment(self) -> None:
bucket = create_s3_buckets(settings.S3_AUTH_UPLOADS_BUCKET)[0]
- user_profile = self.example_user("hamlet")
- url = upload_message_attachment("dummy.txt", "text/plain", b"zulip!", user_profile)[0]
+ self.login("hamlet")
+ # Upload an image which will generate multiple thumbnails
+ webp_anim = ThumbnailFormat("webp", 100, 75, animated=True)
+ webp_still = ThumbnailFormat("webp", 100, 75, animated=False)
+ with (
+ self.thumbnail_formats(webp_anim, webp_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
- path_id = re.sub(r"/user_uploads/", "", url)
self.assertIsNotNone(bucket.Object(path_id).get())
+ self.assertIsNotNone(bucket.Object(f"thumbnail/{path_id}/{webp_anim}").get())
+ self.assertIsNotNone(bucket.Object(f"thumbnail/{path_id}/{webp_still}").get())
delete_message_attachment(path_id)
with self.assertRaises(botocore.exceptions.ClientError):
bucket.Object(path_id).load()
+ with self.assertRaises(botocore.exceptions.ClientError):
+ bucket.Object(f"thumbnail/{path_id}/{webp_anim}").load()
+ with self.assertRaises(botocore.exceptions.ClientError):
+ bucket.Object(f"thumbnail/{path_id}/{webp_still}").load()
@use_s3_backend
def test_delete_message_attachments(self) -> None: