attachments.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. from django.utils.translation import gettext as _
  2. from django.utils.translation import ngettext
  3. from rest_framework import serializers
  4. from rest_framework.fields import empty
  5. from . import PostingEndpoint, PostingMiddleware
  6. from ....acl.objectacl import add_acl_to_obj
  7. from ...serializers import AttachmentSerializer
  8. class AttachmentsMiddleware(PostingMiddleware):
  9. def use_this_middleware(self):
  10. return bool(self.user_acl["max_attachment_size"])
  11. def get_serializer(self):
  12. return AttachmentsSerializer(
  13. data=self.request.data,
  14. context={
  15. "mode": self.mode,
  16. "user": self.user,
  17. "user_acl": self.user_acl,
  18. "post": self.post,
  19. "settings": self.settings,
  20. },
  21. )
  22. def save(self, serializer):
  23. serializer.save()
  24. class AttachmentsSerializer(serializers.Serializer):
  25. attachments = serializers.ListField(
  26. child=serializers.IntegerField(), required=False
  27. )
  28. def __init__(self, *args, **kwargs):
  29. self.update_attachments = False
  30. self.removed_attachments = []
  31. self.final_attachments = []
  32. super().__init__(*args, **kwargs)
  33. def validate_attachments(self, ids):
  34. ids = list(set(ids))
  35. validate_attachments_count(ids, self.context["settings"])
  36. attachments = self.get_initial_attachments()
  37. new_attachments = self.get_new_attachments(ids)
  38. if not attachments and not new_attachments:
  39. return [] # no attachments
  40. # clean existing attachments
  41. for attachment in attachments:
  42. if attachment.pk in ids:
  43. self.final_attachments.append(attachment)
  44. else:
  45. if attachment.acl["can_delete"]:
  46. self.update_attachments = True
  47. self.removed_attachments.append(attachment)
  48. else:
  49. message = _(
  50. "You don't have permission to remove "
  51. '"%(attachment)s" attachment.'
  52. )
  53. raise serializers.ValidationError(
  54. message % {"attachment": attachment.filename}
  55. )
  56. if new_attachments:
  57. self.update_attachments = True
  58. self.final_attachments += new_attachments
  59. self.final_attachments.sort(key=lambda a: a.pk, reverse=True)
  60. def get_initial_attachments(self):
  61. attachments = []
  62. if self.context["mode"] == PostingEndpoint.EDIT:
  63. queryset = self.context["post"].attachment_set.select_related("filetype")
  64. attachments = list(queryset)
  65. add_acl_to_obj(self.context["user_acl"], attachments)
  66. return attachments
  67. def get_new_attachments(self, ids):
  68. if not ids:
  69. return []
  70. queryset = (
  71. self.context["user"]
  72. .attachment_set.select_related("filetype")
  73. .filter(post__isnull=True, id__in=ids)
  74. )
  75. return list(queryset)
  76. def save(self):
  77. if not self.update_attachments:
  78. return
  79. if self.removed_attachments:
  80. for attachment in self.removed_attachments:
  81. attachment.delete_files()
  82. self.context["post"].attachment_set.filter(
  83. id__in=[a.id for a in self.removed_attachments]
  84. ).delete()
  85. if self.final_attachments:
  86. # sort final attachments by id, descending
  87. self.final_attachments.sort(key=lambda a: a.pk, reverse=True)
  88. self.context["user"].attachment_set.filter(
  89. id__in=[a.id for a in self.final_attachments]
  90. ).update(post=self.context["post"])
  91. self.sync_attachments_cache(self.context["post"], self.final_attachments)
  92. def sync_attachments_cache(self, post, attachments):
  93. if attachments:
  94. post.attachments_cache = AttachmentSerializer(attachments, many=True).data
  95. for attachment in post.attachments_cache:
  96. del attachment["acl"]
  97. del attachment["post"]
  98. else:
  99. post.attachments_cache = None
  100. post.update_fields.append("attachments_cache")
  101. def validate_attachments_count(data, settings):
  102. total_attachments = len(data)
  103. if total_attachments > settings.post_attachments_limit:
  104. # pylint: disable=line-too-long
  105. message = ngettext(
  106. "You can't attach more than %(limit_value)s file to single post (added %(show_value)s).",
  107. "You can't attach more than %(limit_value)s flies to single post (added %(show_value)s).",
  108. settings.post_attachments_limit,
  109. )
  110. raise serializers.ValidationError(
  111. message
  112. % {
  113. "limit_value": settings.post_attachments_limit,
  114. "show_value": total_attachments,
  115. }
  116. )