42 lines
1.1 KiB
Python
42 lines
1.1 KiB
Python
|
from channels.generic.websocket import AsyncWebsocketConsumer
|
||
|
|
||
|
from django.contrib.auth.models import User
|
||
|
|
||
|
from games.models import GameModel
|
||
|
|
||
|
import json
|
||
|
|
||
|
from .models import game_room_manager
|
||
|
|
||
|
class GameWebSocket(AsyncWebsocketConsumer):
|
||
|
|
||
|
def __init__(self, *args, **kwargs):
|
||
|
super().__init__(*args, **kwargs)
|
||
|
self.channel_name = "games"
|
||
|
self.group_name = "games"
|
||
|
|
||
|
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.game_id = int(self.scope['url_route']['kwargs']['game_id'])
|
||
|
|
||
|
self.room = game_room_manager.get(self.game_id)
|
||
|
|
||
|
if (self.room is None):
|
||
|
self.member.send("Tournament not found")
|
||
|
self.disconnect(1017)
|
||
|
|
||
|
self.room.append(self.member)
|
||
|
|
||
|
def receive(self, text_data: str = None, bytes_data: bytes = None):
|
||
|
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):
|
||
|
self.room.remove(self.member, close_code)
|