1
0
mirror of https://github.com/EDCD/EDMarketConnector.git synced 2025-06-07 19:03:23 +03:00

CAPI: Continuing code moving/cleanup up/testing

1. Sending back a spurious CredentialsError() to check it's now handled,
   but other issues blocking the code from getting there currently.
2. Move the "Update suit data from CAPI" call into the AppWindow
   handler.
3. Move some more of the old query() exception handling into the worker.
4. session.query() no longer returns anything, and neither should
   anything that calls it (like session.station()).  This is going to
   take quite some unwinding and code moving.
This commit is contained in:
Athanasius 2021-08-16 16:27:00 +01:00
parent 018b4563b3
commit 454c9f3d0c
No known key found for this signature in database
GPG Key ID: AE3E527847057C7D
2 changed files with 43 additions and 47 deletions

View File

@ -934,7 +934,7 @@ class AppWindow(object):
self.w.update_idletasks() self.w.update_idletasks()
querytime = int(time()) querytime = int(time())
data = companion.session.station() companion.session.station()
config.set('querytime', querytime) config.set('querytime', querytime)
@ -1117,6 +1117,9 @@ class AppWindow(object):
if play_sound and play_bad: if play_sound and play_bad:
hotkeymgr.play_bad() hotkeymgr.play_bad()
# Update Odyssey Suit data
companion.suit_update(data)
self.update_suit_text() self.update_suit_text()
self.suit_show_if_set() self.suit_show_if_set()
self.cooldown() self.cooldown()

View File

@ -621,6 +621,10 @@ class Session(object):
try: try:
r = self.session.get(self.server + endpoint, timeout=timeout) # type: ignore r = self.session.get(self.server + endpoint, timeout=timeout) # type: ignore
r.raise_for_status() # Typically 403 "Forbidden" on token expiry r.raise_for_status() # Typically 403 "Forbidden" on token expiry
self.capi_response_queue.put(
CAPIFailedRequest(f'Redirected back to Auth Server', exception=CredentialsError())
)
continue
data = CAPIData(r.json(), endpoint) # May also fail here if token expired since response is empty data = CAPIData(r.json(), endpoint) # May also fail here if token expired since response is empty
except requests.ConnectionError as e: except requests.ConnectionError as e:
@ -631,58 +635,6 @@ class Session(object):
continue continue
# raise ServerConnectionError(f'Unable to connect to endpoint {endpoint}') from e # raise ServerConnectionError(f'Unable to connect to endpoint {endpoint}') from e
except Exception as e:
logger.debug('Attempting GET', exc_info=e)
# LANG: Frontier CAPI data retrieval failed
# raise ServerError(f'{_("Frontier CAPI query failure")}: {endpoint}') from e
self.capi_response_queue.put(
CAPIFailedRequest(f'Frontier CAPI query failure: {endpoint}', exception=e)
)
continue
if r.url.startswith(SERVER_AUTH):
logger.info('Redirected back to Auth Server')
self.capi_response_queue.put(
CAPIFailedRequest(f'Redirected back to Auth Server', exception=CredentialsError()
)
continue
elif 500 <= r.status_code < 600:
# Server error. Typically 500 "Internal Server Error" if server is down
logger.debug('500 status back from CAPI')
self.dump(r)
# LANG: Frontier CAPI data retrieval failed with 5XX code
raise ServerError(f'{_("Frontier CAPI server error")}: {r.status_code}')
self.capi_response_queue.put(
data
)
logger.info('CAPI worker thread DONE')
def capi_query_close_worker(self) -> None:
"""Ask the CAPI query thread to finish."""
self.capi_query_queue.put(None)
def query(self, endpoint: str) -> CAPIData: # noqa: CCR001, C901
"""Perform a query against the specified CAPI endpoint."""
logger.trace_if('capi.query', f'Performing query for endpoint "{endpoint}"')
if self.state == Session.STATE_INIT:
if self.login():
return self.query(endpoint)
elif self.state == Session.STATE_AUTH:
logger.error('cannot make a query when unauthorized')
raise CredentialsError('cannot make a query when unauthorized')
logger.trace_if('capi.query', 'Trying...')
if conf_module.capi_pretend_down:
raise ServerConnectionError(f'Pretending CAPI down: {endpoint}')
self.capi_query_queue.put(endpoint)
try:
...
except (requests.HTTPError, ValueError) as e: except (requests.HTTPError, ValueError) as e:
logger.exception('Frontier CAPI Auth: GET ') logger.exception('Frontier CAPI Auth: GET ')
self.dump(r) self.dump(r)
@ -705,23 +657,67 @@ class Session(object):
logger.error('Frontier CAPI Auth: HTTP error or invalid JSON') logger.error('Frontier CAPI Auth: HTTP error or invalid JSON')
raise CredentialsError('HTTP error or invalid JSON') from e raise CredentialsError('HTTP error or invalid JSON') from e
except Exception as e:
logger.debug('Attempting GET', exc_info=e)
# LANG: Frontier CAPI data retrieval failed
# raise ServerError(f'{_("Frontier CAPI query failure")}: {endpoint}') from e
self.capi_response_queue.put(
CAPIFailedRequest(f'Frontier CAPI query failure: {endpoint}', exception=e)
)
continue
if r.url.startswith(SERVER_AUTH):
logger.info('Redirected back to Auth Server')
self.capi_response_queue.put(
CAPIFailedRequest(f'Redirected back to Auth Server', exception=CredentialsError())
)
continue
elif 500 <= r.status_code < 600:
# Server error. Typically 500 "Internal Server Error" if server is down
logger.debug('500 status back from CAPI')
self.dump(r)
# LANG: Frontier CAPI data retrieval failed with 5XX code
raise ServerError(f'{_("Frontier CAPI server error")}: {r.status_code}')
self.retrying = False self.retrying = False
if endpoint == URL_QUERY and 'commander' not in data:
logger.error('No commander in returned data')
if 'timestamp' not in data: if 'timestamp' not in data:
data['timestamp'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', parsedate(r.headers['Date'])) # type: ignore data['timestamp'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', parsedate(r.headers['Date'])) # type: ignore
# Update Odyssey Suit data self.capi_response_queue.put(
if endpoint == URL_QUERY: data
self.suit_update(data) )
return data logger.info('CAPI worker thread DONE')
def profile(self) -> CAPIData: def capi_query_close_worker(self) -> None:
"""Ask the CAPI query thread to finish."""
self.capi_query_queue.put(None)
def query(self, endpoint: str) -> None:
"""Perform a query against the specified CAPI endpoint."""
logger.trace_if('capi.query', f'Performing query for endpoint "{endpoint}"')
if self.state == Session.STATE_INIT:
if self.login():
return self.query(endpoint)
elif self.state == Session.STATE_AUTH:
logger.error('cannot make a query when unauthorized')
raise CredentialsError('cannot make a query when unauthorized')
logger.trace_if('capi.query', 'Trying...')
if conf_module.capi_pretend_down:
raise ServerConnectionError(f'Pretending CAPI down: {endpoint}')
self.capi_query_queue.put(endpoint)
def profile(self):
"""Perform general CAPI /profile endpoint query.""" """Perform general CAPI /profile endpoint query."""
data = self.query(URL_QUERY) self.query(URL_QUERY)
if 'commander' not in data:
logger.error('No commander in returned data')
return data
def station(self) -> CAPIData: # noqa: CCR001 def station(self) -> CAPIData: # noqa: CCR001
""" """
@ -735,10 +731,7 @@ class Session(object):
:return: Possibly augmented CAPI data. :return: Possibly augmented CAPI data.
""" """
data = self.query(URL_QUERY) self.query(URL_QUERY)
if 'commander' not in data:
logger.error('No commander in returned data')
return data
if not data['commander'].get('docked') and not monitor.state['OnFoot']: if not data['commander'].get('docked') and not monitor.state['OnFoot']:
return data return data