counts.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from time import time
  2. from django.conf import settings
  3. from django.dispatch import receiver
  4. from misago.threads.views.newthreads import NewThreads
  5. from misago.threads.views.unreadthreads import UnreadThreads
  6. class BaseCounter(object):
  7. Threads = None
  8. name = None
  9. def __init__(self, user, session):
  10. self.user = user
  11. self.session = session
  12. self.count = self.get_cached_count()
  13. def __int__(self):
  14. return self.count
  15. def __unicode__(self):
  16. return unicode(self.count)
  17. def __nonzero__( self) :
  18. return bool(self.count)
  19. def get_cached_count(self):
  20. count = self.session.get(self.name, None)
  21. if not count or not self.is_cache_valid(count):
  22. count = self.get_real_count()
  23. self.session[self.name] = count
  24. return count['threads']
  25. def is_cache_valid(self, cache):
  26. if cache.get('expires', 0) > time():
  27. return cache.get('user') == self.user.pk
  28. else:
  29. return False
  30. def get_expiration_timestamp(self):
  31. return time() + settings.MISAGO_CONTENT_COUNTING_FREQUENCY * 60
  32. def get_real_count(self):
  33. return {
  34. 'threads': self.Threads(self.user).get_queryset().count(),
  35. 'expires': self.get_expiration_timestamp()
  36. }
  37. def set(self, count):
  38. self.count = count
  39. self.session[self.name] = {
  40. 'user': self.user.pk,
  41. 'threads': count,
  42. 'expires': self.get_expiration_timestamp()
  43. }
  44. def decrease(self):
  45. if self.count > 0:
  46. self.count -= 1
  47. self.session[self.name] = {
  48. 'user': self.user.pk,
  49. 'threads': self.count,
  50. 'expires': self.session[self.name]['expires']
  51. }
  52. class NewThreadsCount(BaseCounter):
  53. Threads = NewThreads
  54. name = 'new_threads'
  55. class UnreadThreadsCount(BaseCounter):
  56. Threads = UnreadThreads
  57. name = 'unread_threads'
  58. from misago.readtracker.signals import all_read
  59. @receiver(all_read)
  60. def zero_unread_counters(sender, **kwargs):
  61. sender.new_threads.set(0)
  62. sender.unread_threads.set(0)