subscribe.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from django.contrib.auth import get_user_model
  2. from misago.threads.models import Subscription
  3. from . import PostingEndpoint, PostingMiddleware
  4. UserModel = 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 == UserModel.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
  20. == UserModel.SUBSCRIPTION_ALL,
  21. )
  22. def subscribe_replied_thread(self):
  23. if self.mode != PostingEndpoint.REPLY:
  24. return
  25. if self.user.subscribe_to_replied_threads == UserModel.SUBSCRIPTION_NONE:
  26. return
  27. try:
  28. return self.user.subscription_set.get(thread=self.thread)
  29. except Subscription.DoesNotExist:
  30. pass
  31. # posts user's posts in this thread, minus events and current post
  32. posts_queryset = self.user.post_set.filter(
  33. thread=self.thread, is_event=False
  34. ).exclude(pk=self.post.pk)
  35. if posts_queryset.exists():
  36. return
  37. self.user.subscription_set.create(
  38. category=self.thread.category,
  39. thread=self.thread,
  40. send_email=self.user.subscribe_to_replied_threads
  41. == UserModel.SUBSCRIPTION_ALL,
  42. )