participants.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. from django.contrib.auth import get_user_model
  2. from django.utils.translation import ugettext as _
  3. from misago.core.mail import build_mail, send_messages
  4. from .models import ThreadParticipant
  5. from .signals import remove_thread_participant
  6. def has_participants(thread):
  7. return thread.threadparticipant_set.exists()
  8. def make_participants_aware(user, thread):
  9. thread.participants_list = []
  10. thread.participant = None
  11. participants_qs = ThreadParticipant.objects.filter(thread=thread)
  12. participants_qs = participants_qs.select_related('user')
  13. for participant in participants_qs.order_by('-is_owner', 'user__slug'):
  14. participant.thread = thread
  15. thread.participants_list.append(participant)
  16. if participant.user == user:
  17. thread.participant = participant
  18. return thread.participants_list
  19. def set_owner(thread, user):
  20. """
  21. Remove user's ownership over thread
  22. """
  23. ThreadParticipant.objects.set_owner(thread, user)
  24. def set_users_unread_private_threads_sync(users):
  25. User = get_user_model()
  26. User.objects.filter(id__in=[u.pk for u in users]).update(
  27. sync_unread_private_threads=True
  28. )
  29. def add_participant(request, thread, user):
  30. """
  31. Shortcut for adding single participant to thread
  32. """
  33. add_participants(request, thread, [user])
  34. def add_participants(request, thread, users):
  35. """
  36. Add multiple participants to thread, set "recound private threads" flag on them
  37. notify them about being added to thread
  38. """
  39. ThreadParticipant.objects.add_participants(thread, users)
  40. set_users_unread_private_threads_sync(users)
  41. emails = []
  42. for user in users:
  43. emails.append(build_noticiation_email(request, thread, user))
  44. send_messages(emails)
  45. def build_noticiation_email(request, thread, user):
  46. subject = _('%(user)s has invited you to participate in private thread "%(thread)s"')
  47. subject_formats = {
  48. 'thread': thread.title,
  49. 'user': request.user.username
  50. }
  51. return build_mail(
  52. request,
  53. user,
  54. subject % subject_formats,
  55. 'misago/emails/privatethread/added',
  56. {
  57. 'thread': thread
  58. }
  59. )
  60. def remove_participant(thread, user):
  61. """
  62. Remove thread participant, set "recound private threads" flag on user
  63. """
  64. thread.threadparticipant_set.filter(user=user).delete()
  65. set_users_unread_private_threads_sync([user])
  66. remove_thread_participant.send(thread, user=user)