diff --git a/python_sponsorblock/__init__.py b/python_sponsorblock/__init__.py index 1e929fa..63f00f6 100644 --- a/python_sponsorblock/__init__.py +++ b/python_sponsorblock/__init__.py @@ -1,6 +1,8 @@ import requests +import logging from urllib.parse import urlparse, urlunparse, parse_qs import re +from typing import Optional from .exceptions import SponsorBlockError, SponsorBlockIdNotFoundError @@ -25,10 +27,32 @@ def _get_video_id(i: str, silent: bool = False) -> None: else: return query_stuff["v"][0] - class SponsorBlock: - def __init__(self, session: requests.Session = None, base_url: str = "https://sponsor.ajay.app"): + def __init__(self, session: requests.Session = None, base_url: str = "https://sponsor.ajay.app", silent: bool = False, _requests_logging_exists: bool = False): self.base_url: str = base_url self.session: requests.Session = session or requests.Session() + self.silent: bool = silent + self._requests_logging_exists: bool = _requests_logging_exists + self.logger: logging.Logger = logging.Logger("SponsorBlock") + + def _request(self, method: str, endpoint: str) -> Optional[requests.Response]: + error_message = "" + url = self.base_url + endpoint + + r: requests.Response = None + try: + r = self.session.request(method="GET", url=url) + except requests.exceptions.Timeout: + error_message = f"Request timed out at \"{url}\"" + except requests.exceptions.ConnectionError: + error_message = f"Couldn't connect to \"{url}\"" + + if error_message != "": + if not self._requests_logging_exists: + self.logger.error(error_message) + if not self.silent: + raise exceptions.SponsorBlockConnectionError(error_message) + + return r \ No newline at end of file diff --git a/python_sponsorblock/exceptions.py b/python_sponsorblock/exceptions.py index 0085f7e..538bc68 100644 --- a/python_sponsorblock/exceptions.py +++ b/python_sponsorblock/exceptions.py @@ -4,3 +4,6 @@ class SponsorBlockError(Exception): class SponsorBlockIdNotFoundError(SponsorBlockError): pass + +class SponsorBlockConnectionError(SponsorBlockError): + pass