Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: add stricter URL parsing logic
NTFSvolume6fee504a2630
diff --git a/cyberdrop_dl/exceptions.py b/cyberdrop_dl/exceptions.pyindex 1b51a449b..8a2f0527e 100644--- a/cyberdrop_dl/exceptions.py+++ b/cyberdrop_dl/exceptions.py@@ -227,19 +227,6 @@ class ScrapeError(CDLBaseError):return ScrapeError("Unknown yarl.URL path")-class InvalidURLError(ScrapeError):- def __init__(- self,- message: str | None = None,- origin: HasParents | yarl.URL | None = None,- url: yarl.URL | str = "",- ) -> None:- """This error will be thrown when parsed yarl.URL is not valid."""- ui_failure = "Invalid yarl.URL"- self.url: yarl.URL | str = url- super().__init__(ui_failure, message=message, origin=origin)--class LoginError(CDLBaseError):def __init__(self, message: str | None = None, *, origin: HasParents | yarl.URL | None = None) -> None:"""This error will be thrown when the login fails for a site."""diff --git a/cyberdrop_dl/models/types.py b/cyberdrop_dl/models/types.pyindex 83ea9918b..74e2c0362 100644--- a/cyberdrop_dl/models/types.py+++ b/cyberdrop_dl/models/types.py@@ -1,17 +1,15 @@import datetimefrom pathlib import Path-from typing import Annotated, ClassVar, Literal+from typing import Annotated, Literalfrom pydantic import (AfterValidator,- AnyUrl,BeforeValidator,ByteSize,Field,PlainSerializer,PlainValidator,StringConstraints,- UrlConstraints,WithJsonSchema,)@@ -49,20 +47,9 @@ type Timedelta = Annotated[type RemoveDuplicates[T: tuple[str, ...]] = Annotated[T, AfterValidator(remove_duplicates)]-class _HttpURL(AnyUrl):- _constraints: ClassVar[UrlConstraints] = UrlConstraints(- max_length=2083,- allowed_schemes=["http", "https"],- host_required=True,- )--# Only use this for config validation. To parse URLs internally while scraping, call `parse_url` directlytype HttpURL = Annotated[AbsoluteHttpURL,- PlainValidator(- lambda x: to_yarl_url(_HttpURL(str(x))),- json_schema_input_type=str,- ),+ PlainValidator(to_yarl_url, json_schema_input_type=str),WithJsonSchema({"type": "string", "format": "uri"}),]diff --git a/cyberdrop_dl/models/validators/__init__.py b/cyberdrop_dl/models/validators/__init__.pyindex 2b1e932bf..ca3c2fd2e 100644--- a/cyberdrop_dl/models/validators/__init__.py+++ b/cyberdrop_dl/models/validators/__init__.py@@ -27,10 +27,7 @@ def bytesize_to_str(value: _ConvertibleToInt) -> str:def to_yarl_url(value: object) -> yarl.URL:from cyberdrop_dl.utils import parse_url- try:- return parse_url(str(value))- except Exception as e:- raise ValueError(str(e)) from e+ return parse_url(str(value))def to_bytesize(value: ByteSize | str | int) -> ByteSize:diff --git a/cyberdrop_dl/utils/_url.py b/cyberdrop_dl/utils/_url.pyindex 3701afe66..105db98aa 100644--- a/cyberdrop_dl/utils/_url.py+++ b/cyberdrop_dl/utils/_url.py@@ -1,15 +1,11 @@from __future__ import annotations-import loggingimport reimport yarl-from cyberdrop_dl.exceptions import InvalidURLErrorfrom cyberdrop_dl.url_objects import AbsoluteHttpURL, is_absolute_http_url-logger = logging.getLogger(__name__)-def fix_query_params_encoding(link: str) -> str:if "?" not in link:@@ -19,44 +15,56 @@ def fix_query_params_encoding(link: str) -> str:return f"{parts}?{query_and_frag}"-def fix_multiple_slashes(link_str: str) -> str:- return re.sub(r"(?:https?)?:?(\/{3,})", "//", link_str)-+def fix_multi_slashes(url: str) -> str:+ return re.sub(r"(^/|https?:/)/+", r"\1/", url, count=1)-def str_to_url(link_str: str) -> yarl.URL:- if not link_str:- raise InvalidURLError("link_str is empty", url=link_str)- try:- clean_link_str = fix_multiple_slashes(fix_query_params_encoding(link_str))- return yarl.URL(clean_link_str, encoded="%" in clean_link_str)+def str_to_url(url: str) -> yarl.URL:+ if not url:+ raise ValueError("Empty URL", url)- except (AttributeError, ValueError, TypeError) as e:- raise InvalidURLError(str(e), url=link_str) from e+ clean_url = fix_multi_slashes(fix_query_params_encoding(url))+ return yarl.URL(clean_url, encoded="%" in clean_url)def parse_http_url(- link_str: AbsoluteHttpURL | yarl.URL | str, relative_to: AbsoluteHttpURL | None = None, *, trim: bool = True+ link: yarl.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:+ """Parse a string into an absolute URL, handling relative URLs, encoding and optionally removes trailing slash (trimming)."""++ url = str_to_url(link) if isinstance(link, str) else link+ if not is_absolute_http_url(url):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)+ raise ValueError("Relative URL with no known origin", url)+ url = resolve_url(url, relative_to)++ check_url(url)if not trim:return urlreturn remove_trailing_slash(url)+def resolve_url(url: yarl.URL, origin: AbsoluteHttpURL) -> AbsoluteHttpURL:+ url = origin.join(url) if not url.absolute else url+ if not url.scheme:+ url = url.with_scheme(origin.scheme if origin else "https")+ if not is_absolute_http_url(url):+ raise ValueError(f"Unable to parse an absolute URL from {url}")+ return url+++def check_url(url: yarl.URL) -> None:+ if not url.host:+ raise ValueError("URL has no host", url)+ if "." not in url.host and url.host != "localhost":+ raise ValueError("URL has no TLD", url)+ if len(str(url)) > 2083:+ raise ValueError("URL is too long")++def remove_trailing_slash(url: AbsoluteHttpURL) -> AbsoluteHttpURL:if url.name or url.path == "/":return urldiff --git a/tests/test_m3u8.py b/tests/test_m3u8.pyindex e716b2657..397f10784 100644--- a/tests/test_m3u8.py+++ b/tests/test_m3u8.py@@ -3,7 +3,6 @@ from typing import LiteralStringimport pytest-from cyberdrop_dl.exceptions import InvalidURLErrorfrom cyberdrop_dl.url_objects import AbsoluteHttpURLfrom cyberdrop_dl.utils import m3u8@@ -100,8 +99,8 @@ 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", InvalidURLError),- ("", InvalidURLError),+ ("/example.com", ValueError),+ ("", ValueError),],)def test_get_resolution_from_url_invalid_url(url: str, exception: type[Exception]) -> None:diff --git a/tests/test_utils.py b/tests/test_utils.pyindex f6cb43f4e..2c4bbaf80 100644--- a/tests/test_utils.py+++ b/tests/test_utils.py@@ -8,6 +8,8 @@ import pytestfrom cyberdrop_dl.exceptions import InvalidExtensionError, NoExtensionErrorfrom cyberdrop_dl.filepath import get_filename_and_ext+from cyberdrop_dl.url_objects import AbsoluteHttpURL+from cyberdrop_dl.utils._url import fix_multi_slashes, parse_http_urlclass TestGetFilenameAndExt:@@ -92,3 +94,57 @@ class TestGetFilenameAndExt:def test_no_extension_should_raise_no_ext_error(self) -> None:with pytest.raises(NoExtensionError):get_filename_and_ext("README")+++ "url",+ [+ "http:/s",+ "https://google",+ "/path/to/file",+ "file",+ "/example.com/file",+ ],+)+def test_parsing_invalid_url(url: str) -> None:+ with pytest.raises(ValueError, match="URL"):+ parse_http_url(url)+++ ("url", "expected"),+ [+ ("http:////google.com", "http://google.com"),+ ("https://////google.com", "https://google.com"),+ ("http:/google.com", "http:/google.com"),+ ("//google.com", "//google.com"),+ ("/google.com", "/google.com"),+ ("https://example.com////bar", "https://example.com////bar"),+ ],+)+def test_fix_multi_slashes(url: str, expected: str) -> None:+ assert fix_multi_slashes(url) == expected+++ ("url", "origin", "trim", "expected"),+ [+ ("http://localhost", None, False, "http://localhost/"),+ ("https://////example.com/file//a//b/", None, False, "https://example.com/file//a//b/"),+ ("https://////example.com/file//a//b/", None, True, "https://example.com/file//a//b"),+ ("https://////example.com/file/", None, True, "https://example.com/file"),+ ("https://example.com/file/video.mp4?a=1+b=2", None, True, "https://example.com/file/video.mp4?a=1 b%3D2"),+ (+ "https://example.com/video/file/%E6%92%AE%E5%BD%B1%E4%BC%9A",+ None,+ False,+ "https://example.com/video/file/撮影会",+ ),+ ("//example.com/file", "https://example.net", False, "https://example.com/file"),+ ("example.com/file", "https://example.net", False, "https://example.net/example.com/file"),+ ("/example.com/file", "https://example.net", False, "https://example.net/example.com/file"),+ ],+)+def test_parse_http(url: str, origin: str | None, expected: str, *, trim: bool) -> None:+ result = parse_http_url(url, AbsoluteHttpURL(origin) if origin else None, trim=trim)+ assert result.human_repr() == expected