Send purchase state

This commit is contained in:
Eden Kirin
2023-03-30 21:09:11 +02:00
parent 6111d07f09
commit 059408242c
5 changed files with 107 additions and 20 deletions

View File

@ -1,12 +1,22 @@
import asyncio
import logging
from threading import Thread
from typing import Iterable, Optional
import websockets
from websockets import WebSocketServerProtocol
from websockets.exceptions import ConnectionClosedOK
from hopper.models.ws_dto import GameDumpDto, WSGameDumpMessage
from hopper.models.product import Product
from hopper.models.ws_dto import (
GameDumpDto,
ProductPurchaseDoneDto,
ProductPurchaseStartDto,
WSGameDumpMessage,
WSMessage,
WSProductPurchaseDone,
WSProductPurchaseStart,
)
from settings import settings
@ -31,6 +41,19 @@ class WSServer(Thread):
self.connected_clients.remove(websocket)
logging.info(f"Remove client: {websocket.id}")
async def send_message_to_client(
self, client: WebSocketServerProtocol, message: WSMessage
) -> None:
message_str = message.to_str()
logging.debug(
f"Sending message {message.message} to clients: {self.connected_clients}: {message_str}"
)
await client.send(message_str)
async def send_message_to_clients(self, message: WSMessage) -> None:
for client in self.connected_clients:
await self.send_message_to_client(client, message)
def _create_game_dump_message(self) -> WSGameDumpMessage:
# avoid circular imports
from hopper.api.dependencies import get_game_engine
@ -55,15 +78,20 @@ class WSServer(Thread):
async def send_game_dump(self) -> None:
"""Broadcast game state to all connected clients"""
if not self.connected_clients:
return
message = self._create_game_dump_message()
logging.debug(
f"Sending game dump to clients: {self.connected_clients}: {message}"
await self.send_message_to_clients(message)
async def send_product_purchase_message(self, products: Iterable[Product]) -> None:
message = WSProductPurchaseStart(
data=ProductPurchaseStartDto(products=products)
)
for client in self.connected_clients:
await client.send(message)
await self.send_message_to_clients(message)
async def send_product_purchase_done_message(
self, product: Optional[Product] = None
) -> None:
message = WSProductPurchaseDone(data=ProductPurchaseDoneDto(product=product))
await self.send_message_to_clients(message)
async def run_async(self) -> None:
logging.info(