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