Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
attachments: Removing an Attachment should remove its ImageAttachment.
Alex Vandiver415cd20014a7
diff --git a/zerver/lib/attachments.py b/zerver/lib/attachments.pyindex 537cdf6b9a3..89b10e23db1 100644--- a/zerver/lib/attachments.py+++ b/zerver/lib/attachments.py@@ -14,6 +14,7 @@ from zerver.lib.user_groups import get_recursive_membership_groupsfrom zerver.models import (ArchivedAttachment,Attachment,+ ImageAttachment,Message,Realm,Recipient,@@ -49,6 +50,7 @@ def remove_attachment(user_profile: UserProfile, attachment: Attachment) -> Noneraise JsonableError(_("An error occurred while deleting the attachment. Please try again later."))+ ImageAttachment.objects.filter(path_id=attachment.path_id).delete()attachment.delete()diff --git a/zerver/migrations/0772_clean_up_imageattachments.py b/zerver/migrations/0772_clean_up_imageattachments.pynew file mode 100644index 00000000000..254bd4942b6--- /dev/null+++ b/zerver/migrations/0772_clean_up_imageattachments.py@@ -0,0 +1,60 @@+from django.db import connection, migrations+from django.db.backends.base.schema import BaseDatabaseSchemaEditor+from django.db.migrations.state import StateApps+from django.db.models import Exists, OuterRef+from psycopg2.sql import SQL, Identifier+++def delete_unattached_imageattachments(+ apps: StateApps, schema_editor: BaseDatabaseSchemaEditor+) -> None:+ ArchivedAttachment = apps.get_model("zerver", "ArchivedAttachment")+ Attachment = apps.get_model("zerver", "Attachment")+ ImageAttachment = apps.get_model("zerver", "ImageAttachment")++ table = ImageAttachment._meta.db_table+ with connection.cursor() as cursor:+ cursor.execute(SQL("SELECT MIN(id), MAX(id) FROM {}").format(Identifier(table)))+ (min_id, max_id) = cursor.fetchone()+ if min_id is None:+ return++ q = ImageAttachment.objects.alias(+ has_attachment=Exists(Attachment.objects.filter(path_id=OuterRef("path_id"))),+ has_archived_attachment=Exists(+ ArchivedAttachment.objects.filter(path_id=OuterRef("path_id"))+ ),+ ).filter(+ has_attachment=False,+ has_archived_attachment=False,+ )+ # The majority of these rows will have attachment rows still,+ # so we will only be deleting a small number of+ # image_attachment rows per batch; the lookups for attachment+ # and archived_attachment are both by unique path_id, so this+ # query will still be fast.+ batch_size = 10000+ while min_id <= max_id:+ lower = min_id+ upper = min_id + batch_size+ q.filter(id__gte=lower, id__lt=upper).delete()+ min_id = upper+ if min_id > max_id:+ cursor.execute(SQL("SELECT MAX(id) FROM {}").format(Identifier(table)))+ (max_id,) = cursor.fetchone()+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("zerver", "0771_alter_realmemoji_author"),+ ]++ operations = [+ migrations.RunPython(+ delete_unattached_imageattachments,+ reverse_code=migrations.RunPython.noop,+ elidable=True,+ ),+ ]diff --git a/zerver/tests/test_attachments.py b/zerver/tests/test_attachments.pyindex cbc594444d3..eb9ec170e99 100644--- a/zerver/tests/test_attachments.py+++ b/zerver/tests/test_attachments.py@@ -1,3 +1,4 @@+import refrom typing import Anyfrom unittest import mock@@ -5,7 +6,9 @@ from typing_extensions import overridefrom zerver.lib.attachments import user_attachmentsfrom zerver.lib.test_classes import ZulipTestCase-from zerver.models import Attachment+from zerver.lib.test_helpers import get_test_image_file+from zerver.lib.thumbnail import ThumbnailFormat+from zerver.models import Attachment, ImageAttachmentclass AttachmentsTests(ZulipTestCase):@@ -49,6 +52,26 @@ class AttachmentsTests(ZulipTestCase):attachments = user_attachments(user_profile)self.assertEqual(attachments, [])+ @mock.patch("zerver.lib.attachments.delete_message_attachment")+ def test_remove_imageattachment(self, ignored: Any) -> None:+ self.login_user(self.example_user("hamlet"))+ with (+ self.thumbnail_formats(ThumbnailFormat("webp", 100, 75, animated=True)),+ get_test_image_file("img.png") as image_file,+ ):+ response = self.assert_json_success(+ self.client_post("/json/user_uploads", {"file": image_file})+ )++ path_id = re.sub(r"/user_uploads/", "", response["url"])+ self.assertEqual(Attachment.objects.filter(path_id=path_id).count(), 1)+ self.assertEqual(ImageAttachment.objects.filter(path_id=path_id).count(), 1)+ attachment = Attachment.objects.get(path_id=path_id)+ result = self.client_delete(f"/json/attachments/{attachment.id}")+ self.assert_json_success(result)+ self.assertEqual(Attachment.objects.filter(path_id=path_id).count(), 0)+ self.assertEqual(ImageAttachment.objects.filter(path_id=path_id).count(), 0)+def test_list_another_user(self) -> None:user_profile = self.example_user("iago")self.login_user(user_profile)diff --git a/zerver/tests/test_delete_unclaimed_attachments.py b/zerver/tests/test_delete_unclaimed_attachments.pyindex 83aa726c303..f232dd9590e 100644--- a/zerver/tests/test_delete_unclaimed_attachments.py+++ b/zerver/tests/test_delete_unclaimed_attachments.py@@ -15,7 +15,7 @@ from zerver.lib.retention import clean_archived_datafrom zerver.lib.test_classes import UploadSerializeMixin, ZulipTestCasefrom zerver.lib.test_helpers import get_test_image_filefrom zerver.lib.thumbnail import ThumbnailFormat-from zerver.models import ArchivedAttachment, Attachment, Message, UserProfile+from zerver.models import ArchivedAttachment, Attachment, ImageAttachment, Message, UserProfilefrom zerver.models.clients import get_client@@ -44,6 +44,7 @@ class UnclaimedAttachmentTest(UploadSerializeMixin, ZulipTestCase):has_file: bool,has_attachment: bool,has_archived_attachment: bool,+ has_imageattachment: bool = False,) -> None:assert settings.LOCAL_FILES_DIRself.assertEqual( # File existence on disk@@ -55,6 +56,10 @@ class UnclaimedAttachmentTest(UploadSerializeMixin, ZulipTestCase):self.assertEqual( # ArchivedAttachment rowArchivedAttachment.objects.filter(id=attachment.id).exists(), has_archived_attachment)+ self.assertEqual( # ImageAttachment row+ ImageAttachment.objects.filter(path_id=attachment.path_id).exists(),+ has_imageattachment,+ )def test_delete_unused_thumbnails(self) -> None:assert settings.LOCAL_FILES_DIR@@ -62,7 +67,11 @@ class UnclaimedAttachmentTest(UploadSerializeMixin, ZulipTestCase):unused_attachment = self.make_attachment("img.png")self.assert_exists(- unused_attachment, has_file=True, has_attachment=True, has_archived_attachment=False+ unused_attachment,+ has_file=True,+ has_attachment=True,+ has_archived_attachment=False,+ has_imageattachment=True,)# It also has thumbnails@@ -83,7 +92,11 @@ class UnclaimedAttachmentTest(UploadSerializeMixin, ZulipTestCase):# If we have 3 weeks of grace, nothing happensdo_delete_old_unclaimed_attachments(3)self.assert_exists(- unused_attachment, has_file=True, has_attachment=True, has_archived_attachment=False+ unused_attachment,+ has_file=True,+ has_attachment=True,+ has_archived_attachment=False,+ has_imageattachment=True,)self.assertTrue(os.path.isdir(@@ -102,7 +115,11 @@ class UnclaimedAttachmentTest(UploadSerializeMixin, ZulipTestCase):# If we have 1 weeks of grace, the Attachment is deleted, and so is the file on diskdo_delete_old_unclaimed_attachments(1)self.assert_exists(- unused_attachment, has_file=False, has_attachment=False, has_archived_attachment=False+ unused_attachment,+ has_file=False,+ has_attachment=False,+ has_archived_attachment=False,+ has_imageattachment=False,)self.assertFalse(os.path.exists(diff --git a/zerver/views/attachments.py b/zerver/views/attachments.pyindex 7fb88a90742..2997888f611 100644--- a/zerver/views/attachments.py+++ b/zerver/views/attachments.py@@ -1,3 +1,4 @@+from django.db import transactionfrom django.http import HttpRequest, HttpResponsefrom zerver.actions.uploads import notify_attachment_update@@ -16,6 +17,7 @@ def list_by_user(request: HttpRequest, user_profile: UserProfile) -> HttpRespons)[email protected](durable=True)def remove(request: HttpRequest, user_profile: UserProfile, attachment_id: int) -> HttpResponse:attachment = access_attachment_by_id(user_profile, attachment_id, needs_owner=True)remove_attachment(user_profile, attachment)