Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: move rate limit logic to crawler (#1888)

NTFSvolume9e542b32e8e3
diff --git a/cyberdrop_dl/clients/http.py b/cyberdrop_dl/clients/http.py
index 6a38bb5c0..8d4b6e3bf 100644
--- a/cyberdrop_dl/clients/http.py
+++ b/cyberdrop_dl/clients/http.py
@@ -5,9 +5,10 @@ import contextlib
import logging
import platform
import time
+from abc import ABC, abstractmethod
from contextvars import ContextVar
from http import HTTPStatus
-from typing import TYPE_CHECKING, Any, ClassVar, Protocol, Self, cast, final
+from typing import TYPE_CHECKING, Any, Self, cast, final
import aiohttp
@@ -314,6 +315,14 @@ class HTTPClient:
flaresolverr.verify_solution(self.manager.config.global_settings.general.user_agent, solution)
return AbstractResponse.create(solution)
+ @contextlib.contextmanager
+ def json_context(self, check: Callable[[Any, AbstractResponse[Any]], None], /):
+ token = _JSON_CHECK.set(check)
+ try:
+ yield
+ finally:
+ _JSON_CHECK.reset(token)
+
async def _check_json(response: AbstractResponse[Any]) -> None:
if "json" not in response.content_type:
@@ -324,54 +333,10 @@ async def _check_json(response: AbstractResponse[Any]) -> None:
return
-class HTTPClientProxy(Protocol):
- DOMAIN: ClassVar[str]
- _IMPERSONATE: ClassVar[str | bool | None] = None
-
- @property
- def client(self) -> HTTPClient: ...
-
- @classmethod
- def __json_resp_check__(cls, json_resp: Any, resp: AbstractResponse[Any], /) -> None:
- """Custom check for JSON responses.
-
- This method is called automatically by the `HttpClient` when a JSON response is received from `cls.DOMAIN`
- and it was **NOT** successful (`4xx` or `5xx` HTTP code).
-
- Override this method in subclasses to raise a custom `ScrapeError` instead of the default HTTP error
-
- Example:
- ```python
- if isinstance(json, dict) and json.get("status") == "error":
- raise ScrapeError(422, f"API error: {json['message']}")
- ```
-
- IMPORTANT:
- Cases were the response **IS** successful (200, OK) but the JSON indicates an error
- should be handled by the crawler itself
- """
-
+class HTTPMixin(ABC):
+ @abstractmethod
@signature.copy(HTTPClient.request)
- @contextlib.asynccontextmanager
- async def request(
- self,
- *args: Any,
- impersonate: str | bool | None = None,
- **kwargs: Any,
- ) -> AsyncGenerator[AbstractResponse[Any]]:
- if impersonate is None:
- impersonate = self._IMPERSONATE
-
- token = _JSON_CHECK.set(self.__json_resp_check__)
- try:
- async with (
- self.client.global_rate_limiter,
- self.client.rate_limits[self.DOMAIN],
- self.client.request(*args, impersonate=impersonate, **kwargs) as resp,
- ):
- yield resp
- finally:
- _JSON_CHECK.reset(token)
+ def request(self, *args: Any, **kwargs: Any) -> contextlib._AsyncGeneratorContextManager[AbstractResponse[Any]]: ... # pyright: ignore[reportPrivateUsage]
@signature.copy(request)
async def request_json(self, *args: Any, **kwargs: Any) -> Any:
diff --git a/cyberdrop_dl/crawlers/_hls.py b/cyberdrop_dl/crawlers/_hls.py
index 97c36a169..276d5c0cb 100644
--- a/cyberdrop_dl/crawlers/_hls.py
+++ b/cyberdrop_dl/crawlers/_hls.py
@@ -17,7 +17,7 @@ if TYPE_CHECKING:
from cyberdrop_dl.url_objects import AbsoluteHttpURL
-class HLSParser(ABC):
+class HLSMixin(ABC):
"""Class to fetch and parse HTTP live streams
For multi variant m3u8, the best resolution will be automatically selected"""
@@ -80,7 +80,7 @@ class HLSParser(ABC):
@dataclasses.dataclass(slots=True)
-class SimpleHLSParser(HLSParser):
+class SimpleHLSParser(HLSMixin):
"""A simple parser that does not depend on the manager.
DO NOT USE. This is only for testing"""
diff --git a/cyberdrop_dl/crawlers/crawler.py b/cyberdrop_dl/crawlers/crawler.py
index 840e09fa7..b13b39c5b 100644
--- a/cyberdrop_dl/crawlers/crawler.py
+++ b/cyberdrop_dl/crawlers/crawler.py
@@ -19,8 +19,8 @@ from typing import TYPE_CHECKING, Any, ClassVar, Concatenate, Final, Literal, Pa
from typing_extensions import deprecated
from cyberdrop_dl import aio, env, signature
-from cyberdrop_dl.clients.http import HTTPClient, HTTPClientProxy
-from cyberdrop_dl.crawlers._hls import HLSParser
+from cyberdrop_dl.clients.http import HTTPClient, HTTPMixin
+from cyberdrop_dl.crawlers._hls import HLSMixin
from cyberdrop_dl.downloader.http import Downloader
from cyberdrop_dl.exceptions import MaxChildrenError, NoExtensionError, ScrapeError
from cyberdrop_dl.mediaprops import ISO639Subtitle, Resolution
@@ -48,6 +48,7 @@ if TYPE_CHECKING:
from bs4 import BeautifulSoup, Tag
from curl_cffi.requests.impersonate import BrowserTypeLiteral
+ from cyberdrop_dl.clients.response import AbstractResponse
from cyberdrop_dl.manager import Manager
logger = logging.getLogger(__name__)
@@ -161,7 +162,9 @@ class _CrawlerLogger(logging.LoggerAdapter[logging.Logger]):
return f"[{self._crawler_name}] {msg}", kwargs
-class Crawler(HTTPClientProxy, HLSParser, ABC):
+class Crawler(HTTPMixin, HLSMixin, ABC):
+ DOMAIN: ClassVar[str]
+ _IMPERSONATE: ClassVar[str | bool | None] = None
OLD_DOMAINS: ClassVar[tuple[str, ...]] = ()
SUPPORTED_DOMAINS: ClassVar[SupportedDomains] = ()
SUPPORTED_PATHS: ClassVar[SupportedPaths] = {}
@@ -173,7 +176,6 @@ class Crawler(HTTPClientProxy, HLSParser, ABC):
DEFAULT_TRIM_URLS: ClassVar[bool] = True
FOLDER_DOMAIN: ClassVar[str] = ""
- DOMAIN: ClassVar[str]
PRIMARY_URL: ClassVar[AbsoluteHttpURL]
_FORUM: ClassVar[bool] = False
@@ -302,6 +304,45 @@ class Crawler(HTTPClientProxy, HLSParser, ABC):
if add_to_registry:
Registry.concrete.add(cls)
+ @signature.copy(HTTPClient.request)
+ @contextlib.asynccontextmanager
+ async def request(
+ self,
+ *args: Any,
+ impersonate: str | bool | None = None,
+ **kwargs: Any,
+ ) -> AsyncGenerator[AbstractResponse[Any]]:
+ if impersonate is None:
+ impersonate = self._IMPERSONATE
+
+ with self.client.json_context(self.__json_resp_check__):
+ async with (
+ self.client.rate_limits[self.DOMAIN],
+ self.client.global_rate_limiter,
+ self.client.request(*args, impersonate=impersonate, **kwargs) as resp,
+ ):
+ yield resp
+
+ @classmethod
+ def __json_resp_check__(cls, json_resp: Any, resp: AbstractResponse[Any], /) -> None:
+ """Custom check for JSON responses.
+
+ This method is called automatically by the `HttpClient` when a JSON response is received from `cls.DOMAIN`
+ and it was **NOT** successful (`4xx` or `5xx` HTTP code).
+
+ Override this method in subclasses to raise a custom `ScrapeError` instead of the default HTTP error
+
+ Example:
+ ```python
+ if isinstance(json, dict) and json.get("status") == "error":
+ raise ScrapeError(422, f"API error: {json['message']}")
+ ```
+
+ IMPORTANT:
+ Cases were the response **IS** successful (200, OK) but the JSON indicates an error
+ should be handled by the crawler itself
+ """
+
@final
@staticmethod
def _assert_fields_overrides(subclass: type[Crawler], *fields: str) -> None:
@@ -917,16 +958,12 @@ class Crawler(HTTPClientProxy, HLSParser, ABC):
@dataclasses.dataclass(slots=True)
-class CrawlerAPI:
+class API(HTTPMixin):
crawler: Crawler
- @signature.copy(HTTPClient.request)
- async def request_text(self, *args: Any, **kwargs: Any) -> str:
- return await self.crawler.request_text(*args, **kwargs)
-
- @signature.copy(request_text)
- async def request_json(self, *args: Any, **kwargs: Any) -> Any:
- return await self.crawler.request_json(*args, **kwargs)
+ @signature.copy(Crawler.request)
+ def request(self, *args: Any, **kwargs: Any):
+ return self.crawler.request(*args, **kwargs)
def _make_scrape_mapper_keys(cls: type[Crawler] | Crawler) -> tuple[str, ...]:
diff --git a/cyberdrop_dl/crawlers/omegascans.py b/cyberdrop_dl/crawlers/omegascans.py
index 49b5bd847..8a06a2741 100644
--- a/cyberdrop_dl/crawlers/omegascans.py
+++ b/cyberdrop_dl/crawlers/omegascans.py
@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Any, ClassVar
from typing_extensions import override
-from cyberdrop_dl.crawlers.crawler import Crawler, CrawlerAPI, SupportedPaths
+from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedPaths
from cyberdrop_dl.exceptions import ScrapeError
from cyberdrop_dl.url_objects import AbsoluteHttpURL
from cyberdrop_dl.utils import error_handling_wrapper, parse_url
@@ -72,7 +72,7 @@ class OmegaScansCrawler(Crawler):
scrape_item.add_children()
-class OmegaScansAPI(CrawlerAPI):
+class OmegaScansAPI(API):
ENTRYPOINT: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://api.omegascans.org")
async def chapter(self, series_slug: str, chapter_slug: str) -> Chapter: