51 lines
1.4 KiB
Python
51 lines
1.4 KiB
Python
#!/usr/bin/env python
|
|
|
|
import asyncio
|
|
import websockets
|
|
import ssl
|
|
import json
|
|
import sys
|
|
import os
|
|
from routes import Routes
|
|
|
|
|
|
routes = Routes()
|
|
|
|
class UserInfoProtocol(websockets.BasicAuthWebSocketServerProtocol):
|
|
async def check_credentials(self, username, password):
|
|
all_users = routes.users()
|
|
self.user = all_users.get(username, None)
|
|
return self.user != None
|
|
|
|
|
|
async def handle(websocket):
|
|
try:
|
|
await routes.add_connection(websocket)
|
|
|
|
async for message in websocket:
|
|
event = json.loads(message)
|
|
print(event, file=sys.stderr)
|
|
await routes.call(event["action"], websocket, event)
|
|
|
|
finally:
|
|
await routes.remove_connection(websocket)
|
|
|
|
|
|
async def main():
|
|
ssl_context = None
|
|
pem = "/cert/live/beerlog.ddns.net/fullchain.pem"
|
|
key = "/cert/live/beerlog.ddns.net/privkey.pem"
|
|
if os.path.exists(pem):
|
|
print(f"Start with {pem}", file=sys.stderr)
|
|
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
ssl_context.load_cert_chain(pem, keyfile=key)
|
|
|
|
port = os.environ.get("BEERLOG_PORT", 8000)
|
|
host = os.environ.get("BEERLOG_HOST", "0.0.0.0")
|
|
print(f"Start on {host}:{port}", file=sys.stderr)
|
|
async with websockets.serve(handle, host, port, ssl=ssl_context, create_protocol=UserInfoProtocol):
|
|
await asyncio.Future()
|
|
|
|
|
|
asyncio.run(main())
|