|
| 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.websocket = None |
| 15 | + self.streamer_info = None |
| 16 | + self.start_timestamp = None |
| 17 | + self.terminal = MultiTerminal(title="Stream Output") |
| 18 | + self.color_print = ColorPrint() |
| 19 | + self.active = False |
| 20 | + self.request_id = 0 |
| 21 | + self.client = client |
| 22 | + |
| 23 | + async def start(self): |
| 24 | + response = self.client.get_user_preferences() |
| 25 | + if not response: |
| 26 | + self.color_print.print("error", f"Failed to get streamer info: {response.status_code}") |
| 27 | + exit(1) |
| 28 | + self.streamer_info = response['streamerInfo'][0] |
| 29 | + login = self._construct_login_message() |
| 30 | + |
| 31 | + while True: |
| 32 | + try: |
| 33 | + await self._connect_and_stream(login) |
| 34 | + except websockets.exceptions.ConnectionClosedOK: |
| 35 | + self.color_print.print("info", "Stream has closed.") |
| 36 | + break |
| 37 | + except Exception as e: |
| 38 | + self.color_print.print("error", f"{e}") |
| 39 | + self._handle_stream_error(e) |
| 40 | + |
| 41 | + def _construct_login_message(self): |
| 42 | + self.request_id += 1 |
| 43 | + return basic_request("ADMIN", "LOGIN", self.request_id, { |
| 44 | + "Authorization": self.client.token_info.get("access_token"), |
| 45 | + "SchwabClientChannel": self.streamer_info.get("schwabClientChannel"), |
| 46 | + "SchwabClientFunctionId": self.streamer_info.get("schwabClientFunctionId") |
| 47 | + }) |
| 48 | + |
| 49 | + async def _connect_and_stream(self, login): |
| 50 | + self.start_timestamp = datetime.now() |
| 51 | + self.color_print.print("info", "Connecting to server...") |
| 52 | + self.color_print.print("info", f"Start timestamp: {self.start_timestamp}") |
| 53 | + self.color_print.print("info", f"Streamer socket URL: {self.streamer_info.get('streamerSocketUrl')}") |
| 54 | + async with websockets.connect(self.streamer_info.get('streamerSocketUrl'), |
| 55 | + ping_interval=None) as self.websocket: |
| 56 | + self.terminal.print("[INFO]: Connecting to server...") |
| 57 | + await self.websocket.send(json.dumps(login)) |
| 58 | + self.terminal.print(f"[Login]: {await self.websocket.recv()}") |
| 59 | + self.active = True |
| 60 | + while True: |
| 61 | + received = await self.websocket.recv() |
| 62 | + self.terminal.print(received) |
| 63 | + |
| 64 | + def _handle_stream_error(self, error): |
| 65 | + self.active = False |
| 66 | + if isinstance(error, RuntimeError) and str(error) == "Streaming window has been closed": |
| 67 | + self.color_print.print("warning", "Streaming window has been closed.") |
| 68 | + else: |
| 69 | + if (datetime.now() - self.start_timestamp).seconds < 70: |
| 70 | + self.color_print.print("error", "Stream not alive for more than 1 minute, exiting...") |
| 71 | + else: |
| 72 | + self.terminal.print("[WARNING]: Connection lost to server, reconnecting...") |
| 73 | + |
| 74 | + def send(self, listOfRequests): |
| 75 | + async def _send(to_send): |
| 76 | + await self.websocket.send(to_send) |
| 77 | + |
| 78 | + if not isinstance(listOfRequests, list): |
| 79 | + listOfRequests = [listOfRequests] |
| 80 | + if self.active: |
| 81 | + to_send = json.dumps({"requests": listOfRequests}) |
| 82 | + asyncio.run(_send(to_send)) |
| 83 | + else: |
| 84 | + self.color_print.print("warning", "Stream is not active, nothing sent.") |
| 85 | + |
| 86 | + def stop(self): |
| 87 | + self.send(basic_request("ADMIN", "LOGOUT", self.request_id)) |
| 88 | + self.active = False |
0 commit comments