def get_device_token(self, device_code): token_request_params = { "url": API_URL + "/oauth/device/token", "headers": {"Content-Type": "application/json"}, "json": { "code": device_code, "client_id": self.CLIENT_ID, "client_secret": self.CLIENT_SECRET } } token_resp = safe_request('post', token_request_params) if token_resp is None: self._code_fetch_fails += 1 if self._code_fetch_fails == self._CODE_FETCH_FAILS_LIMIT: logger.critical("Unable to get response from trakt.") notify("Unable to get response from trakt.", stdout=True, category="trakt") sys.exit(1) return elif token_resp.status_code == 400: self._code_fetch_fails = 0 return False elif token_resp.status_code == 200: self.token_data = token_resp.json() self._code_fetch_fails = 0 return True else: logger.critical("Invalid status code of token response.") sys.exit(1)
def refresh_token(self): if self._refresh_retries == self._REFRESH_RETRIES_LIMIT: self.token_data = {} self._refresh_retries = 0 logger.critical("Too many failed refreshes. Clearing token.") notify("Trakt token expired. Couldn't auto-refresh token.", stdout=True) self.device_auth() return exchange_params = { "url": API_URL + '/oauth/token', "headers": {"Content-Type": "application/json"}, "json": { "refresh_token": self.token_data['refresh_token'], "client_id": self.CLIENT_ID, "client_secret": self.CLIENT_SECRET, "redirect_uri": "urn:ietf:wg:oauth:2.0:oob", "grant_type": "refresh_token" } } self._refresh_retries += 1 exchange_resp = safe_request('post', exchange_params) if exchange_resp and exchange_resp.status_code == 200: self.token_data = exchange_resp.json() self._refresh_retries = 0 logger.info('Refreshed access token.') else: logger.error("Error refreshing token.")
def get_access_token(self): if not self.token_data: logger.info("Access token not found. Initiating device authentication.") self.device_auth() elif self.is_token_expired(): logger.info("Trakt access token expired. Refreshing.") notify("Trakt access token expired. Refreshing.", category="trakt") self.refresh_token() if not self.token_data or self.is_token_expired(): # either device_auth or refresh_token failed to get token logger.critical("Unable to get access token.") notify("Failed to authorize application with Trakt. " "Run 'trakts auth' manually to retry.", stdout=True, category="trakt") else: return self.token_data['access_token']