subscribe.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from django.contrib.auth import get_user_model
  2. from . import PostingEndpoint, PostingMiddleware
  3. from ...models import Subscription
  4. User = get_user_model()
  5. class SubscribeMiddleware(PostingMiddleware):
  6. def use_this_middleware(self):
  7. return self.mode != PostingEndpoint.EDIT
  8. def post_save(self, serializer):
  9. self.subscribe_new_thread()
  10. self.subscribe_replied_thread()
  11. def subscribe_new_thread(self):
  12. if self.mode != PostingEndpoint.START:
  13. return
  14. if self.user.subscribe_to_started_threads == User.SUBSCRIPTION_NONE:
  15. return
  16. self.user.subscription_set.create(
  17. category=self.thread.category,
  18. thread=self.thread,
  19. send_email=self.user.subscribe_to_started_threads == User.SUBSCRIPTION_ALL,
  20. )
  21. def subscribe_replied_thread(self):
  22. if self.mode != PostingEndpoint.REPLY:
  23. return
  24. if self.user.subscribe_to_replied_threads == User.SUBSCRIPTION_NONE:
  25. return
  26. try:
  27. return self.user.subscription_set.get(thread=self.thread)
  28. except Subscription.DoesNotExist:
  29. pass
  30. # posts user's posts in this thread, minus events and current post
  31. posts_queryset = self.user.post_set.filter(
  32. thread=self.thread, is_event=False
  33. ).exclude(pk=self.post.pk)
  34. if posts_queryset.exists():
  35. return
  36. self.user.subscription_set.create(
  37. category=self.thread.category,
  38. thread=self.thread,
  39. send_email=self.user.subscribe_to_replied_threads == User.SUBSCRIPTION_ALL,
  40. )