booplaysgba/src/server.py

89 lines
2.1 KiB
Python
Raw Normal View History

import asyncio
import json
import logging
import time
import redis
import websockets
from utils import User, Users
2021-11-01 22:15:16 +00:00
PASSWORD_ADMIN: str = "password_admin"
2021-11-01 22:15:16 +00:00
USERS: Users = Users()
KEYMAP: tuple = (
"a",
"b",
"select",
"start",
"right",
"left",
"up",
"down",
"r",
"l",
)
REDIS_INIT: dict = dict([(x, 0) for x in KEYMAP])
logging.basicConfig(level=logging.DEBUG)
r = redis.Redis(host="localhost", port=6379, db=0)
r.mset(REDIS_INIT)
async def parse_message(user: User, message: dict[str, str]) -> None:
2021-11-02 18:32:54 +00:00
"""Parse the user's message.
2021-11-01 20:13:01 +00:00
Args:
user (User): the sender of the message.
2021-11-02 18:32:54 +00:00
message (dict[str, str]): the data received (through the websocket).
2021-11-01 20:13:01 +00:00
"""
2021-11-02 18:32:54 +00:00
if "auth" in message:
data = message["auth"]
if USERS.admin is None and data == PASSWORD_ADMIN:
USERS.admin = user
logging.debug(f"admin authenticated: {user}")
await user.send('{"auth":"success"}')
2021-11-01 20:13:01 +00:00
2021-11-02 18:32:54 +00:00
if "action" in message:
data = message["action"]
if user.last_message + 1.0 > time.time():
logging.debug(f"dropping action: {data}")
return None
elif data in KEYMAP:
r.incr(data)
2021-11-01 20:13:01 +00:00
user.last_message = time.time()
user.has_voted = True
else:
logging.error(f"unsupported action: {data}")
async def handler(websocket, path: str):
2021-11-01 20:13:01 +00:00
"""Handle the messages sent by a user.
Args:
websocket: the websocket used by the user.
2021-11-01 22:15:16 +00:00
path (str): the path used by the websocket. (?)
2021-11-01 20:13:01 +00:00
"""
try:
# Register user
2021-11-01 22:15:16 +00:00
user = User(websocket)
USERS.register(user)
# Manage received messages
2021-11-01 20:13:01 +00:00
async for json_message in websocket:
message: dict[str, str] = json.loads(json_message)
await parse_message(user, message)
finally:
# Unregister user
2021-11-01 22:15:16 +00:00
USERS.unregister(user)
async def main():
2021-11-01 20:13:01 +00:00
"""Start the websocket server."""
async with websockets.serve(handler, "localhost", 6789):
await asyncio.Future() # run forever
if __name__ == "__main__":
asyncio.run(main())