added message + scope status on opponent online/offline

This commit is contained in:
Alexander Karpov 2022-06-26 19:23:18 +03:00
parent 7242992b42
commit df3685b8fe

View File

@ -203,6 +203,7 @@ class RoomConsumer(AsyncWebsocketConsumer):
async def connect(self): async def connect(self):
await self.accept() await self.accept()
await self.check_origin()
if not await self.connect_to_room(): if not await self.connect_to_room():
await self.close() await self.close()
@ -219,7 +220,7 @@ class RoomConsumer(AsyncWebsocketConsumer):
}, },
) )
) )
if self.scope["opponent_channel"]: if "opponent_channel" in self.scope and self.scope["opponent_channel"]:
await self.channel_layer.send( await self.channel_layer.send(
self.scope["opponent_channel"], self.scope["opponent_channel"],
{ {
@ -227,6 +228,10 @@ class RoomConsumer(AsyncWebsocketConsumer):
"channel": self.channel_name, "channel": self.channel_name,
}, },
) )
await self.channel_layer.send(
self.scope["opponent_channel"],
{"type": "connection_info", "online": True},
)
# 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)
@ -277,11 +282,18 @@ class RoomConsumer(AsyncWebsocketConsumer):
await self.channel_layer.group_discard(self.room_group_name, self.channel_name) await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
await self.disconnect_player() await self.disconnect_player()
if "opponent_channel" in self.scope and self.scope["opponent_channel"]:
await self.channel_layer.send(
self.scope["opponent_channel"],
{"type": "connection_info", "online": False},
)
@sync_to_async @sync_to_async
def disconnect_player(self): def disconnect_player(self):
if "player_in_room" in self.scope: if "player_in_room" in self.scope:
self.scope["player_in_room"].online = False self.scope["player_in_room"].online = False
self.scope["player_in_room"].save(update_fields=["online"]) self.scope["player_in_room"].channel_name = None
self.scope["player_in_room"].save(update_fields=["online", "channel_name"])
# Receive message from WebSocket # Receive message from WebSocket
async def receive(self, text_data): async def receive(self, text_data):
@ -346,3 +358,26 @@ class RoomConsumer(AsyncWebsocketConsumer):
async def channel(self, event): async def channel(self, event):
channel = event["channel"] channel = event["channel"]
self.scope["opponent_channel"] = channel self.scope["opponent_channel"] = channel
async def connection_info(self, event):
status = event["online"]
await self.send(
text_data=json.dumps(
{
"type": "INFO",
"message": "opponent is online"
if status
else "opponent is offline",
}
)
)
self.scope["opponent_online"] = status
async def check_origin(self):
if not self.scope["player"]:
await self.send(
text_data=json.dumps(
{"type": "ERROR", "message": "token is incorrect or expired"}
)
)
await self.close()