attachments.py 4.6 KB

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