Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: decouple API from crawler (#1943)

NTFSvolume1e72dc9b7379
diff --git a/cyberdrop_dl/clients/http.py b/cyberdrop_dl/clients/http.py
index fb97969cb..6cb1f0a7e 100644
--- a/cyberdrop_dl/clients/http.py
+++ b/cyberdrop_dl/clients/http.py
@@ -37,6 +37,7 @@ if TYPE_CHECKING:
from cyberdrop_dl.url_objects import AbsoluteHttpURL
_JSON_CHECK: ContextVar[Callable[[Any, AbstractResponse[Any]], None] | None] = ContextVar("_JSON_CHECK", default=None)
+RequestContext = contextlib._AsyncGeneratorContextManager[AbstractResponse[Any]] # pyright: ignore[reportPrivateUsage]
logger = logging.getLogger(__name__)
@@ -340,7 +341,7 @@ async def _check_json(response: AbstractResponse[Any]) -> None:
class HTTPMixin:
@signature.copy(HTTPClient.request)
- def request(self, *args: Any, **kwargs: Any) -> contextlib._AsyncGeneratorContextManager[AbstractResponse[Any]]:
+ def request(self, *args: Any, **kwargs: Any) -> RequestContext:
raise NotImplementedError
@signature.copy(request)
diff --git a/cyberdrop_dl/crawlers/acast.py b/cyberdrop_dl/crawlers/acast.py
index e05f6afca..45c9e390f 100644
--- a/cyberdrop_dl/crawlers/acast.py
+++ b/cyberdrop_dl/crawlers/acast.py
@@ -30,7 +30,7 @@ class ACastCrawler(Crawler):
raise ValueError
def __post_init__(self) -> None:
- self.api: ACastAPI = ACastAPI(self)
+ self.api: ACastAPI = ACastAPI.from_crawler(self)
@error_handling_wrapper
async def show(self, scrape_item: ScrapeItem, show_id: str) -> None:
diff --git a/cyberdrop_dl/crawlers/archive_org.py b/cyberdrop_dl/crawlers/archive_org.py
index a61453095..3653f4331 100644
--- a/cyberdrop_dl/crawlers/archive_org.py
+++ b/cyberdrop_dl/crawlers/archive_org.py
@@ -49,7 +49,7 @@ class ArchiveOrgCrawler(Crawler):
raise ValueError
def __post_init__(self) -> None:
- self.api: ArchiveOrgAPI = ArchiveOrgAPI(self)
+ self.api: ArchiveOrgAPI = ArchiveOrgAPI.from_crawler(self)
@error_handling_wrapper
async def item(self, scrape_item: ScrapeItem, identifier: str, base_path: str | None = None) -> None:
diff --git a/cyberdrop_dl/crawlers/bunkr.py b/cyberdrop_dl/crawlers/bunkr.py
index 0b2e96250..5077b4cb9 100644
--- a/cyberdrop_dl/crawlers/bunkr.py
+++ b/cyberdrop_dl/crawlers/bunkr.py
@@ -70,7 +70,7 @@ class BunkrCrawler(Crawler):
return url
def __post_init__(self) -> None:
- self.api: BunkrAPI = BunkrAPI(self)
+ self.api: BunkrAPI = BunkrAPI.from_crawler(self)
self._parse_files = _make_album_parser()
self._redirect_lock: asyncio.Lock = asyncio.Lock()
diff --git a/cyberdrop_dl/crawlers/clyp_it.py b/cyberdrop_dl/crawlers/clyp_it.py
index bb6fc2da4..f63489e78 100644
--- a/cyberdrop_dl/crawlers/clyp_it.py
+++ b/cyberdrop_dl/crawlers/clyp_it.py
@@ -27,7 +27,7 @@ class ClypItCrawler(Crawler):
PRIMARY_URL: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://clyp.it")
def __post_init__(self) -> None:
- self.api: ClypItAPI = ClypItAPI(self)
+ self.api: ClypItAPI = ClypItAPI.from_crawler(self)
async def fetch(self, scrape_item: ScrapeItem) -> None:
match scrape_item.url.parts[1:]:
diff --git a/cyberdrop_dl/crawlers/crawler.py b/cyberdrop_dl/crawlers/crawler.py
index b4679d02f..35de282ce 100644
--- a/cyberdrop_dl/crawlers/crawler.py
+++ b/cyberdrop_dl/crawlers/crawler.py
@@ -14,12 +14,12 @@ from contextvars import ContextVar
from functools import wraps
from pathlib import Path
from types import MappingProxyType
-from typing import TYPE_CHECKING, Any, ClassVar, Concatenate, Final, Generic, Literal, ParamSpec, Self, final
+from typing import TYPE_CHECKING, Any, ClassVar, Concatenate, Final, Literal, ParamSpec, Self, final
from typing_extensions import TypeVar, deprecated
from cyberdrop_dl import aio, env, signature
-from cyberdrop_dl.clients.http import HTTPClient, HTTPMixin
+from cyberdrop_dl.clients.http import HTTPClient, HTTPMixin, RequestContext
from cyberdrop_dl.crawlers._hls import HLSMixin
from cyberdrop_dl.downloader.http import Downloader
from cyberdrop_dl.exceptions import MaxChildrenError, NoExtensionError, ScrapeError
@@ -958,25 +958,36 @@ class Crawler(HTTPMixin, HLSMixin, ABC):
_CrawlerT = TypeVar("_CrawlerT", bound=Crawler)
-_CrawlerT_generic = TypeVar("_CrawlerT_generic", bound=Crawler, default=Crawler)
-
-
-class API(HTTPMixin, ABC, Generic[_CrawlerT_generic]):
- _crawler: _CrawlerT_generic
+class API(HTTPMixin, ABC):
+ # We inherit from ABC to force type checkers to recognize attributes defined in __post_init__ as if they were defined in __init__
@final
- def __init__(self, crawler: _CrawlerT_generic) -> None:
- self._crawler = crawler
- self.PRIMARY_URL: Final = crawler.PRIMARY_URL
- self.parse_url: Final = crawler.parse_url
- self.request: Final = crawler.request
- self.config: Final = crawler.manager.config
+ def __init__(
+ self,
+ PRIMARY_URL: AbsoluteHttpURL, # noqa: N803
+ config: Config,
+ request: Callable[..., RequestContext],
+ parse_url: Callable[[str | yarl.URL], AbsoluteHttpURL] = parse_url,
+ ) -> None:
+ self.PRIMARY_URL: Final = PRIMARY_URL
+ self.parse_url: Final = parse_url
+ self.request: Final = request
+ self.config: Final = config
self.__post_init__()
+ @classmethod
+ def from_crawler(cls, crawler: Crawler) -> Self:
+ return cls(
+ PRIMARY_URL=crawler.PRIMARY_URL,
+ parse_url=crawler.parse_url,
+ request=crawler.request,
+ config=crawler.manager.config,
+ )
+
def __post_init__(self) -> None: ...
def __repr__(self) -> str:
- return f"{type(self).__name__}(crawler={self._crawler.__name__!r})"
+ return f"<{type(self).__name__}(PRIMARY_URL={self.PRIMARY_URL!r})>"
@final
@property
diff --git a/cyberdrop_dl/crawlers/hitomi_la.py b/cyberdrop_dl/crawlers/hitomi_la.py
index f73f5a3d8..831ceb252 100644
--- a/cyberdrop_dl/crawlers/hitomi_la.py
+++ b/cyberdrop_dl/crawlers/hitomi_la.py
@@ -64,7 +64,7 @@ class HitomiLaCrawler(Crawler):
_SCRAPE_SLOTS: ClassVar[int] = 3
def __post_init__(self) -> None:
- self.api: HitomiAPI = HitomiAPI(self)
+ self.api: HitomiAPI = HitomiAPI.from_crawler(self)
async def fetch(self, scrape_item: ScrapeItem) -> None:
match scrape_item.url.parts[1:]:
diff --git a/cyberdrop_dl/crawlers/livestreamfails.py b/cyberdrop_dl/crawlers/livestreamfails.py
index 9b8afbc45..b98781a04 100644
--- a/cyberdrop_dl/crawlers/livestreamfails.py
+++ b/cyberdrop_dl/crawlers/livestreamfails.py
@@ -28,7 +28,7 @@ class LivestreamFailsCrawler(Crawler):
_RATE_LIMIT: ClassVar[RateLimit] = 8, 1
def __post_init__(self) -> None:
- self.api: LivestreamFailsAPI = LivestreamFailsAPI(self)
+ self.api: LivestreamFailsAPI = LivestreamFailsAPI.from_crawler(self)
async def fetch(self, scrape_item: ScrapeItem) -> None:
match scrape_item.url.parts[1:]:
diff --git a/cyberdrop_dl/crawlers/omegascans.py b/cyberdrop_dl/crawlers/omegascans.py
index b0a472a8a..50c193732 100644
--- a/cyberdrop_dl/crawlers/omegascans.py
+++ b/cyberdrop_dl/crawlers/omegascans.py
@@ -49,7 +49,7 @@ class OmegaScansCrawler(Crawler):
@override
async def __async_post_init__(self) -> None:
- self.api: OmegaScansAPI = OmegaScansAPI(self)
+ self.api: OmegaScansAPI = OmegaScansAPI.from_crawler(self)
@error_handling_wrapper
async def series(self, scrape_item: ScrapeItem, series_slug: str) -> None:
diff --git a/cyberdrop_dl/crawlers/pixeldrain.py b/cyberdrop_dl/crawlers/pixeldrain.py
index 09579d4cf..6105cce8f 100644
--- a/cyberdrop_dl/crawlers/pixeldrain.py
+++ b/cyberdrop_dl/crawlers/pixeldrain.py
@@ -128,7 +128,7 @@ class PixelDrainCrawler(Crawler):
_DOWNLOAD_SLOTS: ClassVar[int | None] = 2
def __post_init__(self) -> None:
- self.api: PixelDrainAPI = PixelDrainAPI(self)
+ self.api: PixelDrainAPI = PixelDrainAPI.from_crawler(self)
if self.api.logged_in:
self.downloader.download_slots = None
diff --git a/cyberdrop_dl/crawlers/rule34vault.py b/cyberdrop_dl/crawlers/rule34vault.py
index 19337d5d5..47e43164f 100644
--- a/cyberdrop_dl/crawlers/rule34vault.py
+++ b/cyberdrop_dl/crawlers/rule34vault.py
@@ -26,7 +26,7 @@ class Rule34VaultCrawler(Crawler):
FOLDER_DOMAIN: ClassVar[str] = "Rule34Vault"
def __post_init__(self) -> None:
- self.api: R34VaultAPI = R34VaultAPI(self)
+ self.api: R34VaultAPI = R34VaultAPI.from_crawler(self)
async def fetch(self, scrape_item: ScrapeItem) -> None:
match scrape_item.url.parts[1:]:
diff --git a/cyberdrop_dl/crawlers/rutube.py b/cyberdrop_dl/crawlers/rutube.py
index f2e95b676..16f6fb028 100644
--- a/cyberdrop_dl/crawlers/rutube.py
+++ b/cyberdrop_dl/crawlers/rutube.py
@@ -40,7 +40,7 @@ class RutubeCrawler(Crawler):
raise ValueError
def __post_init__(self) -> None:
- self.api: RutubeAPI = RutubeAPI(self)
+ self.api: RutubeAPI = RutubeAPI.from_crawler(self)
@error_handling_wrapper
async def embed(self, scrape_item: ScrapeItem, embed_id: str) -> None:
diff --git a/cyberdrop_dl/crawlers/whyp_it.py b/cyberdrop_dl/crawlers/whyp_it.py
index 8f7f41a5f..1d316fdfd 100644
--- a/cyberdrop_dl/crawlers/whyp_it.py
+++ b/cyberdrop_dl/crawlers/whyp_it.py
@@ -36,7 +36,7 @@ class WhypItCrawler(Crawler):
raise ValueError
def __post_init__(self) -> None:
- self.api: WhypItAPI = WhypItAPI(self)
+ self.api: WhypItAPI = WhypItAPI.from_crawler(self)
@error_handling_wrapper
async def collection(self, scrape_item: ScrapeItem, collection_id: str) -> None:
diff --git a/cyberdrop_dl/ddos_guard.py b/cyberdrop_dl/ddos_guard.py
index 065eb2b4b..9a5e82b5c 100644
--- a/cyberdrop_dl/ddos_guard.py
+++ b/cyberdrop_dl/ddos_guard.py
@@ -17,16 +17,16 @@ from cyberdrop_dl.exceptions import DDOSGuardError
if TYPE_CHECKING:
from collections.abc import Iterable
- from multidict import MultiDict
+ from multidict import MultiMapping
class _Response(Protocol):
@property
def content_type(self) -> str: ...
@property
- def headers(self) -> MultiDict[str]: ...
+ def headers(self) -> MultiMapping[str]: ...
@property
- def status_code(self) -> int: ...
+ def status(self) -> int: ...
async def text(self) -> str: ...
diff --git a/tests/test_ddos_guard.py b/tests/test_ddos_guard.py
index 7214b2dbf..3ff7b9c4e 100644
--- a/tests/test_ddos_guard.py
+++ b/tests/test_ddos_guard.py
@@ -72,7 +72,7 @@ async def test_ddos_response_should_raise_ddos_guard_error() -> None:
@dataclasses.dataclass(slots=True)
class DummyResponse:
headers: CIMultiDict[str]
- status_code: int = 403
+ status: int = 403
_text: str = ""
content_type: str = "html"