floodprotection.py 1.5 KB

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