From e1b0da5766056ad7210ad9f3dc361055da8bd67b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elan=20Ruusam=C3=A4e?= Date: Tue, 30 Jan 2024 22:35:41 +0200 Subject: [PATCH 1/2] Add OAuthRefreshException class Add error and error_description properties --- trakt/errors.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/trakt/errors.py b/trakt/errors.py index dfb555b..5645ca1 100644 --- a/trakt/errors.py +++ b/trakt/errors.py @@ -11,6 +11,7 @@ # Errors for use by PyTrakt 'BadResponseException', + 'OAuthRefreshException', # Exceptions by HTTP status code # https://trakt.docs.apiary.io/#introduction/status-codes @@ -62,6 +63,20 @@ class OAuthException(TraktException): message = 'Unauthorized - OAuth must be provided' +class OAuthRefreshException(OAuthException): + def __init__(self, response=None): + super().__init__(response) + self.data = self.response.json() + + @property + def error(self): + return self.data["error"] + + @property + def error_description(self): + return self.data["error_description"] + + class ForbiddenException(TraktException): """TraktException type to be raised when a 403 return code is received""" http_code = 403 From b6136ee26063d752b32cff3176480dfae4022585 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elan=20Ruusam=C3=A4e?= Date: Tue, 30 Jan 2024 22:44:34 +0200 Subject: [PATCH 2/2] Use OAuthRefreshException when oauth token refresh fails Use it also for 400 status code --- trakt/core.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/trakt/core.py b/trakt/core.py index a0e8c23..16001c7 100644 --- a/trakt/core.py +++ b/trakt/core.py @@ -416,7 +416,7 @@ def _refresh_token(s): 'grant_type': 'refresh_token' } response = session.post(url, json=data, headers=HEADERS) - s.logger.debug('RESPONSE [post] (%s): %s', url, str(response)) + s.logger.debug('RESPONSE [post] (%s): %s - %s', url, str(response), response.content) if response.status_code == 200: data = response.json() OAUTH_TOKEN = data.get("access_token") @@ -433,13 +433,14 @@ def _refresh_token(s): OAUTH_TOKEN=OAUTH_TOKEN, OAUTH_REFRESH=OAUTH_REFRESH, OAUTH_EXPIRES_AT=OAUTH_EXPIRES_AT ) - elif response.status_code == 401: - s.logger.debug( - "Rejected - Unable to refresh expired OAuth token, " - "refresh_token is invalid" - ) + elif response.status_code in (401, 400): + from .errors import OAuthRefreshException + raise OAuthRefreshException(response) elif response.status_code in s.error_map: raise s.error_map[response.status_code](response) + else: + from .errors import BadRequestException + raise BadRequestException(response) def load_config():