api.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. from django.db.models import F
  2. from django.db import transaction
  3. from django.utils.html import escape
  4. from misago.notifications.models import Notification
  5. from misago.notifications.utils import hash_trigger
  6. __all__ = [
  7. 'notify_user',
  8. 'read_user_notification',
  9. 'read_all_user_alerts',
  10. 'assert_real_new_notifications_count',
  11. ]
  12. def notify_user(user, message, url, trigger, formats=None, sender=None,
  13. update_user=True):
  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. def read_user_notification(user, trigger, atomic=True):
  33. if user.new_notifications:
  34. if atomic:
  35. with transaction.atomic():
  36. _real_read_user_notification(user, trigger)
  37. else:
  38. _real_read_user_notification(user, trigger)
  39. def _real_read_user_notification(user, trigger):
  40. trigger_hash = hash_trigger(trigger)
  41. update_qs = user.notifications.filter(is_new=True)
  42. update_qs = update_qs.filter(trigger=trigger_hash)
  43. updated = update_qs.update(is_new=False)
  44. if updated:
  45. user.new_notifications -= updated
  46. if user.new_notifications < 0:
  47. # Cos no. of changed rows returned via update()
  48. # isn't always accurate
  49. user.new_notifications = 0
  50. user.save(update_fields=['new_notifications'])
  51. def read_all_user_alerts(user):
  52. locked_user = user.lock()
  53. user.new_notifications = 0
  54. locked_user.new_notifications = 0
  55. locked_user.save(update_fields=['new_notifications'])
  56. locked_user.notifications.update(is_new=False)
  57. def assert_real_new_notifications_count(user):
  58. if user.new_notifications:
  59. real_new_count = user.notifications.filter(is_new=True).count()
  60. if real_new_count != user.new_notifications:
  61. user.new_notifications = real_new_count
  62. user.save(update_fields=['new_notifications'])