2024-08-27 21:21:22 +00:00
|
|
|
from typing import Optional
|
2024-08-27 20:26:35 +00:00
|
|
|
import bencoder
|
2024-08-27 21:21:22 +00:00
|
|
|
from enum import Enum
|
2024-08-27 20:26:35 +00:00
|
|
|
|
2024-08-27 21:21:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
class MsgType(Enum):
|
|
|
|
CONNECT = 0
|
|
|
|
DISCONNECT = 1
|
|
|
|
DATA = 2
|
|
|
|
|
|
|
|
|
|
|
|
class WSMsg:
|
2024-08-27 20:26:35 +00:00
|
|
|
socketid: int
|
2024-08-27 21:21:22 +00:00
|
|
|
msg: MsgType
|
|
|
|
payload: Optional[bytes]
|
2024-08-27 20:26:35 +00:00
|
|
|
|
2024-08-27 21:21:22 +00:00
|
|
|
def __init__(self, socketid: int, msg: MsgType, payload: Optional[bytes] = None):
|
2024-08-27 20:26:35 +00:00
|
|
|
self.socketid = socketid
|
2024-08-27 21:21:22 +00:00
|
|
|
self.msg = msg
|
|
|
|
self.payload = payload
|
2024-08-27 20:26:35 +00:00
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
2024-08-27 21:21:22 +00:00
|
|
|
def from_bytes(b: bytes) -> 'WSMsg':
|
2024-08-27 20:26:35 +00:00
|
|
|
d = bencoder.decode(b)
|
2024-08-27 21:21:22 +00:00
|
|
|
socketid = d[b"sid"]
|
|
|
|
mtype = MsgType(d[b"mt"])
|
|
|
|
|
|
|
|
if mtype == MsgType.CONNECT:
|
|
|
|
return WSMsg(socketid, mtype)
|
|
|
|
elif mtype == MsgType.DISCONNECT:
|
|
|
|
return WSMsg(socketid, mtype)
|
|
|
|
elif mtype == MsgType.DATA:
|
|
|
|
return WSMsg(socketid, mtype, d[b"data"])
|
|
|
|
|
|
|
|
def to_bytes(self) -> bytes:
|
|
|
|
d = {b"sid": self.socketid, b"mt": self.msg.value}
|
|
|
|
if self.payload:
|
|
|
|
d[b"data"] = self.payload
|
|
|
|
return bencoder.encode(d)
|