Product selection message handler

This commit is contained in:
Eden Kirin
2023-05-11 15:08:24 +02:00
parent 69e087c0c9
commit 9151aa3e1e
8 changed files with 113 additions and 89 deletions

View File

@ -1,22 +1,20 @@
import asyncio
import json
import logging
from threading import Thread
from typing import Iterable, Optional
import websockets
from websockets import WebSocketServerProtocol
from websockets.exceptions import ConnectionClosedError, ConnectionClosedOK
from hopper.models.player import Player
from hopper.models.product import Product
from hopper.models.ws_dto import (
GameDumpDto,
PlayerReachedDestinationDto,
ProductPurchaseTimerDto,
WSGameDumpMessage,
WSMessage,
WSPlayerReachedDestinationMessage,
WSProductPurchaseTimerTickMessage,
WSProductSelectionDoneMessage,
)
@ -26,6 +24,31 @@ class WSServer(Thread):
self.port = port
super().__init__(daemon=True)
async def handle_rcv_message(
self, client: WebSocketServerProtocol, raw_message: str
) -> None:
try:
ws_message = json.loads(raw_message)
except Exception as ex:
logging.error(
f"Error decoding WS message from {client.id} {raw_message}: {ex}"
)
return None
data_message = ws_message.get("message")
if data_message == WSProductSelectionDoneMessage.message_type:
await self.handle_rcv_product_selection_done(client)
async def handle_rcv_product_selection_done(
self, client: WebSocketServerProtocol
) -> None:
logging.info(f"Handle WSProductSelectionDoneMessage: {client.id}")
# avoid circular imports
from hopper.api.dependencies import get_game_engine
engine = get_game_engine()
await engine.product_selection_done()
async def handler(self, websocket: WebSocketServerProtocol) -> None:
"""New handler instance spawns for each connected client"""
self.connected_clients.add(websocket)
@ -39,7 +62,8 @@ class WSServer(Thread):
while connected:
try:
# we're expecting nothing from client, but read if client sends a message
await websocket.recv()
rcv_data = await websocket.recv()
await self.handle_rcv_message(client=websocket, raw_message=rcv_data)
except ConnectionClosedOK:
logging.info(f"Connection closed OK for client: {websocket.id}")
connected = False
@ -98,26 +122,10 @@ class WSServer(Thread):
)
await self.send_message_to_clients(message)
async def send_product_purchase_time_left_message(
self, player: Player, time_left: int
) -> None:
message = WSProductPurchaseTimerTickMessage(
data=ProductPurchaseTimerDto(
player=player,
time_left=time_left,
)
)
async def send_product_selection_done_message(self) -> None:
message = WSProductSelectionDoneMessage()
await self.send_message_to_clients(message)
async def send_product_purchase_done_message(
self, player: Player, product: Optional[Product] = None
) -> None:
# message = WSProductPurchaseDoneMessage(
# data=ProductPurchaseDoneDto(player=player, product=product),
# )
# await self.send_message_to_clients(message)
...
async def run_async(self) -> None:
logging.info(
f"Starting FairHopper Websockets Server on {self.host}:{self.port}"