|
| 1 | +import json |
| 2 | +import asyncio |
| 3 | +import threading |
| 4 | +import websockets |
| 5 | +from datetime import datetime, time |
| 6 | +from multi_terminal import MultiTerminal |
| 7 | +from api_client import APIClient |
| 8 | +from stream_utilities import basic_request # Importing utility functions |
| 9 | +from color_print import ColorPrint |
| 10 | + |
| 11 | + |
| 12 | +class StreamClient: |
| 13 | + def __init__(self, client: APIClient): |
| 14 | + self.client = client |
| 15 | + self.websocket = None |
| 16 | + self.streamer_info = None |
| 17 | + self.start_timestamp = None |
| 18 | + self.terminal = MultiTerminal(title="Stream Output") |
| 19 | + self.color_print = ColorPrint() |
| 20 | + self.active = False |
| 21 | + self.login_successful = False |
| 22 | + self.request_id = -1 |
| 23 | + |
| 24 | + async def start(self): |
| 25 | + response = self.client.get_user_preferences() |
| 26 | + if 'error' in response: # Assuming error handling is done inside get_user_preferences |
| 27 | + self.color_print.print("error", f"Failed to get streamer info: {response['error']}") |
| 28 | + exit(1) |
| 29 | + self.streamer_info = response['streamerInfo'][0] |
| 30 | + login = self._construct_login_message() |
| 31 | + await self.connect() |
| 32 | + await self.send(login) |
| 33 | + |
| 34 | + async def connect(self): |
| 35 | + try: |
| 36 | + self.websocket = await websockets.connect(self.streamer_info.get('streamerSocketUrl')) |
| 37 | + self.active = True |
| 38 | + self.color_print.print("info", "Connection established.") |
| 39 | + except Exception as e: |
| 40 | + self.color_print.print("error", f"Failed to connect: {e}") |
| 41 | + |
| 42 | + async def send(self, message): |
| 43 | + if not self.active: |
| 44 | + await self.connect() |
| 45 | + try: |
| 46 | + await self.websocket.send(json.dumps(message)) |
| 47 | + self.color_print.print("info", f"Message sent: {json.dumps(message)}") |
| 48 | + response = await self.websocket.recv() |
| 49 | + await self.handle_response(response) |
| 50 | + except Exception as e: |
| 51 | + self.color_print.print("error", f"Failed to send message: {e}") |
| 52 | + |
| 53 | + async def handle_response(self, message): |
| 54 | + message = json.loads(message) |
| 55 | + self.color_print.print("info", f"Received: {message}") |
| 56 | + if "Login" in message.get('command', '') and message.get('content', {}).get('code') == 0: |
| 57 | + self.login_successful = True |
| 58 | + self.color_print.print("info", "Login successful.") |
| 59 | + |
| 60 | + async def receive(self): |
| 61 | + try: |
| 62 | + return await self.websocket.recv() |
| 63 | + except Exception as e: |
| 64 | + self.color_print.print("error", f"Error receiving message: {e}") |
| 65 | + return None |
| 66 | + |
| 67 | + def _construct_login_message(self): |
| 68 | + # Increment request ID for each new request |
| 69 | + self.request_id += 1 |
| 70 | + |
| 71 | + # Prepare the parameters dictionary specifically for the parameters that need to be nested under 'parameters' |
| 72 | + parameters = { |
| 73 | + "Authorization": self.client.token_info.get("access_token"), |
| 74 | + "SchwabClientChannel": self.streamer_info.get("schwabClientChannel"), |
| 75 | + "SchwabClientFunctionId": self.streamer_info.get("schwabClientFunctionId") |
| 76 | + } |
| 77 | + |
| 78 | + # Call the basic_request function with customer ID and correlation ID at the top level of the request |
| 79 | + return basic_request( |
| 80 | + service="ADMIN", |
| 81 | + request_id=self.request_id, |
| 82 | + command="LOGIN", |
| 83 | + customer_id=self.streamer_info.get("schwabClientCustomerId"), |
| 84 | + correl_id=self.streamer_info.get("schwabClientCorrelId"), |
| 85 | + parameters=parameters |
| 86 | + ) |
| 87 | + |
| 88 | + async def _connect_and_stream(self, login): |
| 89 | + try: |
| 90 | + async with websockets.connect(self.streamer_info.get('streamerSocketUrl')) as websocket: |
| 91 | + self.websocket = websocket |
| 92 | + await websocket.send(json.dumps(login)) |
| 93 | + while True: |
| 94 | + message = await websocket.recv() |
| 95 | + await self.handle_message(json.loads(message)) |
| 96 | + except websockets.exceptions.ConnectionClosedOK: |
| 97 | + self.color_print.print("info", "Stream has closed.") |
| 98 | + except Exception as e: |
| 99 | + self.color_print.print("error", f"{e}") |
| 100 | + self._handle_stream_error(e) |
| 101 | + |
| 102 | + async def handle_message(self, message): |
| 103 | + if "response" in message and any( |
| 104 | + resp.get("code") == "0" for resp in message["response"]): # Check if login is successful |
| 105 | + self.color_print.print("info", "Logged in successfully, sending subscription requests...") |
| 106 | + else: |
| 107 | + self.color_print.print("info", f"Received: {message}") |
| 108 | + |
| 109 | + async def reconnect(self): |
| 110 | + self.terminal.print("[INFO]: Attempting to reconnect...") |
| 111 | + try: |
| 112 | + await asyncio.sleep(10) # Wait before attempting to reconnect |
| 113 | + login = self._construct_login_message() # Reconstruct login info |
| 114 | + await self._connect_and_stream(login) # Attempt to reconnect |
| 115 | + return True |
| 116 | + except Exception as e: |
| 117 | + self.terminal.print(f"Reconnect failed: {e}") |
| 118 | + return False |
| 119 | + |
| 120 | + def _handle_stream_error(self, error): |
| 121 | + self.active = False |
| 122 | + if isinstance(error, RuntimeError) and str(error) == "Streaming window has been closed": |
| 123 | + self.color_print.print("warning", "Streaming window has been closed.") |
| 124 | + else: |
| 125 | + if (datetime.now() - self.start_timestamp).seconds < 70: |
| 126 | + self.color_print.print("error", "Stream not alive for more than 1 minute, exiting...") |
| 127 | + else: |
| 128 | + self.terminal.print("[WARNING]: Connection lost to server, reconnecting...") |
| 129 | + |
| 130 | + def stop(self): |
| 131 | + if self.active: |
| 132 | + self.active = False |
| 133 | + asyncio.create_task(self.websocket.close()) |
| 134 | + self.color_print.print("info", "Connection closed.") |
0 commit comments