counts.py 1.8 KB

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