From 2080c218988472fad9a835552991a17d6b762c30 Mon Sep 17 00:00:00 2001 From: Hellow <74311245+HeIIow2@users.noreply.github.com> Date: Thu, 25 Apr 2024 22:42:40 +0200 Subject: [PATCH] feat: added some invalid json responses, which are ok --- python_sponsorblock/__init__.py | 19 +++++++++++++++---- python_sponsorblock/exceptions.py | 3 +++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/python_sponsorblock/__init__.py b/python_sponsorblock/__init__.py index 53c96c7..114ad1d 100644 --- a/python_sponsorblock/__init__.py +++ b/python_sponsorblock/__init__.py @@ -2,11 +2,11 @@ import requests import logging from urllib.parse import urlparse, urlunparse, parse_qs, urlencode import re -from typing import Optional, List, Dict, Union, Any, Callable +from typing import Optional, List, Dict, Union, Any, Callable, Set import json from functools import wraps -from .exceptions import SponsorBlockError, SponsorBlockIdNotFoundError +from .exceptions import SponsorBlockError, SponsorBlockIdNotFoundError, ReturnDefault from .constants import Segment @@ -19,6 +19,9 @@ def error_handling(default: Any) -> Callable: try: return func(self, *args, **kwargs) except SponsorBlockError as e: + if isinstance(e, ReturnDefault): + return default + if not self.silent: raise e @@ -61,7 +64,12 @@ class SponsorBlock: else: return query_stuff["v"][0] - def _request(self, method: str, endpoint: str) -> Union[List, Dict]: + def _request(self, method: str, endpoint: str, return_default_at_response: List[str] = None) -> Union[List, Dict]: + valid_responses: Set[str] = set([ + "Not Found", + ]) + valid_responses.update(return_default_at_response or []) + error_message = "" url = self.base_url + endpoint @@ -79,11 +87,14 @@ class SponsorBlock: if r.status_code == 400: self.logger.warning(f"{url} returned 400, meaning I did something wrong.") + if r.text in valid_responses: + raise exceptions.ReturnDefault() + data = {} try: data = r.json() except json.JSONDecodeError: - raise exceptions.SponsorBlockConnectionError(f"{r.content} is invalid json.") + raise exceptions.SponsorBlockConnectionError(f"{r.text} is invalid json.") return data diff --git a/python_sponsorblock/exceptions.py b/python_sponsorblock/exceptions.py index b6a11df..9575022 100644 --- a/python_sponsorblock/exceptions.py +++ b/python_sponsorblock/exceptions.py @@ -6,3 +6,6 @@ class SponsorBlockIdNotFoundError(SponsorBlockError): class SponsorBlockConnectionError(SponsorBlockError): pass + +class ReturnDefault(SponsorBlockError): + pass