subscribe.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 == UserModel.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 == UserModel.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,
  33. is_event=False,
  34. ).exclude(
  35. pk=self.post.pk,
  36. )
  37. if posts_queryset.exists():
  38. return
  39. self.user.subscription_set.create(
  40. category=self.thread.category,
  41. thread=self.thread,
  42. send_email=self.user.subscribe_to_replied_threads == UserModel.SUBSCRIPTION_ALL,
  43. )