Fix error with revision check during saving.
[redakcja.git] / src / team / models.py
1 from datetime import timedelta
2 from django.conf import settings
3 from django.db import models
4 from django.utils.timezone import now
5
6
7 class Profile(models.Model):
8     user = models.OneToOneField(settings.AUTH_USER_MODEL, models.CASCADE)
9     presence = models.BooleanField()
10     approve_by_default = models.BooleanField()
11
12     class Meta:
13         verbose_name = verbose_name_plural = 'profil'
14
15     def __str__(self):
16         return self.user.username
17
18
19 class Presence(models.Model):
20     GAP_THRESHOLD = 10
21
22     user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, null=True, blank=True)
23     session_key = models.CharField(max_length=255)
24     chunk = models.ForeignKey('documents.Chunk', models.SET_NULL, blank=True, null=True)
25     since = models.DateTimeField(auto_now_add=True, db_index=True)
26     until = models.DateTimeField(db_index=True)
27     active = models.BooleanField()
28
29     @classmethod
30     def report(cls, user, session_key, chunk, active):
31         user = user if not user.is_anonymous else None
32         report = cls.objects.filter(
33             user=user,
34             session_key=session_key,
35             chunk=chunk,
36             until__gt=now() - timedelta(seconds=cls.GAP_THRESHOLD)
37         ).order_by('-until').first()
38         if report is None or report.active != active:
39             report = cls.objects.create(
40                 user=user,
41                 session_key=session_key,
42                 chunk=chunk,
43                 active=active,
44                 until=now(),
45             )
46         else:
47             report.until = now()
48             report.save()
49
50     @classmethod
51     def get_current(cls, session_key, chunk):
52         sessions = set()
53         presences = []
54         for p in cls.objects.filter(
55             chunk=chunk,
56             until__gt=now() - timedelta(seconds=cls.GAP_THRESHOLD)
57         ).exclude(session_key=session_key).order_by('-since'):
58             if p.session_key not in sessions:
59                 sessions.add(p.session_key)
60                 presences.append(p)
61         presences.reverse()
62         return presences