plateforme-tfjm2/draw/consumers.py

46 lines
1.6 KiB
Python
Raw Normal View History

import json
from asgiref.sync import sync_to_async
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from participation.models import Tournament
class DrawConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
tournament_id = self.scope['url_route']['kwargs']['tournament_id']
self.tournament = await sync_to_async(Tournament.objects.get)(pk=tournament_id)
user = self.scope['user']
reg = user.registration
if reg.is_volunteer and not reg.is_admin and self.tournament not in reg.interesting_tournaments \
or not reg.is_volunteer and reg.team.participation.tournament != self.tournament:
# This user may not have access to the drawing session
await self.close()
return
await self.accept()
await self.channel_layer.group_add(f"tournament-{self.tournament.id}", self.channel_name)
async def disconnect(self, close_code):
await self.channel_layer.group_discard(f"tournament-{self.tournament.id}", self.channel_name)
async def receive_json(self, content, **kwargs):
message = content["message"]
print(self.scope)
# TODO: Implement drawing system, instead of making a simple chatbot
await self.channel_layer.group_send(
f"tournament-{self.tournament.id}",
{
"type": "draw.message",
"username": self.scope["user"].username,
"message": message,
}
)
async def draw_message(self, event):
print(event)
await self.send_json({"message": event['message']})