Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor. fix formatting of some logs (#122)

NTFSvolume495f1686942b
diff --git a/cyberdrop_dl/clients/__init__.py b/cyberdrop_dl/clients/__init__.py
index d1d31bb57..3b4a24b3d 100644
--- a/cyberdrop_dl/clients/__init__.py
+++ b/cyberdrop_dl/clients/__init__.py
@@ -31,6 +31,36 @@ if TYPE_CHECKING:
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
+
+ def __json__(self) -> dict[str, Any]:
+ resp = self.response.__json__()
+ del resp["created_at"]
+ if type(content := resp["content"]) is str and len(content) > 230:
+ resp["content"] = f"{content[:200]} ... ({len(content) - 200:,} chars omitted)"
+ return resp
+
+ def __str__(self) -> str:
+ return str(self.__json__())
+
+
@dataclasses.dataclass(slots=True)
class HTTPClient:
client_manager: ClientManager
@@ -100,16 +130,6 @@ class HTTPClient:
else:
_ = headers.setdefault("user-agent", self.client_manager.manager.global_config.general.user_agent)
- request_params.setdefault("max_redirects", 8)
-
- request_id = str(uuid.uuid4())
- logger.debug(
- "Starting {} request to {} [id={}]\n{}",
- method,
- url,
- request_id,
- request_params | {"headers": dict(headers)},
- )
async with self.__request(url, method, request_params, impersonate=bool(impersonate)) as resp:
exc = None
@@ -119,7 +139,6 @@ class HTTPClient:
exc = e
raise
finally:
- logger.debug("Finishing {} request [id={}]\n{}", method, request_id, str(resp))
if self._save_responses_to_disk:
_ = self.client_manager.manager.task_group.create_task(
asyncio.to_thread(
@@ -153,20 +172,35 @@ class HTTPClient:
*,
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),
+ )
+ resp = None
+ try:
+ if impersonate:
+ async with contextlib.aclosing(
+ await self.client_manager._curl_session.request(method, str(url), stream=True, **request_params)
+ ) as curl_resp:
+ resp = AbstractResponse.create(curl_resp)
+ yield resp
+ self.__sync_session_cookies(url)
- if impersonate:
- async with contextlib.aclosing(
- await self.client_manager._curl_session.request(method, str(url), stream=True, **request_params)
- ) as curl_resp:
- yield AbstractResponse.create(curl_resp)
- self.__sync_session_cookies(url)
-
- return
-
- async with (
- self.client_manager._session.request(method, url, **request_params) as aio_resp,
- ):
- yield AbstractResponse.create(aio_resp)
+ return
+
+ async with (
+ self.client_manager._session.request(method, url, **request_params) as aio_resp,
+ ):
+ resp = AbstractResponse.create(aio_resp)
+ yield resp
+
+ finally:
+ if resp is not None:
+ logger.debug("Finished %s request [id=%s]\n%s", method, request_id, _LazyResponseLog(resp))
async def _check_response(self, abs_resp: AbstractResponse[Any], url: AbsoluteHttpURL, data: Any | None = None):
"""Checks the HTTP response status and retries DDOS Guard errors with FlareSolverr.
diff --git a/cyberdrop_dl/clients/response.py b/cyberdrop_dl/clients/response.py
index e6fa367da..0fc0bbffa 100644
--- a/cyberdrop_dl/clients/response.py
+++ b/cyberdrop_dl/clients/response.py
@@ -68,12 +68,6 @@ class AbstractResponse(ABC, Generic[_ResponseT]):
def __repr__(self) -> str:
return f"<{type(self).__name__} [{self.status}] ({self.url})>"
- def __str__(self) -> str:
- me = self.__json__()
- for key in ("content", "created_at"):
- del me[key]
- return json.dumps(me, indent=2, ensure_ascii=False)
-
def __json__(self) -> dict[str, Any]:
if content := self._text:
if "json" in self.content_type:
diff --git a/cyberdrop_dl/data_structures/url_objects.py b/cyberdrop_dl/data_structures/url_objects.py
index 3a28c2f9f..135cad846 100644
--- a/cyberdrop_dl/data_structures/url_objects.py
+++ b/cyberdrop_dl/data_structures/url_objects.py
@@ -282,7 +282,7 @@ class ScrapeItem:
yield self
finally:
if old_url != self.url:
- logger.info(f"URL transformation applied: \n {old_url = }\n new_url: {self.url}")
+ logger.info(f"URL transformation applied: \n {old_url = !s}\n new_url: {self.url}")
def __repr__(self) -> str:
return f"{type(self).__name__}(url={self.url!r}, parent_title={self.parent_title!r}, possible_datetime={self.uploaded_at!r}"
diff --git a/cyberdrop_dl/logs.py b/cyberdrop_dl/logs.py
index afe2d38ee..d50d45da2 100644
--- a/cyberdrop_dl/logs.py
+++ b/cyberdrop_dl/logs.py
@@ -64,10 +64,14 @@ class JsonLogRecord(logging.LogRecord):
msg = str(self._proccess_msg(self.msg))
if self.args:
args = tuple(map(self._proccess_msg, self.args))
- try:
- return msg.format(*args)
- except Exception:
- return msg % args
+ if "%" in msg:
+ try:
+ return msg % args
+ except TypeError as e:
+ if not e.args or "not all arguments converted" in e.args[0]:
+ raise
+
+ return msg.format(*args)
return msg
diff --git a/cyberdrop_dl/managers/progress_manager.py b/cyberdrop_dl/managers/progress_manager.py
index ffdadda97..64e43d0ee 100644
--- a/cyberdrop_dl/managers/progress_manager.py
+++ b/cyberdrop_dl/managers/progress_manager.py
@@ -192,7 +192,7 @@ def _log_errors(scrape_errors: Sequence[UiFailureTotal], download_errors: Sequen
for error in scrape_errors:
error_code = error.code if error.code is not None else ""
logger.info(
- f" {error_code:>{padding}}{' ' if padding else ''}{error.msg}: {error.count:,}", extra={"color": "red"}
+ f" {error_code:>{padding}}{' ' if padding else ''}{error.msg}: {error.total:,}", extra={"color": "red"}
)
diff --git a/cyberdrop_dl/storage/_psutil.py b/cyberdrop_dl/storage/_psutil.py
index 920afbeb6..c8ba694f9 100644
--- a/cyberdrop_dl/storage/_psutil.py
+++ b/cyberdrop_dl/storage/_psutil.py
@@ -22,7 +22,7 @@ _PARTITIONS: list[DiskPartition] = []
_UNAVAILABLE: set[Path] = set()
_LOCKS: dict[Path, asyncio.Lock] = defaultdict(asyncio.Lock)
_CHECK_PERIOD: Final = 2 # how often the check_free_space_loop will run (in seconds)
-_LOG_PERIOD: Final = 10 # log storage details every <x> loops, AKA log every 20 (2x10) seconds,
+_LOG_PERIOD: Final = 60 # log storage details every <x> loops
_free_space: dict[Path, int] = {}
@@ -83,7 +83,7 @@ async def has_sufficient_space(folder: Path, /, required_free_space: int) -> boo
free_space = _free_space[mount] = await _get_free_space(mount)
logger.info(f"A new mountpoint ('{mount!s}') will be used for '{folder}'")
- logger.info("Storage status \n{}", _Stats())
+ logger.info("Storage status \n%s", _Stats())
return free_space == -1 or free_space > required_free_space
@@ -149,7 +149,7 @@ async def start_loop() -> None:
await update()
if last_check % _LOG_PERIOD == 0:
- logger.debug("Storage status \n{}", _Stats())
+ logger.debug("Storage status \n%s", _Stats())
await asyncio.sleep(_CHECK_PERIOD)