onlines.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from datetime import timedelta
  2. from django.core.cache import cache
  3. from django.utils import timezone
  4. from misago.models import Session
  5. from misago.monitor import monitor, UpdatingMonitor
  6. class MembersOnline(object):
  7. def __init__(self, mode, frequency=180):
  8. self.frequency = frequency
  9. self._mode = mode
  10. self._members = monitor['online_members']
  11. self._all = monitor['online_all']
  12. self._om = self._members
  13. self._oa = self._all
  14. if (self._mode != 'no' and (self._mode == 'real' or monitor.expired('online_all', frequency)
  15. or monitor.expired('online_members', frequency))):
  16. self.count_sessions()
  17. def count_sessions(self):
  18. queryset = Session.objects.filter(crawler__isnull=True).filter(last__gte=timezone.now() - timedelta(seconds=self.frequency))
  19. self._all = queryset.count()
  20. self._members = queryset.filter(user__isnull=False).count()
  21. cache.delete_many(['team_users_online', 'ranks_online'])
  22. def new_session(self):
  23. self._all += 1
  24. def sign_in(self):
  25. self._members += 1
  26. def sign_out(self):
  27. if self._members:
  28. self._members -= 1
  29. @property
  30. def all(self):
  31. return self._all
  32. @property
  33. def members(self):
  34. return self._members
  35. def sync(self):
  36. if self._mode == 'snap':
  37. with UpdatingMonitor() as cm:
  38. if self._members != self._om:
  39. monitor['online_members'] = self._members
  40. if self._all != self._oa:
  41. monitor['online_all'] = self._all
  42. def stats(self, request):
  43. stat = {
  44. 'members': self.members,
  45. 'all': self.all,
  46. }
  47. if not request.user.is_crawler():
  48. if request.user.is_authenticated() and not stat['members']:
  49. stat['members'] += 1
  50. stat['all'] += 1
  51. if not request.user.is_authenticated() and not stat['all']:
  52. stat['all'] += 1
  53. return stat