Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
feat: skip slow downloads (#496)
NTFSvolume48577e8199c7
diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.pyindex ffe77b71e..b7bea82bc 100644--- a/cyberdrop_dl/clients/download_client.py+++ b/cyberdrop_dl/clients/download_client.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport asyncioimport copyimport itertools+import timefrom functools import partial, wrapsfrom http import HTTPStatusfrom pathlib import Path@@ -13,7 +14,12 @@ import aiohttpfrom aiohttp import ClientSessionfrom yarl import URL-from cyberdrop_dl.clients.errors import DownloadError, InsufficientFreeSpaceError, InvalidContentTypeError+from cyberdrop_dl.clients.errors import (+ DownloadError,+ InsufficientFreeSpaceError,+ InvalidContentTypeError,+ SlowDownloadError,+)from cyberdrop_dl.utils.constants import DEBUG_VAR, FILE_FORMATSfrom cyberdrop_dl.utils.logger import log@@ -67,6 +73,8 @@ class DownloadClient:self._global_limiter = self.client_manager.global_rate_limiterself.trace_configs = []self._file_path = None+ self.slow_download_period = 10 # seconds+ self.download_speed_threshold = self.manager.config_manager.settings_data.runtime_options.slow_download_speedif DEBUG_VAR:self.add_request_log_hooks()@@ -163,7 +171,8 @@ class DownloadClient:and any(s in content_type.lower() for s in ("html", "text"))and ext not in FILE_FORMATS["Text"]):- raise InvalidContentTypeError(message=f"Received '{content_type}', was expecting other")+ msg = f"Received '{content_type}', was expecting other"+ raise InvalidContentTypeError(message=msg)if resp.status != HTTPStatus.PARTIAL_CONTENT and media_item.partial_file.is_file():media_item.partial_file.unlink()@@ -193,6 +202,19 @@ class DownloadClient:media_item.partial_file.parent.mkdir(parents=True, exist_ok=True)if not media_item.partial_file.is_file():media_item.partial_file.touch()++ last_slow_speed_read = None++ def check_download_speed():+ nonlocal last_slow_speed_read+ speed = self.manager.progress_manager.file_progress.get_speed(media_item.task_id)+ if speed > self.download_speed_threshold:+ last_slow_speed_read = None+ elif not last_slow_speed_read:+ last_slow_speed_read = time.perf_counter()+ elif time.perf_counter() - last_slow_speed_read > self.slow_download_period:+ raise SlowDownloadError(origin=media_item)+async with aiofiles.open(media_item.partial_file, mode="ab") as f: # type: ignoreasync for chunk in content.iter_chunked(self.client_manager.speed_limiter.chunk_size):chunk_size = len(chunk)@@ -200,6 +222,9 @@ class DownloadClient:await asyncio.sleep(0)await f.write(chunk)update_progress(chunk_size)+ if self.download_speed_threshold:+ check_download_speed()+if not content.total_bytes and not media_item.partial_file.stat().st_size:media_item.partial_file.unlink()raise DownloadError(status=HTTPStatus.INTERNAL_SERVER_ERROR, message="File is empty")diff --git a/cyberdrop_dl/clients/errors.py b/cyberdrop_dl/clients/errors.pyindex 5498a6d12..863b0f102 100644--- a/cyberdrop_dl/clients/errors.py+++ b/cyberdrop_dl/clients/errors.py@@ -56,24 +56,24 @@ class PasswordProtectedError(CDLBaseError):def __init__(self, message: str | None = None, *, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when a file is password protected."""ui_message = "Password Protected"- message = message or "File/Folder is password protected"- super().__init__(ui_message, message=message, origin=origin)+ msg = message or "File/Folder is password protected"+ super().__init__(ui_message, message=msg, origin=origin)class MaxChildrenError(CDLBaseError):def __init__(self, message: str | None = None, *, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when an scrape item reaches its max number or children."""ui_message = "Max Children Reached"- message = message or "Max number of children reached"- super().__init__(ui_message, message=message, origin=origin)+ msg = message or "Max number of children reached"+ super().__init__(ui_message, message=msg, origin=origin)class DDOSGuardError(CDLBaseError):def __init__(self, message: str | None = None, *, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when DDoS-Guard is detected."""ui_message = "DDoS-Guard"- message = message or "DDoS-Guard detected"- super().__init__(ui_message, message=message, origin=origin)+ msg = message or "DDoS-Guard detected"+ super().__init__(ui_message, message=msg, origin=origin)class DownloadError(CDLBaseError):@@ -82,12 +82,21 @@ class DownloadError(CDLBaseError):) -> None:"""This error will be thrown when a download fails."""ui_message = str(status)+ msg = messageif isinstance(status, int):try:- ui_message = f"{status} {HTTPStatus(status).phrase}"+ msg = HTTPStatus(status).phrase+ ui_message = f"{status} {msg}"except ValueError:ui_message = f"{status} HTTP Error"- super().__init__(ui_message, message=message, status=status, origin=origin)+ super().__init__(ui_message, message=msg, status=status, origin=origin)+++class SlowDownloadError(DownloadError):+ def __init__(self, origin: ScrapeItem | MediaItem | URL | None = None) -> None:+ """This error will be thrown when a file will be skipped do to a low download speed."""+ ui_message = "Slow Download"+ super().__init__(ui_message, origin=origin)class InsufficientFreeSpaceError(CDLBaseError):@@ -116,25 +125,12 @@ class MediaFireError(CDLBaseError):class RealDebridError(CDLBaseError):"""Base RealDebrid API error."""- def __init__(self, response: Response, error_codes: dict[int, str]) -> None:+ def __init__(self, response: Response, code: int, message: str) -> None:url = URL(response.url)self.path = url.path- try:- JSONResp: dict = response.json()- code = JSONResp.get("error_code")- if code == 16:- code = 7- error = error_codes.get(code, "Unknown error")-- except AttributeError:- code = response.status_code- error = f"{code} - {HTTPStatus(code).phrase}"-- error = error.capitalize()-- """This error will be thrown when a scrape fails."""+ msg = message.capitalize()ui_message = f"{code} RealDebrid Error"- super().__init__(ui_message, message=error, status=code, origin=url)+ super().__init__(ui_message, message=msg, status=code, origin=url)class ScrapeError(CDLBaseError):@@ -143,12 +139,14 @@ class ScrapeError(CDLBaseError):) -> None:"""This error will be thrown when a scrape fails."""ui_message = str(status)+ msg = messageif isinstance(status, int):try:- ui_message = f"{status} {HTTPStatus(status).phrase}"+ msg = HTTPStatus(status).phrase+ ui_message = f"{status} {msg}"except ValueError:ui_message = f"{status} HTTP Error"- super().__init__(ui_message, message=message, status=status, origin=origin)+ super().__init__(ui_message, message=msg, status=status, origin=origin)class LoginError(CDLBaseError):diff --git a/cyberdrop_dl/config_definitions/config_settings.py b/cyberdrop_dl/config_definitions/config_settings.pyindex 0f7c68ef0..5e86c2328 100644--- a/cyberdrop_dl/config_definitions/config_settings.py+++ b/cyberdrop_dl/config_definitions/config_settings.py@@ -133,6 +133,7 @@ class RuntimeOptions(BaseModel):jdownloader_autostart: bool = Falsejdownloader_whitelist: list[NonEmptyStr] = []deep_scrape: bool = False+ slow_download_speed: ByteSize = ByteSize(0)@field_validator("jdownloader_download_dir", mode="before")@classmethod@@ -148,6 +149,12 @@ class RuntimeOptions(BaseModel):return []return value+ @field_serializer("slow_download_speed")+ def human_readable(self, value: ByteSize | int) -> str:+ if not isinstance(value, ByteSize):+ value = ByteSize(value)+ return value.human_readable(decimal=True)+# TODO: allow None values in sorting format to skip that type of fileclass Sorting(BaseModel):diff --git a/cyberdrop_dl/downloader/downloader.py b/cyberdrop_dl/downloader/downloader.pyindex 157e14749..aaaa2621b 100644--- a/cyberdrop_dl/downloader/downloader.py+++ b/cyberdrop_dl/downloader/downloader.py@@ -42,7 +42,11 @@ def retry(func: Callable) -> None:if e.status != 999:media_item.current_attempt += 1- log_message = f"with status {e.status} and message: {e.message}"+ full_message = str(e.status)+ if e.message != full_message:+ full_message = f"{e.status} - {e.message}"++ log_message = f"with error: {full_message}"log(f"{self.log_prefix} failed: {media_item.url} {log_message}", 40)if media_item.current_attempt < max_attempts:retry_msg = f"Retrying {self.log_prefix.lower()}: {media_item.url} , retry attempt: {media_item.current_attempt + 1}"@@ -162,7 +166,10 @@ class Downloader:except (DownloadError, ClientResponseError) as e:ui_message = getattr(e, "ui_message", e.status)- log_message_short = log_message = f"{e.status} - {e.message}"+ full_message = e.message+ if e.message != ui_message:+ full_message = f"{e.status} - {e.message}"+ log_message_short = log_message = full_messagelog(f"{self.log_prefix} failed: {media_item.url} with error: {log_message}", 40)await self.manager.log_manager.write_download_error_log(media_item.url, log_message_short, origin)self.manager.progress_manager.download_stats_progress.add_failure(ui_message)diff --git a/cyberdrop_dl/managers/real_debrid/api.py b/cyberdrop_dl/managers/real_debrid/api.pyindex 47d1c1c4c..43c660e33 100644--- a/cyberdrop_dl/managers/real_debrid/api.py+++ b/cyberdrop_dl/managers/real_debrid/api.py@@ -82,11 +82,17 @@ class RealDebridApi:@staticmethoddef handle_response(response: Response) -> dict | str | None:try:- response.raise_for_status()JSONResp: dict = response.json()+ response.raise_for_status()except RequestException:- raise RealDebridError(response, ERROR_CODES) from None+ code = JSONResp.get("error_code")+ if not code or code not in ERROR_CODES:+ raise+ code = 7 if code == 16 else code+ msg = ERROR_CODES.get(code, "Unknown error")+ raise RealDebridError(response, code, msg) from Noneexcept AttributeError:+ response.raise_for_status()return response.textelse:return JSONRespdiff --git a/cyberdrop_dl/ui/progress/file_progress.py b/cyberdrop_dl/ui/progress/file_progress.pyindex e870d7d55..58ec8644f 100644--- a/cyberdrop_dl/ui/progress/file_progress.py+++ b/cyberdrop_dl/ui/progress/file_progress.py@@ -64,3 +64,11 @@ class FileProgress(DequeProgress):"""Advances the progress of the given task by the given amount."""self.downloaded_data += amountself._progress.advance(task_id, amount)++ def get_speed(self, task_id: TaskID) -> float:+ if task_id not in self._tasks:+ msg = "Task ID not found"+ raise ValueError(msg)++ task = self._progress._tasks[task_id]+ return task.finished_speed or task.speed or 0diff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.pyindex 6f79d711b..b686b6a2c 100644--- a/cyberdrop_dl/utils/utilities.py+++ b/cyberdrop_dl/utils/utilities.py@@ -51,7 +51,8 @@ def error_handling_wrapper(func: Callable) -> Callable:except Exception as e:exc_info = eif hasattr(e, "status") and hasattr(e, "message"):- log_message_short = log_message = e_ui_failure = f"{e.status} - {e.message}"+ msg = f"{e.status} - {e.message}" if str(e.status) != e.message else e.message+ log_message_short = log_message = e_ui_failure = msgelse:log_message = str(e)log_message_short = "See Log for Details"diff --git a/docs/reference/configuration-options/global-settings/rate-limiting-options.md b/docs/reference/configuration-options/global-settings/rate-limiting-options.mdindex 27ff774ac..99ccab731 100644--- a/docs/reference/configuration-options/global-settings/rate-limiting-options.md+++ b/docs/reference/configuration-options/global-settings/rate-limiting-options.md@@ -34,6 +34,10 @@ The number of seconds to wait while reading data from a website before timing ou|----------------|----------|| `PositiveInt` | `50`|+{% hint style="info" %}+This setting specifies speed and it's interpreted as `<value> / second`. ex: `50` means `50 requests / second`+{% endhint %}+This is the maximum number of requests that can be made by the program per second.## `download_delay`@@ -73,6 +77,10 @@ Some domains have internal limits set by the program, such as `bunkrr`, `cyberfi|----------------|----------|| `ByteSize` | `0`|+{% hint style="info" %}+This setting specifies speed and it's interpreted as `<value> / second`. ex: `8MB` means `8MB/s`+{% endhint %}+This is the max rate of downloading in bytes (per second) for all downloads combined. Set to `0` to disable## `file_host_cache_expire_after`diff --git a/docs/reference/configuration-options/settings/runtime_options.md b/docs/reference/configuration-options/settings/runtime_options.mdindex 602e53221..731c6bffa 100644--- a/docs/reference/configuration-options/settings/runtime_options.md+++ b/docs/reference/configuration-options/settings/runtime_options.md@@ -144,3 +144,15 @@ Use this option only when absolutely necessary, as it will significantly increasFor example, scraping an album normally takes one single request. However, with `--deep-scrape`, CDL will make `n` requests per album, where `n` is the total number of items in the album{% endhint %}++## `slow_download_speed`++| Type | Default |+|----------------|----------|+| `ByteSize` | `0`|++{% hint style="info" %}+This setting specifies speed and it's interpreted as `<value> / second`. ex: `8MB` means `8MB/s`+{% endhint %}++Downloads with a speed lower than this value for more than 10 seconds will be skipped. Set to `0` to disable