X-Git-Url: https://git.mdrn.pl/redakcja.git/blobdiff_plain/3ca475c8e10c811633dec531772e18da6e5fa33d..4e8fc8e3b409859927393db2e40877df3e74208f:/src/team/models.py?ds=sidebyside diff --git a/src/team/models.py b/src/team/models.py index 6e53dd3c..9bd4bf5d 100644 --- a/src/team/models.py +++ b/src/team/models.py @@ -1,3 +1,4 @@ +from datetime import timedelta from django.conf import settings from django.db import models from django.utils.timezone import now @@ -16,18 +17,46 @@ class Profile(models.Model): class Presence(models.Model): - user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE) + GAP_THRESHOLD = 60 + + user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, null=True, blank=True) + session_key = models.CharField(max_length=255) chunk = models.ForeignKey('documents.Chunk', models.SET_NULL, blank=True, null=True) - timestamp = models.DateTimeField(auto_now_add=True, db_index=True) + since = models.DateTimeField(auto_now_add=True, db_index=True) + until = models.DateTimeField(db_index=True) active = models.BooleanField() @classmethod - def report(cls, user, chunk, active): - if user.is_anonymous or not hasattr(user, 'profile') or not user.profile.presence: - return - cls.objects.create( + def report(cls, user, session_key, chunk, active): + user = user if not user.is_anonymous else None + report = cls.objects.filter( user=user, + session_key=session_key, + chunk=chunk, + until__gt=now() - timedelta(seconds=cls.GAP_THRESHOLD) + ).order_by('-until').first() + if report is None or report.active != active: + report = cls.objects.create( + user=user, + session_key=session_key, + chunk=chunk, + active=active, + until=now(), + ) + else: + report.until = now() + report.save() + + @classmethod + def get_current(cls, session_key, chunk): + sessions = set() + presences = [] + for p in cls.objects.filter( chunk=chunk, - timestamp=now(), - active=active - ) + until__gt=now() - timedelta(seconds=cls.GAP_THRESHOLD) + ).exclude(session_key=session_key).order_by('-since'): + if p.session_key not in sessions: + sessions.add(p.session_key) + presences.append(p) + presences.reverse() + return presences