emailnotification.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from django.utils.translation import ugettext as _
  2. from misago.core.mail import build_mail, send_messages
  3. from . import PostingEndpoint, PostingMiddleware
  4. from ...permissions.threads import can_see_post, can_see_thread
  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,
  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 = {
  32. 'user': self.user.username,
  33. 'thread': self.thread.title
  34. }
  35. return build_mail(
  36. self.request,
  37. subscriber,
  38. subject % subject_formats,
  39. 'misago/emails/thread/reply',
  40. {
  41. 'thread': self.thread,
  42. 'post': self.post
  43. }
  44. )