from channels.generic.websocket import WebsocketConsumer from django.contrib.auth.models import User from games.models import GameModel import json from .models import tournament_manager, TournamentMember, TournamentRoom, TournamentRoomManager class TournamentWebConsumer(WebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.channel_name = "tournament" self.group_name = "tournament" def connect(self): self.user: User = self.scope["user"] if (self.user.is_anonymous or not self.user.is_authenticated): return self.channel_layer.group_add(self.group_name, self.channel_name) self.tournament_id = int(self.scope['url_route']['kwargs']['tournament_id']) self.room = tournament_manager.get(self.tournament_id) self.participant = TournamentMember(self.user.pk, self, self.room) if (self.room is None): self.participant.send("Tournament not found") self.disconnect(1017) self.room.append(self.participant) def receive(self, text_data: str = None, bytes_data: bytes = None): self.participant.receive(text_data, bytes_data) def disconnect(self, close_code): member = self.room.get_member_by_socket(self) if (member is not None): self.room.remove(self.participant, close_code)