chat/apps/chat/services/read_state.py

48 lines
1.6 KiB
Python

from uuid import UUID
from django.core.cache import cache
from apps.chat.integrations.mattermost.client import MattermostClient
from apps.chat.models import Conversation, ConversationReadState
_LATEST_POST_CACHE_TTL = 60
class ReadStateService:
def __init__(self, mattermost_client: MattermostClient | None = None):
self._mm = mattermost_client or MattermostClient()
def mark_read(
self, conversation_id, user_id: UUID, post_id: str
) -> ConversationReadState:
read_state, _ = ConversationReadState.objects.update_or_create(
conversation_id=conversation_id,
user_id=user_id,
defaults={"last_read_mattermost_post_id": post_id},
)
return read_state
def has_unread(self, conversation_id, user_id: UUID) -> bool:
try:
read_state = ConversationReadState.objects.get(
conversation_id=conversation_id, user_id=user_id
)
except ConversationReadState.DoesNotExist:
return True
last_read = read_state.last_read_mattermost_post_id
cache_key = f"latest_post:{conversation_id}"
latest_post_id = cache.get(cache_key)
if latest_post_id is None:
conversation = Conversation.objects.get(id=conversation_id)
latest_post_id = self._mm.get_latest_post_id(
conversation.mattermost_channel_id
)
cache.set(cache_key, latest_post_id or "", _LATEST_POST_CACHE_TTL)
if not latest_post_id:
return False
return latest_post_id != last_read