42 lines
1.2 KiB
Python
42 lines
1.2 KiB
Python
from datetime import timedelta
|
|
|
|
from django.utils import timezone
|
|
|
|
from communications.models import ActiveChatSession
|
|
|
|
ACTIVE_CHAT_SESSION_TTL = timedelta(seconds=75)
|
|
|
|
|
|
def set_active_chat(*, user_id: int, chat_id: int, connection_id: str) -> None:
|
|
now = timezone.now()
|
|
ActiveChatSession.objects.update_or_create(
|
|
connection_id=connection_id,
|
|
defaults={
|
|
"user_id": user_id,
|
|
"chat_id": chat_id,
|
|
"expires_at": now + ACTIVE_CHAT_SESSION_TTL,
|
|
},
|
|
)
|
|
|
|
|
|
def touch_active_chat(*, connection_id: str) -> None:
|
|
now = timezone.now()
|
|
ActiveChatSession.objects.filter(connection_id=connection_id).update(
|
|
last_seen_at=now,
|
|
expires_at=now + ACTIVE_CHAT_SESSION_TTL,
|
|
)
|
|
|
|
|
|
def clear_active_chat(*, connection_id: str) -> None:
|
|
ActiveChatSession.objects.filter(connection_id=connection_id).delete()
|
|
|
|
|
|
def user_is_viewing_chat(*, user_id: int, chat_id: int) -> bool:
|
|
now = timezone.now()
|
|
queryset = ActiveChatSession.objects.filter(
|
|
user_id=user_id,
|
|
chat_id=chat_id,
|
|
)
|
|
queryset.filter(expires_at__lte=now).delete()
|
|
return queryset.filter(expires_at__gt=now).exists()
|