Esempio n. 1
0
    def _check_errors(response: requests.Response) -> Any:
        """Check an API response for errors."""

        if response.status_code >= 200 and response.status_code < 300:
            return

        Log.error(f"Bad response code from API: {response.status_code}")

        # Try and read the JSON. If we don't have it, we return the generic
        # exception type
        try:
            data = response.json()
        except json.JSONDecodeError:
            raise TVDBException(
                f"Could not decode error response: {response.text}")

        # Try and get the error message so we can use it
        error = data.get("Error")

        # If we don't have it, just return the generic exception type
        if error is None:
            raise TVDBException(
                f"Could not get error information: {response.text}")

        if error == "Resource not found":
            raise NotFoundException(f"Could not find resource: {response.url}")

        raise TVDBException(f"Unknown error: {response.text}")
Esempio n. 2
0
    def authenticate(self):
        """Authenticate the client with the API.

        This will exit early if we are already authenticated. It does not need
        to be called. All calls requiring that the client is authenticated will
        call this.
        """

        if self.auth_token is not None:
            Log.debug("Already authenticated, skipping")
            return

        Log.info("Authenticating...")

        login_body = {
            "apikey": self.api_key,
            "userkey": self.user_key,
            "username": self.user_name,
        }

        for i in range(0, TVDBClient.Constants.MAX_AUTH_RETRY_COUNT):
            try:
                response = requests.post(
                    self._expand_url("login"),
                    json=login_body,
                    headers=self._construct_headers(),
                    timeout=TVDBClient.Constants.AUTH_TIMEOUT
                )

                # Since we authenticated successfully, we can break out of the
                # retry loop
                break
            except requests.exceptions.Timeout:
                will_retry = i < (TVDBClient.Constants.MAX_AUTH_RETRY_COUNT - 1)
                if will_retry:
                    Log.warning("Authentication timed out, but will retry.")
                else:
                    Log.error("Authentication timed out maximum number of times.")
                    raise Exception("Authentication timed out maximum number of times.")

        if response.status_code < 200 or response.status_code >= 300:
            Log.error(f"Authentication failed withs status code: {response.status_code}")
            raise TVDBAuthenticationException(f"Authentication failed with status code: {response.status_code}")

        content = response.json()
        token = content.get("token")

        if token is None:
            Log.error("Failed to get token from login request")
            raise TVDBAuthenticationException("Failed to get token from login request")

        self.auth_token = token

        Log.info("Authenticated successfully")