From e8900515bbd9ed48af4a844fe08b0a453c9b47dd Mon Sep 17 00:00:00 2001 From: Kai Vogelgesang Date: Thu, 16 Apr 2020 17:15:17 +0200 Subject: [PATCH] Boilerplate --- main.py | 44 +++++++++++++++++++++++++++++++++++++------- static/renderer.js | 9 +++++++++ ui.html | 46 ++++++++++++++++------------------------------ 3 files changed, 62 insertions(+), 37 deletions(-) create mode 100644 static/renderer.js diff --git a/main.py b/main.py index ffb0f67..0f292ed 100644 --- a/main.py +++ b/main.py @@ -11,9 +11,18 @@ CLIENT_REGEX = r'/{client:[a-zA-Z0-9]{16}}' meta_dict = {} -@routes.get(CLIENT_REGEX) -async def handler(request): - client = request.match_info.get("client", "") +def get_client(request: aiohttp.web.Request): + client = request.match_info.get("client", None) + + if not client: + raise aiohttp.web.HTTPBadRequest() + + return client + + +@routes.get(CLIENT_REGEX + '/') +async def handler(request: aiohttp.web.Request): + client = get_client(request) print(f"{client=} accessed") return aiohttp.web.FileResponse('ui.html') @@ -23,10 +32,11 @@ async def handle_request(data, client): @routes.post(CLIENT_REGEX + '/api') -async def handler(request): - client = request.match_info.get("client", "") +async def handler(request: aiohttp.web.Request): + client = get_client(request) + data = await request.json() - data = await request.post() + print(f'{client=} {data=}') ok = await handle_request(data, client) if ok: @@ -36,14 +46,34 @@ async def handler(request): return aiohttp.web.Response(status=400) +@routes.get(CLIENT_REGEX + '/ws') +async def _(request: aiohttp.web.Request): + client = get_client(request) + + ws = aiohttp.web.WebSocketResponse(heartbeat=10) + await ws.prepare(request) + + print(f'model.subscribe({client}, ws)') + + async for msg in ws: + print(f'[WS] client sent {msg=}') + + print(f'model.unsubscribe(ws)') + + return ws + + @routes.get(f"/api/{admintoken}") -async def handler(request): +async def handler(request: aiohttp.web.Request): + del request # unused + return aiohttp.web.json_response(meta_dict) @routes.get('/') async def handler(request): del request # unused + return aiohttp.web.FileResponse('index.html') diff --git a/static/renderer.js b/static/renderer.js new file mode 100644 index 0000000..55c613b --- /dev/null +++ b/static/renderer.js @@ -0,0 +1,9 @@ +const ws_url = new URL('ws', window.location.href); +ws_url.protocol = ws_url.protocol.replace('http', 'ws'); +const ws = new WebSocket(ws_url.href); + +ws.onmessage = function(event) { + const msg = JSON.parse(event.data); + + console.log(msg); +}; \ No newline at end of file diff --git a/ui.html b/ui.html index 5cbc075..89341a6 100644 --- a/ui.html +++ b/ui.html @@ -3,39 +3,25 @@ leafblade Minecraft Server - - - - - - - + -
- this is the UI - +this is the UI + + + + +