emailnotification.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from django.utils.translation import ugettext 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(EmailNotificationMiddleware, self).__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, last_read_on__gte=self.previous_last_post_on
  14. ).exclude(user=self.user).select_related('user')
  15. notifications = []
  16. for subscription in queryset.iterator():
  17. if self.notify_user_of_post(subscription.user):
  18. notifications.append(self.build_mail(subscription.user))
  19. if notifications:
  20. send_messages(notifications)
  21. def notify_user_of_post(self, subscriber):
  22. see_thread = can_see_thread(subscriber, self.thread)
  23. see_post = can_see_post(subscriber, self.post)
  24. return see_thread and see_post
  25. def build_mail(self, subscriber):
  26. if subscriber.id == self.thread.starter_id:
  27. subject = _('%(user)s has replied to your thread "%(thread)s"')
  28. else:
  29. subject = _('%(user)s has replied to thread "%(thread)s" that you are watching')
  30. subject_formats = {'user': self.user.username, 'thread': self.thread.title}
  31. return build_mail(
  32. self.request, subscriber, subject % subject_formats, 'misago/emails/thread/reply',
  33. {'thread': self.thread,
  34. 'post': self.post}
  35. )