floodprotection.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from datetime import timedelta
  2. from django.utils import timezone
  3. from django.utils.translation import gettext as _
  4. from . import PostingEndpoint, PostingInterrupt, PostingMiddleware
  5. from ....conf import settings
  6. MIN_POSTING_PAUSE = 3
  7. class FloodProtectionMiddleware(PostingMiddleware):
  8. def use_this_middleware(self):
  9. return (
  10. not self.user_acl["can_omit_flood_protection"]
  11. and self.mode != PostingEndpoint.EDIT
  12. )
  13. def interrupt_posting(self, serializer):
  14. now = timezone.now()
  15. if self.user.last_posted_on:
  16. previous_post = now - self.user.last_posted_on
  17. if previous_post.total_seconds() < MIN_POSTING_PAUSE:
  18. raise PostingInterrupt(
  19. _("You can't post message so quickly after previous one.")
  20. )
  21. self.user.last_posted_on = timezone.now()
  22. self.user.update_fields.append("last_posted_on")
  23. if settings.MISAGO_HOURLY_POST_LIMIT:
  24. cutoff = now - timedelta(hours=24)
  25. if self.is_limit_exceeded(cutoff, settings.MISAGO_HOURLY_POST_LIMIT):
  26. raise PostingInterrupt(_("Your account has excceed hourly post limit."))
  27. if settings.MISAGO_DIALY_POST_LIMIT:
  28. cutoff = now - timedelta(hours=1)
  29. if self.is_limit_exceeded(cutoff, settings.MISAGO_DIALY_POST_LIMIT):
  30. raise PostingInterrupt(_("Your account has excceed dialy post limit."))
  31. def is_limit_exceeded(self, cutoff, limit):
  32. return self.user.post_set.filter(posted_on__gte=cutoff).count() >= limit