Benachrichtigungen fixen mit Redis

This commit is contained in:
Juhn-Vitus Saß
2025-04-22 12:21:47 +02:00
parent 881bc3d6c1
commit 2dc9a077ee
3 changed files with 40 additions and 8 deletions

View File

@@ -3,6 +3,7 @@ import json
import asyncio
from ..models import QuizGame, QuizGameParticipant
from channels.db import database_sync_to_async
import redis
# Dictionary to track inactive check tasks and active connections per game
game_check_tasks = {}
@@ -10,6 +11,8 @@ game_connections = {}
class LobbyConsumer(AsyncWebsocketConsumer):
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
async def connect(self):
self.join_code = self.scope['url_route']['kwargs']['join_code']
self.room_group_name = f'lobby_{self.join_code}'
@@ -142,12 +145,21 @@ class LobbyConsumer(AsyncWebsocketConsumer):
))()
# Send join notification for new participants
# Zustand laden
try:
prev_names = set(p['display_name'] for p in self.last_participants) if hasattr(self, 'last_participants') else set()
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
# Alte Teilnehmer aus Redis holen
data = r.get(f"last_participants_{self.room_group_name}")
prev_names = set(json.loads(data)) if data else set()
# Aktuelle Teilnehmer aus dem Argument extrahieren
current_names = set(p['display_name'] for p in participants)
# Neue Teilnehmer bestimmen
new_participants = current_names - prev_names
# Benachrichtigung für neue Teilnehmer versenden
for name in new_participants:
await self.channel_layer.group_send(
self.room_group_name,
@@ -156,9 +168,12 @@ class LobbyConsumer(AsyncWebsocketConsumer):
'player_name': name
}
)
# Teilnehmerliste in Redis aktualisieren
r.set(f"last_participants_{self.room_group_name}", json.dumps(list(current_names)))
except Exception as e:
print(f'Error sending join notifications: {e}')
print(f"Error in send_join_notifications: {e}")
self.last_participants = participants
return participants
except QuizGame.DoesNotExist: