added connection to room algorithm, minor changes for player model

This commit is contained in:
Alexander Karpov 2022-06-25 12:36:47 +03:00
parent 7a14089d10
commit e1c8b2fb74
7 changed files with 63 additions and 10 deletions

View File

@ -12,16 +12,16 @@ DEBUG = True
ALLOWED_HOSTS = [] ALLOWED_HOSTS = []
INSTALLED_APPS = [ INSTALLED_APPS = [
"django.contrib.sessions",
"django.contrib.auth", "django.contrib.auth",
"django.contrib.contenttypes", "django.contrib.contenttypes",
"django.contrib.messages", "django.contrib.messages",
"django.contrib.staticfiles",
# Packages # Packages
"rest_framework", "rest_framework",
"channels", "channels",
# Apps # Apps
"game", "game",
"room" "room",
] ]
MIDDLEWARE = [ MIDDLEWARE = [
@ -45,6 +45,7 @@ CHANNEL_LAYERS = {
}, },
} }
WSGI_APPLICATION = "chess_backend.wsgi.application" WSGI_APPLICATION = "chess_backend.wsgi.application"

View File

@ -1,8 +1,14 @@
import string import string
import secrets import secrets
from random import randint
def generate_charset(length: int): def generate_charset(length: int):
return "".join( return "".join(
secrets.choice(string.digits + string.ascii_letters) for _ in range(length) secrets.choice(string.digits + string.ascii_letters) for _ in range(length)
) )
def gen_ton():
return "".join([str(randint(0, 9)) for _ in range(48)])

6
game/admin.py Normal file
View File

@ -0,0 +1,6 @@
from django.contrib import admin
# Register your models here.
from game.models import HeroImageSet
admin.site.register(HeroImageSet)

View File

@ -80,8 +80,8 @@ class PlayerCreateView(GenericAPIView, CreateModelMixin):
serializer.is_valid(raise_exception=True) serializer.is_valid(raise_exception=True)
instance = self.perform_create(serializer) instance = self.perform_create(serializer)
access_jwt = sign_jwt({"id": instance.id, "type": "access"}, t_life=3600) access_jwt = instance.get_access_token()
refresh_jwt = sign_jwt({"jit": instance.get_auth_session(), "type": "refresh"}) refresh_jwt = instance.get_refresh_token()
return Response( return Response(
{ {
"access_token": access_jwt, "access_token": access_jwt,

View File

@ -12,6 +12,7 @@ from django.db import models
from django.conf import settings from django.conf import settings
from common.generators import generate_charset from common.generators import generate_charset
from game.services.jwt import sign_jwt
HER0_TYPES = [ HER0_TYPES = [
("WIZARD", "wizard"), ("WIZARD", "wizard"),
@ -66,6 +67,12 @@ class Player(models.Model):
def get_auth_session(self): def get_auth_session(self):
return PlayerAuthSession.objects.get(player=self).jit return PlayerAuthSession.objects.get(player=self).jit
def get_refresh_token(self):
return sign_jwt({"jit": self.get_auth_session(), "type": "refresh"})
def get_access_token(self):
return sign_jwt({"id": self.id, "type": "access"}, t_life=3600)
def __str__(self): def __str__(self):
return self.name return self.name

View File

@ -5,9 +5,11 @@ from channels.generic.websocket import AsyncWebsocketConsumer
from channels.layers import get_channel_layer from channels.layers import get_channel_layer
from game.models import Deck from game.models import Deck
from room.models import PlayerInQueue from room.models import PlayerInQueue, Room, PlayerInRoom
from room.services.room_create import create_room from room.services.room_create import create_room
channel_layer = get_channel_layer()
class QueueConsumer(AsyncWebsocketConsumer): class QueueConsumer(AsyncWebsocketConsumer):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -91,7 +93,6 @@ class QueueConsumer(AsyncWebsocketConsumer):
) )
else: else:
# add to group and send message that opponent found to players # add to group and send message that opponent found to players
channel_layer = get_channel_layer()
room = await create_room( room = await create_room(
deck_id_1=self.scope["deck"], deck_id_1=self.scope["deck"],
player_id_1=self.scope["player"], player_id_1=self.scope["player"],
@ -201,13 +202,39 @@ class RoomConsumer(AsyncWebsocketConsumer):
self.room_name = None self.room_name = None
async def connect(self): async def connect(self):
self.room_name = self.scope["url_route"]["kwargs"]["room_name"] await self.accept()
self.room_group_name = f"room_{self.room_name}"
if not await self.connect_to_room():
await self.close()
# Join room group # Join room group
await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.channel_layer.group_add(self.room_group_name, self.channel_name)
await self.accept() @sync_to_async
def connect_to_room(self):
slug = self.scope["url_route"]["kwargs"]["room_name"]
self.room_name = slug
self.room_group_name = f"room_{slug}"
room = Room.objects.filter(slug=slug)
if not room:
return False
self.scope["room"] = room
# check if player can be in a room
if self.scope["player"] not in [x.id for x in room.first().players.all()]:
return False
# add player info to scope
player = PlayerInRoom.objects.get(player_id=self.scope["player"])
self.scope["first"] = player.first
self.scope["score"] = player.score
self.scope["deck"] = player.deck.id
return True
async def disconnect(self, close_code): async def disconnect(self, close_code):
# Leave room group # Leave room group
@ -221,6 +248,12 @@ class RoomConsumer(AsyncWebsocketConsumer):
{"type": "chat_message", "message": text_data}, {"type": "chat_message", "message": text_data},
) )
# info type message handler
async def info(self, event):
message = event["message"]
await self.send(text_data=json.dumps({"type": "INFO", "message": message}))
# Receive message from room group # Receive message from room group
async def chat_message(self, event): async def chat_message(self, event):
message = event["message"] message = event["message"]

View File

@ -4,5 +4,5 @@ from . import consumers
websocket_urlpatterns = [ websocket_urlpatterns = [
path("room/", consumers.QueueConsumer.as_asgi()), path("room/", consumers.QueueConsumer.as_asgi()),
path("room/<str:room_name>/", consumers.RoomConsumer.as_asgi()), path("room/<str:room_name>", consumers.RoomConsumer.as_asgi()),
] ]