2022-09-02 21:05:16 +00:00
|
|
|
from typing import Any, Tuple, Union
|
2022-08-29 19:41:15 +00:00
|
|
|
|
|
|
|
from fastapi import WebSocket as FastAPIWebSocket
|
2022-09-06 18:40:58 +00:00
|
|
|
from websockets.client import WebSocketClientProtocol as WebSocket
|
2022-08-29 19:41:15 +00:00
|
|
|
|
|
|
|
from freqtrade.rpc.api_server.ws.types import WebSocketType
|
|
|
|
|
|
|
|
|
|
|
|
class WebSocketProxy:
|
|
|
|
"""
|
|
|
|
WebSocketProxy object to bring the FastAPIWebSocket and websockets.WebSocketClientProtocol
|
|
|
|
under the same API
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, websocket: WebSocketType):
|
|
|
|
self._websocket: Union[FastAPIWebSocket, WebSocket] = websocket
|
|
|
|
|
2022-10-23 01:02:05 +00:00
|
|
|
@property
|
2022-10-23 17:42:59 +00:00
|
|
|
def raw_websocket(self):
|
2022-10-23 01:02:05 +00:00
|
|
|
return self._websocket
|
|
|
|
|
2022-09-02 21:05:16 +00:00
|
|
|
@property
|
|
|
|
def remote_addr(self) -> Tuple[Any, ...]:
|
2022-09-06 18:40:58 +00:00
|
|
|
if isinstance(self._websocket, WebSocket):
|
2022-09-02 21:05:16 +00:00
|
|
|
return self._websocket.remote_address
|
2022-09-06 18:40:58 +00:00
|
|
|
elif isinstance(self._websocket, FastAPIWebSocket):
|
|
|
|
if self._websocket.client:
|
|
|
|
client, port = self._websocket.client.host, self._websocket.client.port
|
|
|
|
return (client, port)
|
2022-09-02 21:05:16 +00:00
|
|
|
return ("unknown", 0)
|
|
|
|
|
2022-08-29 19:41:15 +00:00
|
|
|
async def send(self, data):
|
|
|
|
"""
|
|
|
|
Send data on the wrapped websocket
|
|
|
|
"""
|
2022-09-05 19:47:17 +00:00
|
|
|
if hasattr(self._websocket, "send_text"):
|
|
|
|
await self._websocket.send_text(data)
|
2022-08-29 19:41:15 +00:00
|
|
|
else:
|
|
|
|
await self._websocket.send(data)
|
|
|
|
|
|
|
|
async def recv(self):
|
|
|
|
"""
|
|
|
|
Receive data on the wrapped websocket
|
|
|
|
"""
|
2022-09-05 19:47:17 +00:00
|
|
|
if hasattr(self._websocket, "receive_text"):
|
|
|
|
return await self._websocket.receive_text()
|
2022-08-29 19:41:15 +00:00
|
|
|
else:
|
|
|
|
return await self._websocket.recv()
|
|
|
|
|
|
|
|
async def ping(self):
|
|
|
|
"""
|
|
|
|
Ping the websocket, not supported by FastAPI WebSockets
|
|
|
|
"""
|
|
|
|
if hasattr(self._websocket, "ping"):
|
|
|
|
return await self._websocket.ping()
|
|
|
|
return False
|
|
|
|
|
|
|
|
async def close(self, code: int = 1000):
|
|
|
|
"""
|
|
|
|
Close the websocket connection, only supported by FastAPI WebSockets
|
|
|
|
"""
|
|
|
|
if hasattr(self._websocket, "close"):
|
2022-09-10 21:12:18 +00:00
|
|
|
try:
|
|
|
|
return await self._websocket.close(code)
|
|
|
|
except RuntimeError:
|
|
|
|
pass
|
2022-08-29 19:41:15 +00:00
|
|
|
|
|
|
|
async def accept(self):
|
|
|
|
"""
|
|
|
|
Accept the WebSocket connection, only support by FastAPI WebSockets
|
|
|
|
"""
|
|
|
|
if hasattr(self._websocket, "accept"):
|
|
|
|
return await self._websocket.accept()
|