attachments.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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, PostingInterrupt, PostingMiddleware
  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(data=self.request.data, context={
  13. 'mode': self.mode,
  14. 'user': self.user,
  15. 'post': self.post,
  16. })
  17. def save(self, serializer):
  18. serializer.save()
  19. class AttachmentsSerializer(serializers.Serializer):
  20. attachments = serializers.ListField(
  21. child=serializers.IntegerField(),
  22. required=False
  23. )
  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. new_attachments = self.get_new_attachments(self.context['user'], ids)
  33. if not attachments and not new_attachments:
  34. return [] # no attachments
  35. # clean existing attachments
  36. for attachment in attachments:
  37. if attachment.pk in ids:
  38. self.final_attachments.append(attachment)
  39. else:
  40. if attachment.acl['can_delete']:
  41. self.update_attachments = True
  42. self.removed_attachments.append(attachment)
  43. else:
  44. message = _("You don't have permission to remove \"%(attachment)s\" attachment.")
  45. raise serializers.ValidationError(message % {'attachment': attachment.filename})
  46. if new_attachments:
  47. self.update_attachments = True
  48. self.final_attachments += new_attachments
  49. self.final_attachments.sort(key=lambda a: a.pk, reverse=True)
  50. def get_initial_attachments(self, mode, user, post):
  51. attachments = []
  52. if mode == PostingEndpoint.EDIT:
  53. queryset = post.attachment_set.select_related('filetype')
  54. attachments = list(queryset)
  55. add_acl(user, attachments)
  56. return attachments
  57. def get_new_attachments(self, user, ids):
  58. if not ids:
  59. return []
  60. queryset = user.attachment_set.select_related('filetype').filter(
  61. post__isnull=True,
  62. id__in=ids
  63. )
  64. return list(queryset)
  65. def save(self):
  66. if not self.update_attachments:
  67. return
  68. if self.removed_attachments:
  69. for attachment in self.removed_attachments:
  70. attachment.delete_files()
  71. self.context['post'].attachment_set.filter(
  72. id__in=[a.id for a in self.removed_attachments]
  73. ).delete()
  74. if self.final_attachments:
  75. # sort final attachments by id, descending
  76. self.final_attachments.sort(key=lambda a: a.pk, reverse=True)
  77. self.context['user'].attachment_set.filter(
  78. id__in=[a.id for a in self.final_attachments]
  79. ).update(post=self.context['post'])
  80. self.sync_attachments_cache(self.context['post'], self.final_attachments)
  81. def sync_attachments_cache(self, post, attachments):
  82. if attachments:
  83. post.attachments_cache = AttachmentSerializer(attachments, many=True).data
  84. for attachment in post.attachments_cache:
  85. del attachment['acl']
  86. del attachment['post']
  87. del attachment['uploader_ip']
  88. else:
  89. post.attachments_cache = None
  90. post.update_fields.append('attachments_cache')
  91. def validate_attachments_count(data):
  92. total_attachments = len(data)
  93. if total_attachments > settings.MISAGO_POST_ATTACHMENTS_LIMIT:
  94. message = ungettext(
  95. "You can't attach more than %(limit_value)s file to single post (added %(show_value)s).",
  96. "You can't attach more than %(limit_value)s flies to single post (added %(show_value)s).",
  97. settings.MISAGO_POST_ATTACHMENTS_LIMIT)
  98. raise serializers.ValidationError(message % {
  99. 'limit_value': settings.MISAGO_POST_ATTACHMENTS_LIMIT,
  100. 'show_value': total_attachments
  101. })