emailnotification.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from django.utils.translation import gettext as _
  2. from misago.acl import useracl
  3. from misago.core.mail import build_mail, send_messages
  4. from misago.threads.permissions import can_see_post, can_see_thread
  5. from . import PostingEndpoint, PostingMiddleware
  6. class EmailNotificationMiddleware(PostingMiddleware):
  7. def __init__(self, **kwargs):
  8. super().__init__(**kwargs)
  9. self.previous_last_post_on = self.thread.last_post_on
  10. def use_this_middleware(self):
  11. return self.mode == PostingEndpoint.REPLY
  12. def post_save(self, serializer):
  13. queryset = self.thread.subscription_set.filter(
  14. send_email=True,
  15. last_read_on__gte=self.previous_last_post_on,
  16. ).exclude(user=self.user).select_related('user')
  17. notifications = []
  18. for subscription in queryset.iterator():
  19. if self.subscriber_can_see_post(subscription.user):
  20. notifications.append(self.build_mail(subscription.user))
  21. if notifications:
  22. send_messages(notifications)
  23. def subscriber_can_see_post(self, subscriber):
  24. user_acl = useracl.get_user_acl(subscriber, self.request.cache_versions)
  25. see_thread = can_see_thread(user_acl, self.thread)
  26. see_post = can_see_post(user_acl, self.post)
  27. return see_thread and see_post
  28. def build_mail(self, subscriber):
  29. if subscriber.id == self.thread.starter_id:
  30. subject = _('%(user)s has replied to your thread "%(thread)s"')
  31. else:
  32. subject = _('%(user)s has replied to thread "%(thread)s" that you are watching')
  33. subject_formats = {'user': self.user.username, 'thread': self.thread.title}
  34. return build_mail(
  35. subscriber,
  36. subject % subject_formats,
  37. 'misago/emails/thread/reply',
  38. sender=self.user,
  39. context={
  40. "settings": self.request.settings,
  41. "thread": self.thread,
  42. "post": self.post,
  43. },
  44. )