python-sponsorblock/python_sponsorblock/__init__.py

62 lines
2.1 KiB
Python
Raw Normal View History

2024-04-24 08:58:48 +00:00
import requests
2024-04-24 10:26:56 +00:00
import logging
from urllib.parse import urlparse, urlunparse, parse_qs
import re
2024-04-24 10:35:22 +00:00
from typing import Optional, List
2024-04-24 08:58:48 +00:00
from .exceptions import SponsorBlockError, SponsorBlockIdNotFoundError
2024-04-24 10:35:22 +00:00
from .constants import Segment
2024-04-24 08:58:48 +00:00
class SponsorBlock:
2024-04-24 10:26:56 +00:00
def __init__(self, session: requests.Session = None, base_url: str = "https://sponsor.ajay.app", silent: bool = False, _requests_logging_exists: bool = False):
2024-04-24 08:58:48 +00:00
self.base_url: str = base_url
self.session: requests.Session = session or requests.Session()
2024-04-24 10:26:56 +00:00
self.silent: bool = silent
self._requests_logging_exists: bool = _requests_logging_exists
self.logger: logging.Logger = logging.Logger("SponsorBlock")
2024-04-24 10:35:22 +00:00
def _get_video_id(self, video: str) -> Optional[str]:
if re.match(r"^[a-zA-Z0-9_-]{11}$", video):
return video.strip()
url = urlparse(url=video)
if url.netloc == "youtu.be":
return url.path[1:]
type_frag_list = url.path.split("/")
query_stuff = parse_qs(url.query)
if "v" not in query_stuff:
if not self.silent:
raise SponsorBlockIdNotFoundError("No video id found in the url")
return None
else:
return query_stuff["v"][0]
2024-04-24 10:26:56 +00:00
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)
2024-04-24 08:58:48 +00:00
2024-04-24 10:35:22 +00:00
return r
def get_segments(video: str) -> List[Segment]:
video_id = _get_video_id
r: List[Segment] = []