summary refs log tree commit diff
path: root/main.py
blob: 39413c24436fc6b413cc6bf50561cabde109dac3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import asyncio
import json
import logging
from websockets.asyncio.server import serve
from websockets.asyncio.server import broadcast

addr = "localhost"
port = 3636

logging.basicConfig(level=logging.INFO)

ulist = {}
ulist_connection_ids = {}
clients = []

class util:
    def error(code, listener):
        return json.dumps({
            "error": True,
            "code": code,
            "form": "helium-util",
            "listener": listener
        })
    
    def field_check(expects, gets):
        for i in expects:
            if i not in gets:
                return "malformedJson"
            if type(gets[i]) in [str, dict, list]:
                if len(gets[i]) not in expects[i]:
                    return "lengthInvalid"
        return True

async def handler(websocket):
    clients.append(websocket)
    async for message in websocket:
        try:
            r = json.loads(message)
        except:
            await websocket.send(util.error("malformedJson", None))
            continue
        if "listener" not in r:
            r["listener"] = None
        listener = r["listener"]
        if "command" not in r:
            await websocket.send(util.error("malformedJson", listener))
            continue
        if r["command"] == "register":
            fc = util.field_check({"username": range(1,21), "password": range(8,256), "invite_code": range(16,17)}, r)
            if fc != True:
                await websocket.send(util.error(fc, listener))
                continue
        else:
            await websocket.send(util.error("malformedJson", listener))
    if websocket in clients:
        clients.append(websocket)

async def main():
    async with serve(handler, addr, port) as server:
        await server.serve_forever()

asyncio.run(main())