ft_transcendence/tournament/consumers.py

43 lines
1.2 KiB
Python
Raw Permalink Normal View History

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)
2023-12-26 12:24:23 -05:00
self.member = TournamentMember(self.user.pk, self, self.room)
if (self.room is None):
2023-12-26 12:24:23 -05:00
self.member.send("Tournament not found")
self.disconnect(1017)
2023-12-26 12:24:23 -05:00
self.room.append(self.member)
def receive(self, text_data: str = None, bytes_data: bytes = None):
2023-12-26 12:24:23 -05:00
self.member.receive(text_data, bytes_data)
def disconnect(self, close_code):
member = self.room.get_member_by_socket(self)
if (member is not None):
2023-12-26 12:24:23 -05:00
self.room.remove(self.member, close_code)