Exemple #1
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")
Exemple #2
0
    def get_paged(self,
                  url_path: str,
                  *,
                  timeout: float,
                  key: Optional[str] = None) -> List[Any]:
        """Get paged data."""

        if url_path is None or url_path == "":
            raise AttributeError("An invalid URL path was supplied")

        self.authenticate()

        url_path = self._expand_url(url_path)

        all_results: List[Any] = []

        while True:

            Log.info(f"GET: {url_path}")

            response = requests.get(
                url_path,
                headers=self._construct_headers(),
                timeout=timeout,
            )

            TVDBClient._check_errors(response)

            content = response.json()

            data = content.get("data")

            if data is None:
                raise NotFoundException(
                    f"Could not get data for path: {url_path}")

            if key is None:
                all_results += data
            else:
                all_results += data[key]

            links = content.get("links")

            if links is None:
                break

            if links.get("next"):
                Log.debug("Fetching next page")
                url_path = links["next"]
            else:
                break

        return all_results
Exemple #3
0
    def get_paged(self, url_path: str, *, timeout: float) -> List[Any]:
        """Get paged data."""

        if url_path is None or url_path == "":
            raise AttributeError("An invalid URL path was supplied")

        self.authenticate()

        page = 0

        all_results: List[Any] = []

        while True:

            if page != 0:
                url_path += f"?page={page}"

            Log.info(f"GET: {url_path}")

            response = requests.get(
                self._expand_url(url_path),
                headers=self._construct_headers(),
                timeout=timeout
            )

            TVDBClient._check_errors(response)

            content = response.json()

            data = content.get('data')

            if data is None:
                raise NotFoundException(f"Could not get data for path: {url_path}")

            all_results += data

            links = content.get('links')

            if links is None:
                break

            if links.get('next'):
                Log.debug("Fetching next page")
                page = links["next"]
            else:
                break

        return all_results