Change visibility of decorators require_websocket_connection and require_websocket_authentication (and hardcode HEARTBEAT).

This commit is contained in:
Davide Casale
2023-06-17 22:24:27 +02:00
parent b12fedb7a3
commit d9733e8d38
3 changed files with 16 additions and 17 deletions

View File

@@ -4,9 +4,7 @@ from ..handlers import PublicChannelsHandler
from ..exceptions import ConnectionNotOpen, TooManySubscriptions
_HEARTBEAT = "hb"
def _require_websocket_connection(function):
def require_websocket_connection(function):
async def wrapper(self, *args, **kwargs):
if self.websocket is None or not self.websocket.open:
raise ConnectionNotOpen("No open connection with the server.")
@@ -59,7 +57,7 @@ class BfxWebSocketBucket:
self.event_emitter.emit("wss-error", message["code"], message["msg"])
if isinstance(message, list):
if (chan_id := message[0]) and message[1] != _HEARTBEAT:
if (chan_id := message[0]) and message[1] != "hb":
self.handler.handle(self.subscriptions[chan_id], message[1:])
async def __recover_state(self):
@@ -71,7 +69,7 @@ class BfxWebSocketBucket:
self.subscriptions.clear()
@_require_websocket_connection
@require_websocket_connection
async def subscribe(self, channel, sub_id=None, **kwargs):
if len(self.subscriptions) + len(self.pendings) == BfxWebSocketBucket.MAXIMUM_SUBSCRIPTIONS_AMOUNT:
raise TooManySubscriptions("The client has reached the maximum number of subscriptions.")
@@ -88,14 +86,14 @@ class BfxWebSocketBucket:
await self.websocket.send(json.dumps(subscription))
@_require_websocket_connection
@require_websocket_connection
async def unsubscribe(self, chan_id):
await self.websocket.send(json.dumps({
"event": "unsubscribe",
"chanId": chan_id
}))
@_require_websocket_connection
@require_websocket_connection
async def close(self, code=1000, reason=str()):
await self.websocket.close(code=code, reason=reason)

View File

@@ -6,24 +6,25 @@ import traceback, json, asyncio, hmac, hashlib, time, socket, random, websockets
from pyee.asyncio import AsyncIOEventEmitter
from .bfx_websocket_bucket import _HEARTBEAT, _require_websocket_connection, BfxWebSocketBucket
from .bfx_websocket_bucket import require_websocket_connection, BfxWebSocketBucket
from .bfx_websocket_inputs import BfxWebSocketInputs
from ..handlers import PublicChannelsHandler, AuthEventsHandler
from ..exceptions import WebSocketAuthenticationRequired, InvalidAuthenticationCredentials, EventNotSupported, \
from ..exceptions import ActionRequiresAuthentication, InvalidAuthenticationCredentials, EventNotSupported, \
ZeroConnectionsError, ReconnectionTimeoutError, OutdatedClientVersion
from ...utils.json_encoder import JSONEncoder
from ...utils.logger import ColorLogger, FileLogger
def _require_websocket_authentication(function):
def require_websocket_authentication(function):
async def wrapper(self, *args, **kwargs):
if hasattr(self, "authentication") and not self.authentication:
raise WebSocketAuthenticationRequired("To perform this action you need to " \
raise ActionRequiresAuthentication("To perform this action you need to " \
"authenticate using your API_KEY and API_SECRET.")
await _require_websocket_connection(function)(self, *args, **kwargs)
await require_websocket_connection(function) \
(self, *args, **kwargs)
return wrapper
@@ -170,7 +171,7 @@ class BfxWebSocketClient:
self.event_emitter.emit("wss-error", message["code"], message["msg"])
if isinstance(message, list):
if message[0] == 0 and message[1] != _HEARTBEAT:
if message[0] == 0 and message[1] != "hb":
self.handler.handle(message[1], message[2])
while True:
@@ -256,11 +257,11 @@ class BfxWebSocketClient:
if self.websocket is not None and self.websocket.open:
await self.websocket.close(code=code, reason=reason)
@_require_websocket_authentication
@require_websocket_authentication
async def notify(self, info, message_id=None, **kwargs):
await self.websocket.send(json.dumps([ 0, "n", message_id, { "type": "ucm-test", "info": info, **kwargs } ]))
@_require_websocket_authentication
@require_websocket_authentication
async def __handle_websocket_input(self, event, data):
await self.websocket.send(json.dumps([ 0, event, None, data], cls=JSONEncoder))

View File

@@ -7,7 +7,7 @@ __all__ = [
"TooManySubscriptions",
"ZeroConnectionsError",
"ReconnectionTimeoutError",
"WebSocketAuthenticationRequired",
"ActionRequiresAuthentication",
"InvalidAuthenticationCredentials",
"EventNotSupported",
"OutdatedClientVersion"
@@ -38,7 +38,7 @@ class ReconnectionTimeoutError(BfxWebSocketException):
This error indicates that the connection has been offline for too long without being able to reconnect.
"""
class WebSocketAuthenticationRequired(BfxWebSocketException):
class ActionRequiresAuthentication(BfxWebSocketException):
"""
This error indicates an attempt to access a protected resource without logging in first.
"""