feat: Упрощено взаимодействие по вебсокетам между клиентом и сервером
This commit is contained in:
@@ -3,5 +3,5 @@ function _message_call(data)
|
||||
{
|
||||
local compile_string = "try { " + data["data"] + " } catch(id) { print(\"[PyG2O] Error white executing the code: \" + id + \"\\nCode: " + data["data"] + "\"); return null; }";
|
||||
local result = compilestring(compile_string)();
|
||||
_send({"uuid": data["uuid"], "data": result});
|
||||
_send({"event": "sq_response", "uuid": data["uuid"], "data": result});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import inspect
|
||||
import server
|
||||
from fastapi import WebSocket
|
||||
|
||||
_EVENTS = {}
|
||||
|
||||
@@ -15,9 +17,12 @@ def event(event_name: str, priority: int = 9999):
|
||||
return func
|
||||
return inlineEvent
|
||||
|
||||
async def call_event(event_name: str, *args, **kwargs):
|
||||
async def call_event(event_name: str, connection: WebSocket, uuid: str | None, *args, **kwargs):
|
||||
if event_name not in _EVENTS:
|
||||
return
|
||||
|
||||
for item in _EVENTS[event_name]:
|
||||
await item['function'](*args, **kwargs)
|
||||
result = await item['function'](*args, **kwargs)
|
||||
if uuid is None or result is None:
|
||||
return
|
||||
await server.Server.send(connection = connection, uuid = uuid, message = result)
|
||||
|
||||
@@ -33,7 +33,7 @@ class Server:
|
||||
cls._register_routes(app)
|
||||
|
||||
@classmethod
|
||||
async def publish(cls, topic: str, message: str) -> asyncio.Future:
|
||||
async def publish(cls, topic: str, message) -> asyncio.Future:
|
||||
if topic not in cls._topics:
|
||||
raise KeyError('Клиентов прослушивающих этот топик не существует')
|
||||
|
||||
@@ -49,7 +49,7 @@ class Server:
|
||||
return request
|
||||
|
||||
@classmethod
|
||||
async def send(cls, connection: WebSocket, message: str, uuid: str):
|
||||
async def send(cls, connection: WebSocket, message, uuid: str):
|
||||
data = {
|
||||
'uuid': uuid,
|
||||
'data': message,
|
||||
@@ -133,14 +133,12 @@ class Server:
|
||||
async def _process_message(cls, connection: WebSocket, message: dict):
|
||||
match message:
|
||||
|
||||
case {'uuid': id, 'data': data}:
|
||||
if id in cls._requests:
|
||||
cls._requests[id].set_result(data)
|
||||
else:
|
||||
asyncio.create_task(call_event('onWebsocketMessage', connection, id, data))
|
||||
|
||||
case {'event': event, **args}:
|
||||
asyncio.create_task(call_event(event, **args))
|
||||
case {'event': event, **kwargs}:
|
||||
try:
|
||||
cls._requests[kwargs['uuid']].set_result(kwargs)
|
||||
except KeyError:
|
||||
uuid = kwargs.get('uuid')
|
||||
asyncio.create_task(call_event(event, connection, uuid, **kwargs))
|
||||
|
||||
case {'subscribe': topics}:
|
||||
await cls._subscribe(topics, connection)
|
||||
|
||||
Reference in New Issue
Block a user