emailnotification.py 1.8 KB

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