Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: define custom request object (#1818)

NTFSvolume4985898069c8
diff --git a/cyberdrop_dl/clients/http.py b/cyberdrop_dl/clients/http.py
index 52f6bf1ad..b3fa35b40 100644
--- a/cyberdrop_dl/clients/http.py
+++ b/cyberdrop_dl/clients/http.py
@@ -5,16 +5,15 @@ import contextlib
import logging
import platform
import time
-import uuid
from contextvars import ContextVar
from http import HTTPStatus
from typing import TYPE_CHECKING, Any, ClassVar, Protocol, Self, cast, final
import aiohttp
-from multidict import CIMultiDict
from cyberdrop_dl import aio, cookies, ddos_guard, signature
from cyberdrop_dl.clients import flaresolverr, tcp
+from cyberdrop_dl.clients.request import Request, normalize_impersonation, prepare_headers
from cyberdrop_dl.clients.response import AbstractResponse
from cyberdrop_dl.cookies import make_simple_cookie
from cyberdrop_dl.exceptions import DDOSGuardError, DownloadError, ScrapeError
@@ -37,21 +36,6 @@ _JSON_CHECK: ContextVar[Callable[[Any, AbstractResponse[Any]], None] | None] = C
logger = logging.getLogger(__name__)
-class _LazyRequestLog:
- def __init__(self, params: Mapping[str, Any]) -> None:
- self.params: Mapping[str, Any] = params
-
- def __json__(self) -> dict[str, Any]:
- params = {k: v for k, v in self.params.items() if v is not None}
- headers = dict(params.pop("headers")) or None
- if headers:
- params.update(headers=headers)
- return params
-
- def __str__(self) -> str:
- return str(self.__json__())
-
-
class _LazyResponseLog:
def __init__(self, response: AbstractResponse[Any]) -> None:
self.response = response
@@ -240,47 +224,30 @@ class HTTPClient:
json: Any = None,
request_params: dict[str, Any] | None = None,
) -> AsyncGenerator[AbstractResponse[Any]]:
- request_params = request_params or {}
- request_params["headers"] = headers = _prepare_headers(headers)
- request_params["data"] = data
- request_params["json"] = json
-
- if method == "GET" and (data or json):
- method = "POST"
- impersonate = self.manager.cli_args.impersonate or impersonate
- if impersonate:
- if impersonate is True:
- impersonate = "chrome"
- request_params["impersonate"] = impersonate
+ request = Request(
+ url=url,
+ method=method,
+ data=data,
+ json=json,
+ params=request_params or {},
+ headers=prepare_headers(headers),
+ impersonate=normalize_impersonation(impersonate),
+ )
- else:
- _ = headers.setdefault("User-Agent", self.manager.config.global_settings.general.user_agent)
+ if not request.impersonate:
+ _ = request.headers.setdefault("User-Agent", self.manager.config.global_settings.general.user_agent)
- async with self._request(url, method, request_params, impersonate=bool(impersonate)) as resp:
+ async with self._request(request) as resp:
yield resp
@contextlib.asynccontextmanager
- async def _request(
- self,
- url: AbsoluteHttpURL,
- method: HttpMethod,
- request_params: Mapping[str, Any],
- *,
- impersonate: bool,
- ) -> AsyncGenerator[AbstractResponse[Any]]:
- request_id = str(uuid.uuid4())
- logger.debug(
- "Starting %s request [id=%s] to %s \n%s",
- method,
- request_id,
- url,
- _LazyRequestLog(request_params),
- )
+ async def _request(self, request: Request) -> AsyncGenerator[AbstractResponse[Any]]:
+ logger.debug("Starting %s request [id=%s]\n%s", request.method, request.id, request)
exc = None
- async with self.__request(url, method, request_params, impersonate=impersonate) as resp:
- resp.id = request_id
- logger.debug("Finished %s request [id=%s]\n%s", method, request_id, _LazyResponseLog(resp))
+ async with self.__request(request) as resp:
+ resp.id = request.id
+ logger.debug("Finished %s request [id=%s]\n%s", request.method, request.id, _LazyResponseLog(resp))
try:
yield resp
except Exception as e:
@@ -288,30 +255,38 @@ class HTTPClient:
raise
finally:
if self._dump_responses:
- self.manager.logs.write_response(url, resp, exc)
+ self.manager.logs.write_response(request.url, resp, exc)
del exc
del resp
@contextlib.asynccontextmanager
- async def __request(
- self,
- url: AbsoluteHttpURL,
- method: HttpMethod,
- request_params: Mapping[str, Any],
- *,
- impersonate: bool,
- ) -> AsyncGenerator[AbstractResponse[Any]]:
-
- if impersonate:
+ async def __request(self, request: Request) -> AsyncGenerator[AbstractResponse[Any]]:
+ if request.impersonate:
async with contextlib.aclosing(
- await self.curl_session.request(method, str(url), stream=True, **request_params)
+ await self.curl_session.request(
+ request.method,
+ str(request.url),
+ stream=True,
+ headers=request.headers,
+ json=request.json,
+ data=request.data,
+ impersonate=request.impersonate,
+ **request.params,
+ )
) as curl_resp:
yield AbstractResponse.create(curl_resp)
- self.__sync_session_cookies(url)
+ self.__sync_session_cookies(request.url)
return
- async with self._session.request(method, url, **request_params) as aio_resp:
+ async with self._session.request(
+ request.method,
+ request.url,
+ headers=request.headers,
+ json=request.json,
+ data=request.data,
+ **request.params,
+ ) as aio_resp:
yield AbstractResponse.create(aio_resp)
async def _flaresolverr_request(
@@ -339,10 +314,6 @@ async def _check_json(response: AbstractResponse[Any]) -> None:
return
-def _prepare_headers(headers: Mapping[str, str] | None) -> CIMultiDict[str]:
- return CIMultiDict(headers) if headers else CIMultiDict()
-
-
class HTTPClientProxy(Protocol):
DOMAIN: ClassVar[str]
_IMPERSONATE: ClassVar[str | bool | None] = None
diff --git a/cyberdrop_dl/clients/request.py b/cyberdrop_dl/clients/request.py
new file mode 100644
index 000000000..4a0b7dace
--- /dev/null
+++ b/cyberdrop_dl/clients/request.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+import dataclasses
+import uuid
+from typing import TYPE_CHECKING, Any, Literal, cast
+
+from multidict import CIMultiDict
+
+if TYPE_CHECKING:
+ from collections.abc import Generator, Mapping
+
+ from curl_cffi.requests.impersonate import BrowserTypeLiteral
+ from curl_cffi.requests.session import HttpMethod
+
+ from cyberdrop_dl.url_objects import AbsoluteHttpURL
+
+
[email protected](slots=True, kw_only=True)
+class Request:
+ url: AbsoluteHttpURL
+ method: HttpMethod = "GET"
+ headers: CIMultiDict[str] = dataclasses.field(default_factory=CIMultiDict)
+ impersonate: BrowserTypeLiteral | Literal[False] | None = None
+ data: Any = None
+ json: Any = None
+ params: dict[str, Any] = dataclasses.field(default_factory=dict)
+
+ id: str = dataclasses.field(init=False, default_factory=lambda: str(uuid.uuid4()))
+
+ def __post_init__(self) -> None:
+ if self.method == "GET" and (self.data or self.json):
+ self.method = "POST"
+
+ def __json__(self) -> dict[str, Any]:
+ return dict(self._serialize())
+
+ def _serialize(self) -> Generator[tuple[str, Any]]:
+ yield "url", str(self.url)
+ if self.headers:
+ yield "headers", dict(self.headers)
+ if self.impersonate is not None:
+ yield "impersonate", self.impersonate
+ if self.data is not None:
+ yield "data", self.data
+ if self.json is not None:
+ yield "json", self.json
+
+ def __str__(self) -> str:
+ return str(self.__json__())
+
+
+def normalize_impersonation(value: str | bool | None, /) -> BrowserTypeLiteral | Literal[False] | None:
+ if value is True:
+ return "chrome"
+ if value is None:
+ return None
+ return cast("BrowserTypeLiteral", value) or False
+
+
+def prepare_headers(headers: Mapping[str, str] | None) -> CIMultiDict[str]:
+ return CIMultiDict(headers) if headers else CIMultiDict()
diff --git a/tests/test_rate_limiter.py b/tests/test_rate_limiter.py
index e461eab89..084b0905f 100644
--- a/tests/test_rate_limiter.py
+++ b/tests/test_rate_limiter.py
@@ -14,6 +14,7 @@ async def consume(limiter: RateLimiter, iterations: int) -> list[float]:
return times
[email protected](reason="flaky")
async def test_no_op_never_throttles() -> None:
limiter = RateLimiter.no_op()
assert limiter.max_rate == 0
@@ -40,6 +41,7 @@ async def test_w_no_burst_spreads_evenly() -> None:
assert delta == pytest.approx(0.1, rel=0.3)
[email protected](reason="flaky")
async def test_default_contructor_allows_burst() -> None:
max_rate = 20
limiter = RateLimiter(max_rate, time_period=1)
diff --git a/tests/test_request.py b/tests/test_request.py
new file mode 100644
index 000000000..f0dbc1974
--- /dev/null
+++ b/tests/test_request.py
@@ -0,0 +1,44 @@
+from __future__ import annotations
+
+from multidict import CIMultiDict
+
+from cyberdrop_dl.clients.request import Request
+from cyberdrop_dl.url_objects import AbsoluteHttpURL
+
+
+def test_get_is_promoted_to_post_when_data_present() -> None:
+ req = Request(url=AbsoluteHttpURL("https://example.com"), method="GET", data=b"payload")
+ assert req.method == "POST"
+
+
+def test_get_is_promoted_to_post_when_json_present() -> None:
+ req = Request(url=AbsoluteHttpURL("https://example.com"), method="GET", json={"key": "value"})
+ assert req.method == "POST"
+
+
+def test_json_omits_empty_headers() -> None:
+ req = Request(
+ url=AbsoluteHttpURL("https://example.com"),
+ method="GET",
+ headers=CIMultiDict(),
+ )
+ assert "headers" not in req.__json__()
+
+
+def test_json_method_returns_expected_dict() -> None:
+ req = Request(
+ url=AbsoluteHttpURL("https://example.com"),
+ method="GET",
+ headers=CIMultiDict([("Accept", "application/json")]),
+ impersonate="firefox",
+ data=None,
+ json={"foo": "bar"},
+ params={},
+ )
+ expected = {
+ "url": "https://example.com",
+ "headers": {"Accept": "application/json"},
+ "impersonate": "firefox",
+ "json": {"foo": "bar"},
+ }
+ assert req.__json__() == expected