|
| 1 | +import random |
| 2 | +from time import sleep |
| 3 | +import requests |
| 4 | +import webbrowser |
| 5 | +import base64 |
| 6 | +import json |
| 7 | +from datetime import datetime, timedelta |
| 8 | +import logging |
| 9 | +from config import APIConfig |
| 10 | +from color_print import ColorPrint |
| 11 | + |
| 12 | + |
| 13 | +class APIClient: |
| 14 | + def __init__(self, initials): |
| 15 | + self.initials = initials |
| 16 | + self.account_numbers = None |
| 17 | + self.config = APIConfig(self.initials) |
| 18 | + self.session = requests.Session() |
| 19 | + self.setup_logging() |
| 20 | + self.token_info = self.load_token() |
| 21 | + |
| 22 | + # Validate and refresh token or reauthorize if necessary |
| 23 | + if not self.token_info or not self.ensure_valid_token(): |
| 24 | + self.manual_authorization_flow() |
| 25 | + |
| 26 | + def setup_logging(self): |
| 27 | + logging.basicConfig(**self.config.LOGGING_CONFIG) |
| 28 | + self.logger = logging.getLogger(__name__) |
| 29 | + |
| 30 | + def ensure_valid_token(self): |
| 31 | + """Ensure the token is valid, refresh if possible, otherwise prompt for reauthorization.""" |
| 32 | + if self.token_info: |
| 33 | + if self.validate_token(): |
| 34 | + self.logger.info("Token loaded and valid.") |
| 35 | + return True |
| 36 | + elif 'refresh_token' in self.token_info: |
| 37 | + self.logger.info("Access token expired. Attempting to refresh.") |
| 38 | + if self.refresh_access_token(): |
| 39 | + return True |
| 40 | + self.logger.warning("Token invalid and could not be refreshed.") |
| 41 | + return False |
| 42 | + |
| 43 | + def manual_authorization_flow(self): |
| 44 | + """ Handle the manual steps required to get the authorization code from the user. """ |
| 45 | + self.logger.info("Starting manual authorization flow.") |
| 46 | + auth_url = f"{self.config.API_BASE_URL}/v1/oauth/authorize?client_id={self.config.APP_KEY}&redirect_uri={self.config.CALLBACK_URL}&response_type=code" |
| 47 | + webbrowser.open(auth_url) |
| 48 | + self.logger.info(f"Please authorize the application by visiting: {auth_url}") |
| 49 | + response_url = ColorPrint.input( |
| 50 | + "After authorizing, wait for it to load (<1min) and paste the WHOLE url here: ") |
| 51 | + authorization_code = f"{response_url[response_url.index('code=') + 5:response_url.index('%40')]}@" |
| 52 | + # session = response_url[response_url.index("session=")+8:] |
| 53 | + self.exchange_authorization_code_for_tokens(authorization_code) |
| 54 | + |
| 55 | + def exchange_authorization_code_for_tokens(self, code): |
| 56 | + """ Exchange the authorization code for access and refresh tokens. """ |
| 57 | + data = { |
| 58 | + 'grant_type': 'authorization_code', |
| 59 | + 'code': code, |
| 60 | + 'redirect_uri': self.config.CALLBACK_URL |
| 61 | + } |
| 62 | + self.post_token_request(data) |
| 63 | + |
| 64 | + def post_token_request(self, data): |
| 65 | + """ Generalized token request handling. """ |
| 66 | + headers = { |
| 67 | + 'Authorization': f'Basic {base64.b64encode(f"{self.config.APP_KEY}:{self.config.APP_SECRET}".encode()).decode()}', |
| 68 | + 'Content-Type': 'application/x-www-form-urlencoded' |
| 69 | + } |
| 70 | + response = self.session.post(f"{self.config.API_BASE_URL}/v1/oauth/token", headers=headers, data=data) |
| 71 | + if response.status_code == 200: |
| 72 | + self.save_token(response.json()) |
| 73 | + self.logger.info("Tokens successfully updated.") |
| 74 | + return True |
| 75 | + else: |
| 76 | + self.logger.error("Failed to obtain tokens.") |
| 77 | + response.raise_for_status() |
| 78 | + |
| 79 | + def refresh_access_token(self): |
| 80 | + """Use the refresh token to obtain a new access token and validate it.""" |
| 81 | + |
| 82 | + data = { |
| 83 | + 'grant_type': 'refresh_token', |
| 84 | + 'refresh_token': self.token_info['refresh_token'] |
| 85 | + } |
| 86 | + if not self.post_token_request(data): |
| 87 | + self.logger.error("Failed to refresh access token.") |
| 88 | + return False |
| 89 | + self.token_info = self.load_token() |
| 90 | + return self.validate_token() |
| 91 | + |
| 92 | + def save_token(self, token_data): |
| 93 | + """ Save token data securely. """ |
| 94 | + token_data['expires_at'] = (datetime.now() + timedelta(seconds=token_data['expires_in'])).isoformat() |
| 95 | + with open(f'schwab_token_data_{self.initials}.json', 'w') as f: |
| 96 | + json.dump(token_data, f) |
| 97 | + self.logger.info("Token data saved successfully.") |
| 98 | + |
| 99 | + def load_token(self): |
| 100 | + """ Load token data. """ |
| 101 | + try: |
| 102 | + with open(f'schwab_token_data_{self.initials}.json', 'r') as f: |
| 103 | + token_data = json.load(f) |
| 104 | + return token_data |
| 105 | + except Exception as e: |
| 106 | + self.logger.warning(f"Loading token failed: {e}") |
| 107 | + return None |
| 108 | + |
| 109 | + def validate_token(self, force=False): |
| 110 | + """ Validate the current token. """ |
| 111 | + # print(self.token_info['expires_at']) |
| 112 | + # print(datetime.now()) |
| 113 | + # print(datetime.fromisoformat(self.token_info['expires_at'])) |
| 114 | + # print(datetime.now() < datetime.fromisoformat(self.token_info['expires_at'])) |
| 115 | + if self.token_info and datetime.now() < datetime.fromisoformat(self.token_info['expires_at']): |
| 116 | + print(f"Token expires in {datetime.fromisoformat(self.token_info['expires_at']) - datetime.now()} seconds") |
| 117 | + return True |
| 118 | + elif force: |
| 119 | + print("Token expired or invalid.") |
| 120 | + # get AAPL to validate token |
| 121 | + params = {'symbol': 'AAPL'} |
| 122 | + response = self.make_request(endpoint=f"{self.config.MARKET_DATA_BASE_URL}/chains", params=params, validating=True) |
| 123 | + print(response) |
| 124 | + if response: |
| 125 | + self.logger.info("Token validated successfully.") |
| 126 | + # self.account_numbers = response.json() |
| 127 | + return True |
| 128 | + self.logger.warning("Token validation failed.") |
| 129 | + return False |
| 130 | + |
| 131 | + def make_request(self, endpoint, method="GET", **kwargs): |
| 132 | + sleep(0.5 + random.randint(0, 1000) / 1000) |
| 133 | + """ Make authenticated HTTP requests. """ |
| 134 | + if 'validating' not in kwargs: |
| 135 | + if not self.validate_token(): |
| 136 | + self.logger.info("Token expired or invalid, re-authenticating.") |
| 137 | + self.manual_authorization_flow() |
| 138 | + kwargs.pop('validating', None) |
| 139 | + if self.config.API_BASE_URL not in endpoint: |
| 140 | + url = f"{self.config.API_BASE_URL}{endpoint}" |
| 141 | + else: |
| 142 | + url = endpoint |
| 143 | + print(f"Making request to {url} with method {method} and kwargs {kwargs} (validating already popped if present)") |
| 144 | + headers = {'Authorization': f"Bearer {self.token_info['access_token']}"} |
| 145 | + response = self.session.request(method, url, headers=headers, **kwargs) |
| 146 | + print(response.status_code) |
| 147 | + print(response.text) |
| 148 | + if response.status_code == 401: |
| 149 | + self.logger.warning("Token expired during request. Refreshing token...") |
| 150 | + self.manual_authorization_flow() |
| 151 | + headers = {'Authorization': f"Bearer {self.token_info['access_token']}"} |
| 152 | + response = self.session.request(method, url, headers=headers, **kwargs) |
| 153 | + response.raise_for_status() |
| 154 | + return response.json() |
| 155 | + |
| 156 | + def get_user_preferences(self): |
| 157 | + """Retrieve user preferences.""" |
| 158 | + try: |
| 159 | + return self.make_request(f'{self.config.TRADER_BASE_URL}/userPreference') |
| 160 | + except Exception as e: |
| 161 | + self.logger.error(f"Failed to get user preferences: {e}") |
| 162 | + return None |
0 commit comments