Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: make `parse_url` a class method (#75)

NTFSvolume52674a0fbd96
diff --git a/cyberdrop_dl/crawlers/camwhores_dot_tv.py b/cyberdrop_dl/crawlers/camwhores_dot_tv.py
index 24ccf254a..68645f9f6 100644
--- a/cyberdrop_dl/crawlers/camwhores_dot_tv.py
+++ b/cyberdrop_dl/crawlers/camwhores_dot_tv.py
@@ -25,6 +25,7 @@ class CamwhoresTVCrawler(KernelVideoSharingCrawler):
PRIMARY_URL: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://www.camwhores.tv")
DOMAIN: ClassVar[str] = "camwhores.tv"
+ DEFAULT_TRIM_URLS: ClassVar[bool] = False
async def fetch(self, scrape_item: ScrapeItem) -> None:
# Returns 404 without the trailing slash
@@ -32,11 +33,6 @@ class CamwhoresTVCrawler(KernelVideoSharingCrawler):
scrape_item.url = scrape_item.url / ""
await super().fetch(scrape_item)
- def parse_url(
- self, link_str: str, relative_to: AbsoluteHttpURL | None = None, *, trim: bool | None = None
- ) -> AbsoluteHttpURL:
- return super().parse_url(link_str, relative_to, trim=False)
-
async def picture(self, scrape_item: ScrapeItem) -> None:
# images are encrypted, similar to the video URLS
# https://www.camwhores.tv/get_image/93/9da0742b1fb753388286b95c2a66d766/sources/100000/100557/1472879.jpg/
diff --git a/cyberdrop_dl/crawlers/crawler.py b/cyberdrop_dl/crawlers/crawler.py
index afa78c72b..02fbacf38 100644
--- a/cyberdrop_dl/crawlers/crawler.py
+++ b/cyberdrop_dl/crawlers/crawler.py
@@ -623,12 +623,15 @@ class Crawler(HTTPClientProxy, ABC):
post_title, _ = safe_format(title_format, id=id, number=id, date=date, title=title)
return post_title
- def parse_url(self, link_str: str, relative_to: URL | None = None, *, trim: bool | None = None) -> AbsoluteHttpURL:
+ @classmethod
+ def parse_url(
+ cls, link_str: str, relative_to: AbsoluteHttpURL | None = None, *, trim: bool | None = None
+ ) -> AbsoluteHttpURL:
"""Wrapper around `utils.parse_url` to use `self.PRIMARY_URL` as base"""
- base = relative_to or self.PRIMARY_URL
+ base = relative_to or cls.PRIMARY_URL
assert is_absolute_http_url(base)
if trim is None:
- trim = self.DEFAULT_TRIM_URLS
+ trim = cls.DEFAULT_TRIM_URLS
return parse_url(link_str, base, trim=trim)
def update_cookies(self, cookies: dict[str, Any], url: URL | None = None) -> None:
diff --git a/cyberdrop_dl/crawlers/discourse/_discourse.py b/cyberdrop_dl/crawlers/discourse/_discourse.py
index 0748594fd..3fb957ffd 100644
--- a/cyberdrop_dl/crawlers/discourse/_discourse.py
+++ b/cyberdrop_dl/crawlers/discourse/_discourse.py
@@ -147,8 +147,9 @@ class DiscourseCrawler(MessageBoardCrawler, is_generic=True):
return unique(iter_links())
+ @classmethod
def parse_url(
- self, link_str: str, relative_to: AbsoluteHttpURL | None = None, *, trim: bool | None = None
+ cls, link_str: str, relative_to: AbsoluteHttpURL | None = None, *, trim: bool | None = None
) -> AbsoluteHttpURL:
return _clean_url(super().parse_url(link_str, relative_to, trim=trim))
diff --git a/cyberdrop_dl/crawlers/jpg5.py b/cyberdrop_dl/crawlers/jpg5.py
index 61bd026b6..345d8c648 100644
--- a/cyberdrop_dl/crawlers/jpg5.py
+++ b/cyberdrop_dl/crawlers/jpg5.py
@@ -58,8 +58,9 @@ class JPG5Crawler(CheveretoCrawler):
await super().direct_file(scrape_item, link, assume_ext)
+ @classmethod
def parse_url(
- self, link_str: str, relative_to: AbsoluteHttpURL | None = None, *, trim: bool | None = None
+ cls, link_str: str, relative_to: AbsoluteHttpURL | None = None, *, trim: bool | None = None
) -> AbsoluteHttpURL:
if not link_str.startswith("https") and not link_str.startswith("/"):
encrypted_url = bytes.fromhex(base64.b64decode(link_str).decode())
diff --git a/cyberdrop_dl/crawlers/wordpress/_wordpress.py b/cyberdrop_dl/crawlers/wordpress/_wordpress.py
index afc349eb8..f3ca37cbc 100644
--- a/cyberdrop_dl/crawlers/wordpress/_wordpress.py
+++ b/cyberdrop_dl/crawlers/wordpress/_wordpress.py
@@ -170,7 +170,8 @@ class WordPressBaseCrawler(Crawler, is_abc=True):
if link:
await self.handle_link(scrape_item, link)
- def parse_url(self, link: str) -> AbsoluteHttpURL:
+ @classmethod
+ def parse_url(cls, link: str) -> AbsoluteHttpURL:
# TODO: handle more domains and move it to the base crawler
link = _get_original_quality_link(link)
url = super().parse_url(link)
diff --git a/cyberdrop_dl/crawlers/xenforo/f95zone.py b/cyberdrop_dl/crawlers/xenforo/f95zone.py
index 63c13d236..256b8bd49 100644
--- a/cyberdrop_dl/crawlers/xenforo/f95zone.py
+++ b/cyberdrop_dl/crawlers/xenforo/f95zone.py
@@ -29,8 +29,9 @@ class F95ZoneCrawler(XenforoCrawler):
def thumbnail_to_img(cls, url: AbsoluteHttpURL) -> AbsoluteHttpURL:
return url.with_path(url.path.replace("/thumb/", ""))
- def parse_url(self, link: str) -> AbsoluteHttpURL:
+ @classmethod
+ def parse_url(cls, link: str) -> AbsoluteHttpURL:
url = super().parse_url(link)
- if self.is_thumbnail(url):
- return self.thumbnail_to_img(url)
+ if cls.is_thumbnail(url):
+ return cls.thumbnail_to_img(url)
return url
diff --git a/cyberdrop_dl/crawlers/xenforo/titsintops.py b/cyberdrop_dl/crawlers/xenforo/titsintops.py
index 109b4db65..7d9ec398d 100644
--- a/cyberdrop_dl/crawlers/xenforo/titsintops.py
+++ b/cyberdrop_dl/crawlers/xenforo/titsintops.py
@@ -16,8 +16,9 @@ class TitsInTopsCrawler(XenforoCrawler):
DOMAIN: ClassVar[str] = "titsintops"
FOLDER_DOMAIN: ClassVar[str] = "TitsInTops"
- def parse_url(self, link: str) -> AbsoluteHttpURL:
- return super().parse_url(fix_link(link))
+ @classmethod
+ def parse_url(cls, link: str) -> AbsoluteHttpURL:
+ return super().parse_url(_query_to_path(link))
def is_username_or_attachment(self, link_obj: Tag) -> bool:
text = css.text(link_obj)
@@ -29,7 +30,7 @@ class TitsInTopsCrawler(XenforoCrawler):
return super().is_username_or_attachment(link_obj)
-def fix_link(link: str) -> str:
+def _query_to_path(link: str) -> str:
return (
link.replace("index.php%3F", "index.php/")
.replace("index.php?", "index.php/")
diff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.py
index 8fd649a81..ba54f310e 100644
--- a/cyberdrop_dl/utils/utilities.py
+++ b/cyberdrop_dl/utils/utilities.py
@@ -55,29 +55,32 @@ from cyberdrop_dl.utils.logger import log_with_color
if TYPE_CHECKING:
from collections.abc import Callable, Coroutine, Generator, Iterable, Mapping
- from cyberdrop_dl.crawlers import Crawler
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL, MediaItem, ScrapeItem
from cyberdrop_dl.downloader.downloader import Downloader
from cyberdrop_dl.managers.manager import Manager
- CrawerOrDownloader = TypeVar("CrawerOrDownloader", bound=Crawler | Downloader)
- Origin = TypeVar("Origin", bound=ScrapeItem | MediaItem | URL)
-
_P = ParamSpec("_P")
_T = TypeVar("_T")
_R = TypeVar("_R")
class Dataclass(Protocol):
- __dataclass_fields__: ClassVar[dict]
+ __dataclass_fields__: ClassVar[dict[str, Any]]
+
+ class _HasManager(Protocol):
+ manager: Manager
+
+ _HasManagerT = TypeVar("_HasManagerT", bound=_HasManager)
+ Origin = TypeVar("Origin", bound=ScrapeItem | MediaItem | URL)
logger = logging.getLogger(__name__)
+
_ALLOWED_FILEPATH_PUNCTUATION = " .-_!#$%'()+,;=@[]^{}~"
_BLOB_OR_SVG = ("data:", "blob:", "javascript:")
@contextlib.contextmanager
-def error_handling_context(self: Crawler | Downloader, item: ScrapeItem | MediaItem | URL) -> Generator[None]:
+def error_handling_context(self: _HasManager, item: ScrapeItem | MediaItem | URL) -> Generator[None]:
link: URL = item if isinstance(item, URL) else item.url
error_log_msg = origin = exc_info = None
link_to_show: URL | str = ""
@@ -147,32 +150,32 @@ def error_handling_context(self: Crawler | Downloader, item: ScrapeItem | MediaI
@overload
def error_handling_wrapper(
- func: Callable[Concatenate[CrawerOrDownloader, Origin, _P], _R],
-) -> Callable[Concatenate[CrawerOrDownloader, Origin, _P], _R]: ...
+ func: Callable[Concatenate[_HasManagerT, Origin, _P], _R],
+) -> Callable[Concatenate[_HasManagerT, Origin, _P], _R]: ...
@overload
def error_handling_wrapper(
- func: Callable[Concatenate[CrawerOrDownloader, Origin, _P], Coroutine[None, None, _R]],
-) -> Callable[Concatenate[CrawerOrDownloader, Origin, _P], Coroutine[None, None, _R]]: ...
+ func: Callable[Concatenate[_HasManagerT, Origin, _P], Coroutine[None, None, _R]],
+) -> Callable[Concatenate[_HasManagerT, Origin, _P], Coroutine[None, None, _R]]: ...
def error_handling_wrapper(
- func: Callable[Concatenate[CrawerOrDownloader, Origin, _P], _R | Coroutine[None, None, _R]],
-) -> Callable[Concatenate[CrawerOrDownloader, Origin, _P], _R | Coroutine[None, None, _R]]:
+ func: Callable[Concatenate[_HasManagerT, Origin, _P], _R | Coroutine[None, None, _R]],
+) -> Callable[Concatenate[_HasManagerT, Origin, _P], _R | Coroutine[None, None, _R]]:
"""Wrapper handles errors for url scraping."""
if inspect.iscoroutinefunction(func):
@wraps(func)
- async def async_wrapper(self: CrawerOrDownloader, item: Origin, *args: _P.args, **kwargs: _P.kwargs) -> _R:
+ async def async_wrapper(self: _HasManagerT, item: Origin, *args: _P.args, **kwargs: _P.kwargs) -> _R:
with error_handling_context(self, item):
return await func(self, item, *args, **kwargs)
return async_wrapper
@wraps(func)
- def wrapper(self: CrawerOrDownloader, item: Origin, *args: _P.args, **kwargs: _P.kwargs) -> _R:
+ def wrapper(self: _HasManagerT, item: Origin, *args: _P.args, **kwargs: _P.kwargs) -> _R:
with error_handling_context(self, item):
result = func(self, item, *args, **kwargs)
assert not inspect.isawaitable(result)
@@ -397,15 +400,7 @@ def get_text_between(original_text: str, start: str, end: str) -> str:
return original_text[start_index:end_index].strip()
-def parse_url(link_str: str, relative_to: AbsoluteHttpURL | None = None, *, trim: bool = True) -> AbsoluteHttpURL:
- """Parse a string into an absolute URL, handling relative URLs, encoding and optionally removes trailing slash (trimming).
- Raises:
- InvalidURLError: If the input string is not a valid URL or if any other error occurs during parsing.
- TypeError: If `relative_to` is `None` and the parsed URL is relative or has no scheme.
- """
-
- base: AbsoluteHttpURL = relative_to # type: ignore
-
+def _str_to_url(link_str: str) -> URL:
def fix_query_params_encoding(link: str) -> str:
if "?" not in link:
return link
@@ -416,24 +411,37 @@ def parse_url(link_str: str, relative_to: AbsoluteHttpURL | None = None, *, trim
def fix_multiple_slashes(link_str: str) -> str:
return re.sub(r"(?:https?)?:?(\/{3,})", "//", link_str)
+ if not link_str:
+ raise InvalidURLError("link_str is empty", url=link_str)
+
try:
- assert link_str, "link_str is empty"
- assert isinstance(link_str, str), f"link_str must be a string object, got: {link_str!r}"
clean_link_str = fix_multiple_slashes(fix_query_params_encoding(link_str))
- is_encoded = "%" in clean_link_str
- new_url = URL(clean_link_str, encoded=is_encoded)
+ return URL(clean_link_str, encoded="%" in clean_link_str)
- except (AssertionError, AttributeError, ValueError, TypeError) as e:
+ except (AttributeError, ValueError, TypeError) as e:
raise InvalidURLError(str(e), url=link_str) from e
- if not new_url.absolute:
- new_url = base.join(new_url)
- if not new_url.scheme:
- new_url = new_url.with_scheme(base.scheme or "https")
- assert is_absolute_http_url(new_url)
+
+def parse_url(
+ link_str: AbsoluteHttpURL | URL | str, relative_to: AbsoluteHttpURL | None = None, *, trim: bool = True
+) -> AbsoluteHttpURL:
+ """Parse a string into an absolute URL, handling relative URLs, encoding and optionally removes trailing slash (trimming).
+ Raises:
+ InvalidURLError: If the input string is not a valid URL or if any other error occurs during parsing.
+ TypeError: If `relative_to` is `None` and the parsed URL is relative or has no scheme.
+ """
+
+ url = _str_to_url(link_str) if isinstance(link_str, str) else link_str
+ if not url.absolute:
+ if not relative_to:
+ raise InvalidURLError("Relative URL with no known base", url=link_str)
+ url = relative_to.join(url)
+ if not url.scheme:
+ url = url.with_scheme(relative_to.scheme if relative_to else "https")
+ assert is_absolute_http_url(url)
if not trim:
- return new_url
- return remove_trailing_slash(new_url)
+ return url
+ return remove_trailing_slash(url)
def is_absolute_http_url(url: URL) -> TypeGuard[AbsoluteHttpURL]:
diff --git a/tests/test_m3u8.py b/tests/test_m3u8.py
index de7e9953c..a903c4ff5 100644
--- a/tests/test_m3u8.py
+++ b/tests/test_m3u8.py
@@ -100,7 +100,7 @@ def test_get_resolution_from_url(url: str, resolution: tuple[int, int], name: st
[
("https://example.com/780/playlist.m3u8", RuntimeError),
("https://example.com", RuntimeError),
- ("/example.com", AttributeError),
+ ("/example.com", InvalidURLError),
("", InvalidURLError),
],
)