Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def __init__(self, title, url, ws_uri, tab_id):
self.id_ = tab_id
self._title = title
self._url = url
self._ws_uri = ws_uri
self.target_id = ws_uri.split('/')[-1]
self._ws: Optional[websockets.WebSocketClientProtocol] = None
self._message_id = 0
self._current_task: Optional[asyncio.Task] = None
self._ack_events = {}
self._ack_payloads = {}
self._input_events = {}
self._trigger_events = {}
self._event_payloads = {}
self._recv_task = None
self._log = logging.getLogger('chromewhip.chrome.ChromeTab')
self._send_log = logging.getLogger('chromewhip.chrome.ChromeTab.send_handler')
self._recv_log = logging.getLogger('chromewhip.chrome.ChromeTab.recv_handler')
async def listen_for_order_book_diffs(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
while True:
try:
trading_pairs: List[str] = await self.get_trading_pairs()
async with websockets.connect(WS_URL) as ws:
ws: websockets.WebSocketClientProtocol = ws
for trading_pair in trading_pairs:
request: Dict[str, str] = {
"type": "SUBSCRIBE",
"topic": "BOOK",
"market": trading_pair
}
await ws.send(ujson.dumps(request))
async for raw_msg in self._inner_messages(ws):
msg = ujson.loads(raw_msg)
# Valid Diff messages from RadarRelay have action key
if "action" in msg:
diff_msg: RadarRelayOrderBookMessage = RadarRelayOrderBook.diff_message_from_exchange(
msg, time.time())
output.put_nowait(diff_msg)
except asyncio.CancelledError:
raise
async def listen_for_user_stream(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
"""
*required
Subscribe to user stream via web socket, and keep the connection open for incoming messages
:param ev_loop: ev_loop to execute this function in
:param output: an async queue where the incoming messages are stored
"""
while True:
try:
async with websockets.connect(Constants.BAEE_WS_URL) as ws:
ws: websockets.WebSocketClientProtocol = ws
# Send a auth request first
auth_request: Dict[str, Any] = {
"event": Constants.WS_AUTH_REQUEST_EVENT,
"data": self._liquid_auth.get_ws_auth_data()
}
await ws.send(ujson.dumps(auth_request))
active_markets_df = await LiquidAPIOrderBookDataSource.get_active_exchange_markets()
quoted_currencies = [
active_markets_df.loc[trading_pair, 'quoted_currency']
for trading_pair in self._trading_pairs
]
for trading_pair, quoted_currency in zip(self._trading_pairs, quoted_currencies):
subscribe_request: Dict[str, Any] = {
def __init__(self, addr: str):
super().__init__()
self.addr: str = addr
self.ws: Optional[websockets.WebSocketClientProtocol]
async def listen_for_user_stream(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
"""
*required
Subscribe to user stream via web socket, and keep the connection open for incoming messages
:param ev_loop: ev_loop to execute this function in
:param output: an async queue where the incoming messages are stored
"""
while True:
try:
async with websockets.connect(COINBASE_WS_FEED) as ws:
ws: websockets.WebSocketClientProtocol = ws
subscribe_request: Dict[str, any] = {
"type": "subscribe",
"product_ids": self._symbols,
"channels": ["user"]
}
auth_dict: Dict[str] = self._coinbase_pro_auth.generate_auth_dict("get", "/users/self/verify", "")
subscribe_request.update(auth_dict)
await ws.send(ujson.dumps(subscribe_request))
async for raw_msg in self._inner_messages(ws):
msg = ujson.loads(raw_msg)
msg_type: str = msg.get("type", None)
if msg_type is None:
raise ValueError(f"Coinbase Pro Websocket message does not contain a type - {msg}")
elif msg_type == "error":
raise ValueError(f"Coinbase Pro Websocket received error message - {msg['message']}")
elif msg_type in ["open", "match", "change", "done"]:
async def release(self, sock: WebSocketClientProtocol) -> None:
if not isinstance(sock, websockets.WebSocketClientProtocol):
return
if sock.closed:
await sock.close()
return
self._freepool.add(sock)
""" IPC via websockets
Mimic the API of yoton2 (the mmap one) but implementation is via a
websocket. This provides a way for languages that do not support mmap
(like JavaScript) to be used from Zoof.
"""
import websockets
def foo(*args):
print(args)
s1 = websockets.WebSocketServerProtocol(foo, host='localhost', port=8765)
s2 = websockets.WebSocketClientProtocol(host='localhost', port=8765)
def __init__(
self, endpoint_uri: URI, loop: asyncio.AbstractEventLoop, websocket_kwargs: Any
) -> None:
self.ws: websockets.WebSocketClientProtocol = None
self.endpoint_uri = endpoint_uri
self.loop = loop
self.websocket_kwargs = websocket_kwargs
def __init__(self):
self._client: Optional[websockets.WebSocketClientProtocol] = None
self._events: Dict[str, bool] = {}
self._nonce = 0
import binascii
import json
import logging
import random
import time
from typing import Dict, Union, Callable, Awaitable
import websockets
from websockets.framing import OP_CLOSE, parse_close, OP_PING, OP_PONG
class SonoffLANModeClientProtocol(websockets.WebSocketClientProtocol):
"""Customised WebSocket client protocol to ignore pong payload match."""
async def read_data_frame(self, max_size):
"""
Copied from websockets.WebSocketCommonProtocol to change pong handling
"""
logger = logging.getLogger(__name__)
while True:
frame = await self.read_frame(max_size)
if frame.opcode == OP_CLOSE:
self.close_code, self.close_reason = parse_close(frame.data)
await self.write_close_frame(frame.data)
return