emailnotification.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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__gt=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. return can_see_thread(subscriber, self.thread) and can_see_post(subscriber, self.post)
  24. def build_mail(self, subscriber):
  25. if subscriber.id == self.thread.starter_id:
  26. subject = _('%(user)s has replied to your thread "%(thread)s"')
  27. else:
  28. subject = _('%(user)s has replied to thread "%(thread)s" that you are watching')
  29. subject_formats = {
  30. 'user': self.user.username,
  31. 'thread': self.thread.title
  32. }
  33. return build_mail(
  34. self.request,
  35. subscriber,
  36. subject % subject_formats,
  37. 'misago/emails/thread/reply',
  38. {
  39. 'thread': self.thread,
  40. 'post': self.post
  41. }
  42. )