Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: add `struct` dataclass wrapper

NTFSvolumef49d2dc8eeec
diff --git a/cyberdrop_dl/clients/http.py b/cyberdrop_dl/clients/http.py
index 64b3185e6..5bca0b5c8 100644
--- a/cyberdrop_dl/clients/http.py
+++ b/cyberdrop_dl/clients/http.py
@@ -20,7 +20,7 @@ from cyberdrop_dl.cookies import make_simple_cookie
from cyberdrop_dl.exceptions import DDOSGuardError, DownloadError, ScrapeError
from cyberdrop_dl.signature import dataclass_repr
from cyberdrop_dl.utils import enter_context, truncated_preview
-from cyberdrop_dl.utils.dataclass import ConfigDataclass, frozen
+from cyberdrop_dl.utils.dataclass import ConfigDataclass, struct
if TYPE_CHECKING:
from collections.abc import AsyncGenerator, Awaitable, Callable
@@ -524,7 +524,7 @@ class HTTPMixin(HTTPController, Protocol):
@final
-@frozen
+@struct
class HTTPConfig(ConfigDataclass):
__attr_name__: ClassVar[str] = "__http_config__"
headers: dict[str, str] | None = None
diff --git a/cyberdrop_dl/crawlers/crawler.py b/cyberdrop_dl/crawlers/crawler.py
index 92fbcd501..3423088f5 100644
--- a/cyberdrop_dl/crawlers/crawler.py
+++ b/cyberdrop_dl/crawlers/crawler.py
@@ -43,7 +43,7 @@ from cyberdrop_dl.utils._url import (
path_qs_frag,
remove_trailing_slash,
)
-from cyberdrop_dl.utils.dataclass import ConfigDataclass, DictDataclass, frozen
+from cyberdrop_dl.utils.dataclass import ConfigDataclass, DictDataclass, struct
from cyberdrop_dl.utils.errors import OnExceptionCallback, error_handling_context
if TYPE_CHECKING:
@@ -84,7 +84,7 @@ _CHECK_DL_CAPACITY: ContextVar[bool] = ContextVar("_CHECK_DL_CAPACITY")
_HASH_PREFIXES = "md5:", "sha1:", "sha256:", "xxh128:"
-@frozen
+@struct
class _PlaceHolderConfigInclude:
file_id: bool = True
video_codec: bool = True
@@ -112,7 +112,7 @@ _DB_PATH_BUILDERS: MappingProxyType[str, URLHasher] = MappingProxyType(
)
-@frozen(order=False, kw_only=False)
+@struct(kw_only=False)
class ContainerChecker[T: Container, R]:
values: T
check: Callable[[R], bool]
@@ -121,7 +121,7 @@ class ContainerChecker[T: Container, R]:
return self.check(obj)
-@frozen(order=True, kw_only=False)
+@struct(order=True, kw_only=False)
class CrawlerInfo:
site: str
primary_url: AbsoluteHttpURL
@@ -150,7 +150,7 @@ class CrawlerInfo:
return me
-@frozen(kw_only=False)
+@struct(kw_only=False)
class SiteCookies:
raw: http.cookies.BaseCookie[str]
@@ -184,7 +184,7 @@ def _get_logger(crawler_name: str) -> _CrawlerLogger:
@final
-@frozen
+@struct
class URLConfig(ConfigDataclass):
__attr_name__: ClassVar[str] = "__url_config__"
trim: bool | None = None
@@ -193,7 +193,7 @@ class URLConfig(ConfigDataclass):
@final
-@frozen
+@struct
class DownloadConfig(ConfigDataclass):
__attr_name__: ClassVar[str] = "__dl_config__"
slots: int | None = None
diff --git a/cyberdrop_dl/crawlers/hitomi_la.py b/cyberdrop_dl/crawlers/hitomi_la.py
index 7a95bd7b7..a1ef2a660 100644
--- a/cyberdrop_dl/crawlers/hitomi_la.py
+++ b/cyberdrop_dl/crawlers/hitomi_la.py
@@ -6,8 +6,8 @@ import dataclasses
import itertools
import json
import re
-import struct
from collections import defaultdict
+from struct import unpack as struct_unpack
from typing import TYPE_CHECKING, Any, ClassVar
from cyberdrop_dl import aio
@@ -285,7 +285,7 @@ def _re_int_or_none(pattern: str, string: str) -> int | None:
def _decode_nozomi_resp(data: bytes) -> tuple[int, ...]:
- return struct.unpack(f">{(len(data) / 4):.0f}I", data)
+ return struct_unpack(f">{(len(data) / 4):.0f}I", data)
def _parse_search_query(query_string: str) -> Generator[SearchArgs]:
diff --git a/cyberdrop_dl/crawlers/lensdump.py b/cyberdrop_dl/crawlers/lensdump.py
index 936438270..2ae4c0aaa 100644
--- a/cyberdrop_dl/crawlers/lensdump.py
+++ b/cyberdrop_dl/crawlers/lensdump.py
@@ -1,7 +1,6 @@
from __future__ import annotations
import asyncio
-import dataclasses
from typing import TYPE_CHECKING, Any, ClassVar, Self, override
from cyberdrop_dl import aio
@@ -11,7 +10,7 @@ from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedDomains, Suppor
from cyberdrop_dl.exceptions import DownloadError, ScrapeError
from cyberdrop_dl.url_objects import AbsoluteHttpURL
from cyberdrop_dl.utils import css, json
-from cyberdrop_dl.utils.dataclass import deserialize
+from cyberdrop_dl.utils.dataclass import deserialize, struct
from cyberdrop_dl.utils.errors import error_handling_wrapper
if TYPE_CHECKING:
@@ -149,7 +148,7 @@ class LensDumpCrawler(Crawler):
)
[email protected](slots=True, frozen=True)
+@struct
class File:
id: str
type: str
@@ -172,7 +171,7 @@ class File:
)
[email protected](slots=True, frozen=True)
+@struct
class User:
id: str
username: str
@@ -181,7 +180,7 @@ class User:
parse = classmethod(deserialize)
[email protected](slots=True, frozen=True)
+@struct
class FullUser(User):
files: int
albums: int
@@ -189,7 +188,7 @@ class FullUser(User):
tier: str
[email protected](slots=True, frozen=True)
+@struct
class Album:
id: str
name: str
@@ -197,7 +196,7 @@ class Album:
parse = classmethod(deserialize)
[email protected](slots=True, frozen=True)
+@struct
class FullAlbum(Album):
files: int
sub_albums: int
@@ -205,7 +204,7 @@ class FullAlbum(Album):
parent: str | None = None
[email protected](slots=True, frozen=True)
+@struct
class AriaNode:
id: str
name: str
@@ -214,7 +213,7 @@ class AriaNode:
parent: str | None
[email protected](slots=True, frozen=True)
+@struct
class AriaTree:
nodes: Mapping[str, AriaNode]
children: Mapping[str, tuple[str, ...]]
diff --git a/cyberdrop_dl/utils/__init__.py b/cyberdrop_dl/utils/__init__.py
index 747371f64..baff13f02 100644
--- a/cyberdrop_dl/utils/__init__.py
+++ b/cyberdrop_dl/utils/__init__.py
@@ -4,7 +4,7 @@ import contextlib
import itertools
import logging
import sys
-from typing import TYPE_CHECKING, Any, cast
+from typing import TYPE_CHECKING, Any, Concatenate, cast
from cyberdrop_dl.constants import MISSING
from cyberdrop_dl.utils._url import parse_http_url as parse_url # noqa: F401
@@ -147,7 +147,9 @@ def unique[T](itr: Iterable[T], /, key: Callable[[T], Any] | None = None) -> Gen
def fast_cache[T, R](fn: Callable[[T], R]) -> Callable[[T], R]:
- "Like functools.cache but for single argument function and without all the stats logic"
+ """Like functools.cache but for single argument function and without all the stats logic
+
+ cache never expires"""
cache: dict[T, R] = {}
def compute(obj: T) -> R:
@@ -165,3 +167,20 @@ def b64_pad(b64_string: str) -> str:
if pad := len(b64_string) % 4:
return b64_string + "=" * (4 - pad)
return b64_string
+
+
+def bind_fn[T, **P, R](
+ func: Callable[Concatenate[T, P], R],
+ value: T,
+) -> Callable[P, R]:
+ """Bind `value` as the first positional argument of `func`.
+
+ The returned callable accepts the rest of `func`'s arguments.
+
+ Similiar to functools.partial but this preserves type annotations
+ """
+
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
+ return func(value, *args, **kwargs)
+
+ return wrapper
diff --git a/cyberdrop_dl/utils/dataclass.py b/cyberdrop_dl/utils/dataclass.py
index 6f2cc7a18..8102446a5 100644
--- a/cyberdrop_dl/utils/dataclass.py
+++ b/cyberdrop_dl/utils/dataclass.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import dataclasses
import sys
-from typing import TYPE_CHECKING, Any, ClassVar, Final, Protocol, Self, dataclass_transform, overload
+from typing import TYPE_CHECKING, Any, ClassVar, Final, Literal, Protocol, Self, dataclass_transform, overload
from cyberdrop_dl.constants import MISSING
from cyberdrop_dl.utils import fast_cache
@@ -82,25 +82,68 @@ class DictDataclass(_DataClass, Protocol):
@overload
-def frozen[T](cls: None = None, *, order: bool = False, kw_only: bool = True) -> Callable[[type[T]], type[T]]: ...
+def struct[T](
+ cls: None = None,
+ *,
+ order: bool = False,
+ kw_only: bool = True,
+ frozen: bool = True,
+ extras: Literal["forbid", "ignore"] = "forbid",
+) -> Callable[[type[T]], type[T]]: ...
@overload
-def frozen[T](cls: type[T], *, order: bool = False, kw_only: bool = True) -> type[T]: ...
+def struct[T](
+ cls: type[T],
+ *,
+ order: bool = False,
+ kw_only: bool = True,
+ frozen: bool = True,
+ extras: Literal["forbid", "ignore"] = "forbid",
+) -> type[T]: ...
@dataclass_transform(frozen_default=True, kw_only_default=True)
-def frozen[T](
- cls: type[T] | None = None, *, order: bool = False, kw_only: bool = True
+def struct[T](
+ cls: type[T] | None = None,
+ *,
+ order: bool = False,
+ kw_only: bool = True,
+ frozen: bool = True,
+ extras: Literal["forbid", "ignore"] = "forbid",
) -> Callable[[type[T]], type[T]] | type[T]:
- fn = dataclasses.dataclass(frozen=True, kw_only=kw_only, order=order, slots=True)
- return fn if cls is None else fn(cls)
+
+ def wrap(cls: type[T]) -> type[T]:
+ dt_cls = dataclasses.dataclass(frozen=frozen, kw_only=kw_only, order=order, slots=True)(cls)
+ if extras == "ignore":
+ return filter_unknown_kwargs(dt_cls) # pyright: ignore[reportUnknownVariableType, reportArgumentType]
+
+ return dt_cls
+
+ if cls is None:
+ return wrap
+
+ return wrap(cls)
+
+
+def filter_unknown_kwargs[**P, T: _DataClass](cls: type[T]) -> type[T]:
+ """Replace __init__ to filter out invalid kwargs.
+
+ Unknown keys are silently dropped before calling the original __init__.
+ """
+ original_init = cls.__init__
+
+ def init(self: T, *args: P.args, **kwargs: P.kwargs) -> None:
+ original_init(self, *args, **filter_data(type(self), kwargs))
+
+ cls.__init__ = init
+ return cls
CONFIG_REGISTRY: dict[str, type[ConfigDataclass]] = {}
-@frozen
+@struct
class ConfigDataclass:
__attr_name__: ClassVar[str]
__iter__: ClassVar[Final] = DictDataclass.__iter__