subscribe.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from django.contrib.auth import get_user_model
  2. from . import PostingEndpoint, PostingMiddleware
  3. from ...models import Subscription
  4. UserModel = get_user_model()
  5. SUBSCRIBE_NONE = UserModel.AUTO_SUBSCRIBE_NONE
  6. SUBSCRIBE_ALL = UserModel.AUTO_SUBSCRIBE_NOTIFY_AND_EMAIL
  7. class SubscribeMiddleware(PostingMiddleware):
  8. def use_this_middleware(self):
  9. return self.mode != PostingEndpoint.EDIT
  10. def post_save(self, serializer):
  11. self.subscribe_new_thread()
  12. self.subscribe_replied_thread()
  13. def subscribe_new_thread(self):
  14. if self.mode != PostingEndpoint.START:
  15. return
  16. if self.user.subscribe_to_started_threads == SUBSCRIBE_NONE:
  17. return
  18. self.user.subscription_set.create(
  19. category=self.thread.category,
  20. thread=self.thread,
  21. send_email=self.user.subscribe_to_started_threads == SUBSCRIBE_ALL
  22. )
  23. def subscribe_replied_thread(self):
  24. if self.mode != PostingEndpoint.REPLY:
  25. return
  26. if self.user.subscribe_to_replied_threads == SUBSCRIBE_NONE:
  27. return
  28. try:
  29. subscription = self.user.subscription_set.get(thread=self.thread)
  30. return
  31. except Subscription.DoesNotExist:
  32. pass
  33. # we are replying to thread again?
  34. if self.user.post_set.filter(thread=self.thread).count() > 1:
  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 == SUBSCRIBE_ALL
  40. )