api.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from django.db.models import F
  2. from django.db import transaction
  3. from django.utils.html import escape
  4. from misago.notifications.utils import hash_trigger
  5. __all__ = [
  6. 'notify_user',
  7. 'read_user_notification',
  8. 'read_all_user_alerts',
  9. 'assert_real_new_notifications_count',
  10. ]
  11. def notify_user(user, message, url, trigger, formats=None, sender=None,
  12. update_user=True):
  13. from misago.notifications.models import Notification
  14. message_escaped = escape(message)
  15. if formats:
  16. final_formats = {}
  17. for format, replace in formats.items():
  18. final_formats[format] = '<strong>%s</strong>' % escape(replace)
  19. message_escaped = message_escaped % final_formats
  20. new_notification = Notification(user=user,
  21. trigger=hash_trigger(trigger),
  22. url=url,
  23. message=message_escaped)
  24. if sender:
  25. new_notification.sender = sender
  26. new_notification.sender_username = sender.username
  27. new_notification.sender_slug = sender.slug
  28. new_notification.save()
  29. user.new_notifications = F('new_notifications') + 1
  30. if update_user:
  31. user.save(update_fields=['new_notifications'])
  32. return new_notification
  33. def read_user_notification(user, trigger, atomic=True):
  34. if user.new_notifications:
  35. if atomic:
  36. with transaction.atomic():
  37. _real_read_user_notification(user, trigger)
  38. else:
  39. _real_read_user_notification(user, trigger)
  40. def _real_read_user_notification(user, trigger):
  41. trigger_hash = hash_trigger(trigger)
  42. update_qs = user.notifications.filter(is_new=True)
  43. update_qs = update_qs.filter(trigger=trigger_hash)
  44. updated = update_qs.update(is_new=False)
  45. if updated:
  46. user.new_notifications -= updated
  47. if user.new_notifications < 0:
  48. # Cos no. of changed rows returned via update()
  49. # isn't always accurate
  50. user.new_notifications = 0
  51. user.save(update_fields=['new_notifications'])
  52. def read_all_user_alerts(user):
  53. locked_user = user.lock()
  54. user.new_notifications = 0
  55. locked_user.new_notifications = 0
  56. locked_user.save(update_fields=['new_notifications'])
  57. locked_user.notifications.update(is_new=False)
  58. def assert_real_new_notifications_count(user):
  59. if user.new_notifications:
  60. real_new_count = user.notifications.filter(is_new=True).count()
  61. if real_new_count != user.new_notifications:
  62. user.new_notifications = real_new_count
  63. user.save(update_fields=['new_notifications'])