Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: additional config changes (#1976)

NTFSvolume95102e5b2faa
diff --git a/.zed/debug.json b/.zed/debug.json
index 42e51800d..b3129e2e2 100644
--- a/.zed/debug.json
+++ b/.zed/debug.json
@@ -12,7 +12,6 @@
"--dump-json",
"--min-free-space",
"512MB",
- "--exclude.no-coomer-post-content",
"--downloads",
"2",
"--flaresolverr",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4b036ce3e..61b631593 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -61,19 +61,19 @@ Several config options have new names:
- `--disable-crawlers`-> `--crawlers.disabled`
- `--disable-file-timestamps`-> `--mtime`
-- `--maximum-audio-duration` -> `--max-audio-duration`
-- `--maximum-image-size` -> `--max-image-size`
+- `--maximum-audio-duration` -> `--audio.duration.max`
+- `--maximum-image-size` -> `--image.size.max`
- `--maximum-number-of-children` -> `--max-children`
-- `--maximum-other-size` -> `--max-non-media-size`
+- `--maximum-other-size` -> `--non-media.size.max`
- `--maximum-thread-depth` -> `--max-thread-depth`
- `--maximum-thread-folder-depth` -> `--max-thread-folder-depth`
-- `--maximum-video-duration` -> `--max-video-duration`
-- `--maximum-video-size` -> `--max-video-size`
-- `--minimum-audio-duration` -> `--min-audio-duration`
-- `--minimum-image-size` -> `--min-image-size`
-- `--minimum-other-size` -> `--min-non-media-size`
-- `--minimum-video-duration` -> `--min-video-duration`
-- `--minimum-video-size` -> `--min-video-size`
+- `--maximum-video-duration` -> `--video.duration.max`
+- `--maximum-video-size` -> `--video.size.max`
+- `--minimum-audio-duration` -> `--audio.duration.min`
+- `--minimum-image-size` -> `--image.size.min`
+- `--minimum-other-size` -> `--non-media.size.min`
+- `--minimum-video-duration` -> `--video.duration.min`
+- `--minimum-video-size` -> `--video.size.min`
- `--required-free-space` -> `--min-free-space`
- `--print-stats` -> `--stats` , `--no-stats`
- `--send-deleted-to-trash` -> `--hashing.dedupe.use-trash-bin`
@@ -141,6 +141,13 @@ The behavior of `--before` and `--after` has been reversed and the `--exclude` p
- `--download-delay` -> `--delay`
- `--download-speed-limit` -> `--speed-limit`
+#### Generic crawlers
+
+- `--wordpress-media` -> `--crawlers.generic.wordpress-media`
+- `--wordpress-html` -> `--crawlers.generic.wordpress-html`
+- `--discourse` -> `--crawlers.generic.discourse`
+- `--chevereto` -> `--crawlers.generic.chevereto`
+
### Removed
- Support for python 3.11
diff --git a/cyberdrop_dl/cli/download.py b/cyberdrop_dl/cli/download.py
index 213bd9c03..6a4c68f5b 100644
--- a/cyberdrop_dl/cli/download.py
+++ b/cyberdrop_dl/cli/download.py
@@ -12,6 +12,7 @@ from cyberdrop_dl.cli import CLIargs
from cyberdrop_dl.config import Config
from cyberdrop_dl.exceptions import CDLConfigRuntimeErrorsGroup
from cyberdrop_dl.logs import log_spacer, set_console_level, setup_file_logging
+from cyberdrop_dl.models import merge_models
from cyberdrop_dl.models.types import HttpURL # noqa: TC001
from cyberdrop_dl.utils import cleanup
@@ -127,7 +128,8 @@ def download(
config = config or Config()
appdata = AppData.from_path(cli.appdata_folder) if cli.appdata_folder else AppData.default()
- config = Config.from_file(cli.config_file or appdata.config_file) | config
+ config_file = cli.config_file or appdata.config_file
+ config = merge_models(Config.from_file(config_file), config)
if not config.ui.mode.is_fullscreen or cli.config_file or config.sort.enabled:
cli.download = True
@@ -143,7 +145,7 @@ def _check_ffmpeg(config: Config) -> None:
exc.add_note("Disable sorting or install ffmpeg")
errors.append(exc)
- if config.media_duration_limits.needs_ffmpeg:
+ if config.filters.duration.needs_ffmpeg:
exc = RuntimeError("Filtering files by duration requires 'ffmpeg' to be installed")
exc.add_note("Disable media duration limits or install ffmpeg")
errors.append(exc)
diff --git a/cyberdrop_dl/clients/downloads.py b/cyberdrop_dl/clients/downloads.py
index 86e8d702e..e80609cc0 100644
--- a/cyberdrop_dl/clients/downloads.py
+++ b/cyberdrop_dl/clients/downloads.py
@@ -379,6 +379,8 @@ class DownloadClient:
return media.size in limits.image
if media.ext in FileExt.VIDEO:
return media.size in limits.video
+ if media.ext in FileExt.AUDIO:
+ return media.size in limits.audio
return media.size in limits.non_media
@@ -421,7 +423,7 @@ async def filter_by_duration(media_item: MediaItem, config: Config) -> bool:
if media_item.is_segment:
return False
- duration_limits = config.media_duration_limits.ranges
+ duration_limits = config.filters.duration.ranges
if media_item.ext.lower() in FileExt.VIDEO:
limits = duration_limits.video
elif media_item.ext.lower() in FileExt.AUDIO:
diff --git a/cyberdrop_dl/clients/http.py b/cyberdrop_dl/clients/http.py
index d6d303347..8aadab585 100644
--- a/cyberdrop_dl/clients/http.py
+++ b/cyberdrop_dl/clients/http.py
@@ -165,7 +165,11 @@ class HTTPClient:
headers={"User-Agent": self.config.network.user_agent},
raise_for_status=False,
cookie_jar=self.cookies,
- timeout=self.config.network.aiohttp_timeout,
+ timeout=aiohttp.ClientTimeout(
+ total=None,
+ sock_connect=self.config.network.connection_timeout,
+ sock_read=self.config.network.read_timeout,
+ ),
proxy=self.config.network.proxy,
connector=tcp.create_connector(self._ssl_context),
requote_redirect_url=False,
diff --git a/cyberdrop_dl/clients/jdownloader.py b/cyberdrop_dl/clients/jdownloader.py
index 769c24e61..5a1712ecb 100644
--- a/cyberdrop_dl/clients/jdownloader.py
+++ b/cyberdrop_dl/clients/jdownloader.py
@@ -22,9 +22,9 @@ if TYPE_CHECKING:
@dataclasses.dataclass(frozen=True, slots=True)
class JDConfig:
enabled: bool
- username: str
- password: str
- device: str
+ username: str | None
+ password: str | None
+ device: str | None
download_dir: Path
autostart: bool
whitelist: tuple[str, ...]
diff --git a/cyberdrop_dl/config/__init__.py b/cyberdrop_dl/config/__init__.py
index 192eb938d..c4a613282 100644
--- a/cyberdrop_dl/config/__init__.py
+++ b/cyberdrop_dl/config/__init__.py
@@ -2,50 +2,53 @@ from __future__ import annotations
import logging
from pathlib import Path
-from typing import TYPE_CHECKING, Annotated, Literal, Self
+from typing import TYPE_CHECKING, Annotated, Literal, final
from cyclopts import App, Parameter
from cyclopts.bind import normalize_tokens
-from pydantic import BaseModel, ByteSize, Field, NonNegativeInt, PositiveInt, field_validator
+from pydantic import AfterValidator, BaseModel, Field, NonNegativeInt, PositiveInt
from cyberdrop_dl import yaml
from cyberdrop_dl.constants import DEFAULT_DOWNLOAD_STORAGE
from cyberdrop_dl.exceptions import CDLConfigRuntimeErrorsGroup
-from cyberdrop_dl.models import merge_models
-from cyberdrop_dl.models.types import ByteSizeSerilized, ListNonNegativeInt # noqa: TC001
+from cyberdrop_dl.models import DeferedModel
+from cyberdrop_dl.models.types import ByteSizeSerilized, FalsyAsTuple # noqa: TC001
from cyberdrop_dl.models.validators import to_bytesize
from cyberdrop_dl.utils import cleanup
-from .auth import AuthSettings, Notifications
+from .auth import Authentication, Notifications
from .crawlers import Crawlers
-from .settings import (
- Downloads,
- Filters,
- GenericCrawlers,
- Hashing,
- Jdownloader,
- Logs,
- MediaDurationLimits,
- Network,
- Sort,
- SubFolders,
- UIOptions,
-)
+from .filters import Filters
+from .settings import Downloads, Hashing, Jdownloader, Logs, Network, Sort, SubFolders, UIOptions
if TYPE_CHECKING:
from collections.abc import Iterable
-_app: App | None = None
MIN_REQUIRED_FREE_SPACE = to_bytesize("512MB")
+MODULE_PATH = Path(__file__).parent
logger = logging.getLogger(__name__)
+_app: App | None = None
+
+
+@final
+class Files:
+ DEFAULT: Path = MODULE_PATH / "default.json"
+ SCHEMA: Path = MODULE_PATH / "schema.json"
+
+ @staticmethod
+ def update() -> None:
+ import json
+
+ Files.SCHEMA.write_text(json.dumps(Config.model_json_schema(), indent=2, ensure_ascii=False))
+ Files.DEFAULT.write_text(Config().model_dump_json(indent=2))
@Parameter(name="*")
-class Config(BaseModel):
+class Config(DeferedModel, title="cyberdrop-dl config"):
__final__: Literal[True] = True
- auth: AuthSettings = Field(default_factory=AuthSettings)
+ auth: Authentication = Field(default_factory=Authentication)
cookies: Path | None = None
"File/folder to import cookies from (.txt Netscape files)"
@@ -57,23 +60,23 @@ class Config(BaseModel):
downloads: Downloads = Field(default_factory=Downloads)
dump_json: Annotated[bool, Parameter(alias="-j")] = False
filters: Filters = Field(default_factory=Filters)
- generic_crawlers: GenericCrawlers = Field(default_factory=GenericCrawlers)
hashing: Hashing = Field(default_factory=Hashing)
ignore_history: bool = False
jdownloader: Jdownloader = Field(default_factory=Jdownloader)
logs: Logs = Field(default_factory=Logs)
- max_children: ListNonNegativeInt = []
+ max_children: FalsyAsTuple[NonNegativeInt] = ()
max_file_name_length: PositiveInt = 95
max_folder_name_length: PositiveInt = 60
max_thread_depth: NonNegativeInt = 0
max_thread_folder_depth: NonNegativeInt | None = None
- media_duration_limits: MediaDurationLimits = Field(default_factory=MediaDurationLimits)
- min_free_space: ByteSizeSerilized = to_bytesize("5GB")
+ min_free_space: Annotated[ByteSizeSerilized, AfterValidator(lambda x: max(x, MIN_REQUIRED_FREE_SPACE))] = (
+ to_bytesize("5GB")
+ )
mtime: bool = True
network: Network = Field(default_factory=Network)
notifications: Notifications = Field(default_factory=Notifications)
show_stats: Annotated[bool, Parameter(name="stats")] = True
- "show stats report at the end of a run"
+ "Show stats report at the end of a run"
sort: Sort = Field(default_factory=Sort)
subfolders: SubFolders = Field(default_factory=SubFolders)
@@ -82,6 +85,9 @@ class Config(BaseModel):
_resolved: bool = False
_source: Path | None = None
+ def __repr_args__(self) -> list[tuple[str, Path | None]]:
+ return [("source", self._source)]
+
@property
def source(self) -> Path | None:
return self._source
@@ -93,16 +99,13 @@ class Config(BaseModel):
except FileNotFoundError:
default = Config()
if _save_if_not_found:
- yaml.save(file, default.model_dump())
+ yaml.save(file, default.model_dump(mode="json"))
return default
- config = Config.model_validate(content, extra="forbid")
+ config = Config.model_validate(content)
config._source = file
return config
- def __or__(self, other: Self) -> Self:
- return merge_models(self, other)
-
@staticmethod
def parse_args(tokens: str | Iterable[str]) -> Config:
global _app # noqa: PLW0603
@@ -124,25 +127,20 @@ class Config(BaseModel):
cleanup.rm_empty_dirs(self.logs.folder)
self._resolved = True
- @field_validator("min_free_space", mode="after")
- @classmethod
- def _override_min_storage(cls, value: ByteSize) -> ByteSize:
- return max(value, MIN_REQUIRED_FREE_SPACE)
-
def _resolve_paths(model: BaseModel) -> None:
- for name, value in vars(model).items():
- if isinstance(value, Path):
- if "{config}" in str(value):
+ for field_name, field_value in model:
+ if isinstance(field_value, Path):
+ if "{config}" in str(field_value):
error = ValueError(
- f"Using '{{config}}' as reference on a path is no longer supported: {value} ({name})"
+ f"Using '{{config}}' as reference on a path is no longer supported: {field_value} ({field_name})"
)
raise CDLConfigRuntimeErrorsGroup("Invalid config", (error,))
- object.__setattr__(model, name, value.expanduser().resolve().absolute())
+ object.__setattr__(model, field_name, field_value.expanduser().resolve().absolute())
- elif isinstance(value, BaseModel):
- _resolve_paths(value)
+ elif isinstance(field_value, BaseModel):
+ _resolve_paths(field_value)
def merge_additive_args[T: list[str] | tuple[str, ...]](cli_values: T, config_values: Iterable[str]) -> T:
@@ -163,4 +161,4 @@ def _coerce(*, config: Config | None = None) -> Config:
return config
-__all__ = ["Config"]
+__all__ = ["Config", "Files"]
diff --git a/cyberdrop_dl/config/auth.py b/cyberdrop_dl/config/auth.py
index c267c4cca..7079acb8a 100644
--- a/cyberdrop_dl/config/auth.py
+++ b/cyberdrop_dl/config/auth.py
@@ -1,48 +1,76 @@
+from __future__ import annotations
+
import importlib.util
import logging
-from typing import Annotated
+from typing import TYPE_CHECKING, Any, override
from cyclopts import Parameter
-from pydantic import BeforeValidator, Field
+from pydantic import Field, Secret
-from cyberdrop_dl.models import AliasModel, AppriseURL
-from cyberdrop_dl.models.validators import falsy_as_none
+from cyberdrop_dl.models import AppriseURL, DeferedModel
+from cyberdrop_dl.models.types import FalsyAsNone # noqa: TC001
-logger = logging.getLogger(__name__)
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+logger = logging.getLogger(__name__)
_HAS_APPRISE = importlib.util.find_spec("apprise") is not None
-class ApiKeyAuth(AliasModel):
- api_key: str = ""
+def _censor(value: object) -> object:
+ if value and isinstance(value, str):
+ return Secret(value)
+ return value
-class EmailAuth(AliasModel):
- email: str = ""
- password: str = ""
+@Parameter(show=False)
+class CensoredModel(DeferedModel):
+ @override
+ def __repr_name__(self) -> str:
+ return ""
+ @override
+ def __repr__(self) -> str:
+ return f"{{{self.__repr_str__(', ')}}}"
-class JDownloaderAuth(AliasModel):
- username: str = ""
- password: str = ""
- device: str = ""
+ @override
+ def __repr_args__(self) -> Iterable[tuple[str | None, Any]]:
+ for name, value in super().__repr_args__():
+ yield name, _censor(value)
-@Parameter(show=False)
-class AuthSettings(AliasModel):
- gofile: ApiKeyAuth = Field(default_factory=ApiKeyAuth)
- jdownloader: JDownloaderAuth = Field(default_factory=JDownloaderAuth)
- meganz: EmailAuth = Field(default_factory=EmailAuth)
- pixeldrain: ApiKeyAuth = Field(default_factory=ApiKeyAuth)
- realdebrid: ApiKeyAuth = Field(default_factory=ApiKeyAuth)
+class ApiKeyAuth(CensoredModel):
+ api_key: str | None = None
-@Parameter(show=False)
-class Notifications(AliasModel):
+class EmailAuth(CensoredModel):
+ email: str | None = None
+ password: str | None = None
+
+
+class JDownloaderAuth(CensoredModel):
+ username: str | None = None
+ password: str | None = None
+ device: str | None = None
+
+
+class Notifications(CensoredModel):
apprise: tuple[AppriseURL, ...] = ()
- webhook: Annotated[AppriseURL | None, BeforeValidator(falsy_as_none)] = None
+ webhook: FalsyAsNone[AppriseURL] = None
def model_post_init(self, *_) -> None:
if self.apprise and not _HAS_APPRISE:
logger.warning("Found apprise URLs for notifications but apprise is not installed. Ignoring")
self.apprise = ()
+
+
+@Parameter(show=False)
+class Authentication(DeferedModel):
+ gofile: ApiKeyAuth = Field(default_factory=ApiKeyAuth)
+ jdownloader: JDownloaderAuth = Field(default_factory=JDownloaderAuth)
+ mega_nz: EmailAuth = Field(default_factory=EmailAuth)
+ pixeldrain: ApiKeyAuth = Field(default_factory=ApiKeyAuth)
+ realdebrid: ApiKeyAuth = Field(default_factory=ApiKeyAuth)
+
+ def censored_dump(self) -> dict[str, bool]:
+ return {site: all(vars(credentials).values()) for site, credentials in self}
diff --git a/cyberdrop_dl/config/crawlers.py b/cyberdrop_dl/config/crawlers.py
index 5d750196a..eb7395158 100644
--- a/cyberdrop_dl/config/crawlers.py
+++ b/cyberdrop_dl/config/crawlers.py
@@ -1,27 +1,29 @@
-from typing import Annotated
+from pydantic import Field
-from pydantic import AfterValidator, Field
+from cyberdrop_dl.models import ConfigGroup, DeferedModel
+from cyberdrop_dl.models.types import FalsyAsTuple, HttpURL, NonEmptyStr, RemoveDuplicates
-from cyberdrop_dl.models import AliasModel, ConfigGroup
-from cyberdrop_dl.models.types import ListNonEmptyStr
-
-def _unique_list[T](value: list[T]) -> list[T]:
- return sorted(set(value)) # pyright: ignore[reportArgumentType, reportUnknownVariableType]
-
-
-class KemonoConfig(AliasModel):
+class KemonoConfig(DeferedModel):
ignore_ads: bool = False
ignore_post_content: bool = True
-class TiktokConfig(AliasModel):
+class TikTokConfig(DeferedModel):
original: bool = False
-class Crawlers(ConfigGroup):
- disabled: Annotated[ListNonEmptyStr, AfterValidator(_unique_list)] = Field(default_factory=list)
+class GenericCrawlers(DeferedModel):
+ wordpress_media: FalsyAsTuple[HttpURL] = ()
+ wordpress_html: FalsyAsTuple[HttpURL] = ()
+ discourse: FalsyAsTuple[HttpURL] = ()
+ chevereto: FalsyAsTuple[HttpURL] = ()
+
+
+class Crawlers(ConfigGroup, name=None):
+ disabled: RemoveDuplicates[FalsyAsTuple[NonEmptyStr]] = ()
+ generic: GenericCrawlers = Field(default_factory=GenericCrawlers)
kemono: KemonoConfig = Field(default_factory=KemonoConfig)
coomer: KemonoConfig = Field(default_factory=KemonoConfig)
nekohouse: KemonoConfig = Field(default_factory=KemonoConfig)
- tiktok: TiktokConfig = Field(default_factory=TiktokConfig)
+ tiktok: TikTokConfig = Field(default_factory=TikTokConfig)
diff --git a/cyberdrop_dl/config/default.json b/cyberdrop_dl/config/default.json
new file mode 100644
index 000000000..414c0cdc6
--- /dev/null
+++ b/cyberdrop_dl/config/default.json
@@ -0,0 +1,186 @@
+{
+ "auth": {
+ "gofile": {
+ "api_key": null
+ },
+ "jdownloader": {
+ "username": null,
+ "password": null,
+ "device": null
+ },
+ "mega_nz": {
+ "email": null,
+ "password": null
+ },
+ "pixeldrain": {
+ "api_key": null
+ },
+ "realdebrid": {
+ "api_key": null
+ }
+ },
+ "cookies": null,
+ "crawlers": {
+ "disabled": [],
+ "generic": {
+ "wordpress_media": [],
+ "wordpress_html": [],
+ "discourse": [],
+ "chevereto": []
+ },
+ "kemono": {
+ "ignore_ads": false,
+ "ignore_post_content": true
+ },
+ "coomer": {
+ "ignore_ads": false,
+ "ignore_post_content": true
+ },
+ "nekohouse": {
+ "ignore_ads": false,
+ "ignore_post_content": true
+ },
+ "tiktok": {
+ "original": false
+ }
+ },
+ "deep_scrape": false,
+ "delete_empty_folders": true,
+ "delete_partial_files": false,
+ "download_folder": "Downloads",
+ "downloads": {
+ "concurrency": 15,
+ "concurrency_per_domain": 5,
+ "attempts": 2,
+ "delay": 0.0,
+ "slow_speed": "0B",
+ "speed_limit": "0B",
+ "jitter": 0.0,
+ "skip_and_mark_completed": false,
+ "concurrent_segments": 10
+ },
+ "dump_json": false,
+ "filters": {
+ "files": {
+ "audio": true,
+ "images": true,
+ "videos": true,
+ "non_media": true
+ },
+ "sizes": {
+ "image": {
+ "min": "0B",
+ "max": "0B"
+ },
+ "video": {
+ "min": "0B",
+ "max": "0B"
+ },
+ "audio": {
+ "min": "0B",
+ "max": "0B"
+ },
+ "non_media": {
+ "min": "0B",
+ "max": "0B"
+ }
+ },
+ "duration": {
+ "video": {
+ "min": "0:00:00",
+ "max": "0:00:00"
+ },
+ "audio": {
+ "min": "0:00:00",
+ "max": "0:00:00"
+ }
+ },
+ "before": null,
+ "after": null,
+ "filename_regex": null,
+ "only_hosts": [],
+ "skip_hosts": [],
+ "allow_files_with_no_extension": false
+ },
+ "hashing": {
+ "mode": "in_place",
+ "algorithms": [
+ "xxh128",
+ "md5",
+ "sha256"
+ ],
+ "dedupe": {
+ "enabled": true,
+ "use_trash_bin": true
+ }
+ },
+ "ignore_history": false,
+ "jdownloader": {
+ "enabled": false,
+ "autostart": false,
+ "download_dir": null,
+ "whitelist": []
+ },
+ "logs": {
+ "level": "DEBUG",
+ "console_level": null,
+ "files": {
+ "main": "downloader.log",
+ "download_errors": "Download_Error_URLs.csv",
+ "scrape_errors": "Scrape_Error_URLs.csv",
+ "unsupported": "Unsupported_URLs.csv"
+ },
+ "folder": "AppData/Logs",
+ "expire_after": null,
+ "rotate": false
+ },
+ "max_children": [],
+ "max_file_name_length": 95,
+ "max_folder_name_length": 60,
+ "max_thread_depth": 0,
+ "max_thread_folder_depth": null,
+ "min_free_space": "5.0GB",
+ "mtime": true,
+ "network": {
+ "dump_responses": false,
+ "flaresolverr": null,
+ "proxy": null,
+ "rate_limit": 25.0,
+ "connection_timeout": 15.0,
+ "read_timeout": 300.0,
+ "ssl_context": "truststore+certifi",
+ "user_agent": "Mozilla/5.0 (X11; Linux x86_64; rv:150.0) Gecko/20100101 Firefox/150.0"
+ },
+ "notifications": {
+ "apprise": [],
+ "webhook": null
+ },
+ "show_stats": true,
+ "sort": {
+ "enabled": false,
+ "input_folder": null,
+ "output_folder": "Downloads/Cyberdrop-DL Sorted Downloads",
+ "formats": {
+ "audio": "{sort_dir}/{base_dir}/Audio/{filename}{ext}",
+ "image": "{sort_dir}/{base_dir}/Images/{filename}{ext}",
+ "non_media": "{sort_dir}/{base_dir}/Other/{filename}{ext}",
+ "video": "{sort_dir}/{base_dir}/Videos/{filename}{ext}",
+ "incrementer": " ({i})"
+ }
+ },
+ "subfolders": {
+ "create": true,
+ "include": {
+ "album_id": false,
+ "thread_id": false,
+ "domain": true
+ },
+ "separate_posts_format": "{default}",
+ "separate_posts": false
+ },
+ "ui": {
+ "mode": "fullscreen",
+ "portrait": false,
+ "refresh_rate": 10.0
+ }
+}
diff --git a/cyberdrop_dl/config/filters.py b/cyberdrop_dl/config/filters.py
new file mode 100644
index 000000000..96bc5f34d
--- /dev/null
+++ b/cyberdrop_dl/config/filters.py
@@ -0,0 +1,150 @@
+from __future__ import annotations
+
+import dataclasses
+import datetime
+import re # noqa: TC003
+from typing import TYPE_CHECKING, Self
+
+from cyclopts import Parameter
+from pydantic import ByteSize, Field
+
+from cyberdrop_dl.models import ConfigGroup, DeferedModel
+from cyberdrop_dl.models.types import ( # noqa: TC001
+ ByteSizeSerilized,
+ FalsyAsNone,
+ FalsyAsTuple,
+ NonEmptyStr,
+ RemoveDuplicates,
+ Timedelta,
+)
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+
+def _limit_suffix(suffix: str) -> Callable[[str], str]:
+ def transform(name: str) -> str:
+ return name if name in {"min", "max"} else f"{name}.{suffix}"
+
+ return transform
+
+
[email protected](slots=True, frozen=True)
+class _FloatRange:
+ min: float
+ max: float
+
+ def __post_init__(self) -> None:
+ if not self.max:
+ object.__setattr__(self, "max", float("inf"))
+
+ def __contains__(self, value: float, /) -> bool:
+ return self.min <= value <= self.max
+
+ @classmethod
+ def parse(cls, min: float, max: float | None) -> Self | None: # noqa: A002
+ if not min and not max:
+ return None
+ return cls(min, max or float("inf"))
+
+
[email protected](slots=True, frozen=True)
+class _FileSizeRanges:
+ video: _FloatRange
+ image: _FloatRange
+ audio: _FloatRange
+ non_media: _FloatRange
+
+
+class _SizeLimit(DeferedModel):
+ min: ByteSizeSerilized = ByteSize(0)
+ max: ByteSizeSerilized = ByteSize(0)
+
+
+@Parameter(name="*", name_transform=_limit_suffix("size"))
+class _FileSizes(DeferedModel):
+ image: _SizeLimit = Field(default_factory=_SizeLimit)
+ video: _SizeLimit = Field(default_factory=_SizeLimit)
+ audio: _SizeLimit = Field(default_factory=_SizeLimit)
+ non_media: _SizeLimit = Field(default_factory=_SizeLimit)
+ _ranges: _FileSizeRanges | None = None
+
+ @property
+ def ranges(self) -> _FileSizeRanges:
+ if self._ranges is None:
+ self._ranges = _FileSizeRanges(
+ video=_FloatRange(
+ self.video.min,
+ self.video.max,
+ ),
+ image=_FloatRange(
+ self.image.min,
+ self.image.max,
+ ),
+ non_media=_FloatRange(
+ self.non_media.min,
+ self.non_media.max,
+ ),
+ audio=_FloatRange(
+ self.audio.min,
+ self.audio.max,
+ ),
+ )
+ return self._ranges
+
+
[email protected](slots=True, frozen=True)
+class _DurationRanges:
+ video: _FloatRange | None
+ audio: _FloatRange | None
+
+
+class _DurationLimit(DeferedModel):
+ min: Timedelta = datetime.timedelta(seconds=0)
+ max: Timedelta = datetime.timedelta(seconds=0)
+
+
+@Parameter(name="*", name_transform=_limit_suffix("duration"))
+class _DurationLimits(DeferedModel):
+ video: _DurationLimit = Field(default_factory=_DurationLimit)
+ audio: _DurationLimit = Field(default_factory=_DurationLimit)
+ _ranges: _DurationRanges | None = None
+
+ @property
+ def needs_ffmpeg(self) -> bool:
+ return bool(self.video.min or self.video.max or self.audio.min or self.audio.max)
+
+ @property
+ def ranges(self) -> _DurationRanges:
+ if self._ranges is None:
+ self._ranges = _DurationRanges(
+ video=_FloatRange.parse(
+ self.video.min.total_seconds(),
+ self.video.max.total_seconds(),
+ ),
+ audio=_FloatRange.parse(
+ self.audio.min.total_seconds(),
+ self.audio.max.total_seconds(),
+ ),
+ )
+ return self._ranges
+
+
+@Parameter(name="*")
+class _FileFilter(DeferedModel):
+ audio: bool = True
+ images: bool = True
+ videos: bool = True
+ non_media: bool = True
+
+
+class Filters(ConfigGroup):
+ files: _FileFilter = Field(default_factory=_FileFilter)
+ sizes: _FileSizes = Field(default_factory=_FileSizes)
+ duration: _DurationLimits = Field(default_factory=_DurationLimits)
+ before: FalsyAsNone[datetime.date] = None
+ after: FalsyAsNone[datetime.date] = None
+ filename_regex: FalsyAsNone[re.Pattern[str]] = None
+ only_hosts: RemoveDuplicates[FalsyAsTuple[NonEmptyStr]] = ()
+ skip_hosts: RemoveDuplicates[FalsyAsTuple[NonEmptyStr]] = ()
+ allow_files_with_no_extension: bool = False
diff --git a/cyberdrop_dl/config/schema.json b/cyberdrop_dl/config/schema.json
new file mode 100644
index 000000000..9836a0eb6
--- /dev/null
+++ b/cyberdrop_dl/config/schema.json
@@ -0,0 +1,1051 @@
+{
+ "$defs": {
+ "ApiKeyAuth": {
+ "additionalProperties": false,
+ "properties": {
+ "api_key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Api Key"
+ }
+ },
+ "title": "ApiKeyAuth",
+ "type": "object"
+ },
+ "AppriseURL": {
+ "additionalProperties": false,
+ "properties": {
+ "url": {
+ "format": "uri",
+ "minLength": 1,
+ "title": "Url",
+ "type": "string"
+ },
+ "tags": {
+ "default": [],
+ "items": {
+ "type": "string"
+ },
+ "title": "Tags",
+ "type": "array",
+ "uniqueItems": true
+ }
+ },
+ "required": [
+ "url"
+ ],
+ "title": "AppriseURL",
+ "type": "object"
+ },
+ "Authentication": {
+ "additionalProperties": false,
+ "properties": {
+ "gofile": {
+ "$ref": "#/$defs/ApiKeyAuth"
+ },
+ "jdownloader": {
+ "$ref": "#/$defs/JDownloaderAuth"
+ },
+ "mega_nz": {
+ "$ref": "#/$defs/EmailAuth"
+ },
+ "pixeldrain": {
+ "$ref": "#/$defs/ApiKeyAuth"
+ },
+ "realdebrid": {
+ "$ref": "#/$defs/ApiKeyAuth"
+ }
+ },
+ "title": "Authentication",
+ "type": "object"
+ },
+ "ByteSizeSerilized": {
+ "anyOf": [
+ {
+ "pattern": "^\\s*(\\d*\\.?\\d+)\\s*(\\w+)?",
+ "type": "string"
+ },
+ {
+ "minimum": 0,
+ "type": "integer"
+ }
+ ]
+ },
+ "CSVPath": {
+ "format": "path",
+ "type": "string"
+ },
+ "Crawlers": {
+ "additionalProperties": false,
+ "properties": {
+ "disabled": {
+ "$ref": "#/$defs/RemoveDuplicates_FalsyAsTuple_NonEmptyStr__",
+ "default": []
+ },
+ "generic": {
+ "$ref": "#/$defs/GenericCrawlers"
+ },
+ "kemono": {
+ "$ref": "#/$defs/KemonoConfig"
+ },
+ "coomer": {
+ "$ref": "#/$defs/KemonoConfig"
+ },
+ "nekohouse": {
+ "$ref": "#/$defs/KemonoConfig"
+ },
+ "tiktok": {
+ "$ref": "#/$defs/TikTokConfig"
+ }
+ },
+ "title": "Crawlers",
+ "type": "object"
+ },
+ "Dedupe": {
+ "additionalProperties": false,
+ "properties": {
+ "enabled": {
+ "default": true,
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "use_trash_bin": {
+ "default": true,
+ "title": "Use Trash Bin",
+ "type": "boolean"
+ }
+ },
+ "title": "Dedupe",
+ "type": "object"
+ },
+ "Downloads": {
+ "additionalProperties": false,
+ "properties": {
+ "concurrency": {
+ "default": 15,
+ "exclusiveMinimum": 0,
+ "title": "Concurrency",
+ "type": "integer"
+ },
+ "concurrency_per_domain": {
+ "default": 5,
+ "exclusiveMinimum": 0,
+ "title": "Concurrency Per Domain",
+ "type": "integer"
+ },
+ "attempts": {
+ "default": 2,
+ "exclusiveMinimum": 0,
+ "title": "Attempts",
+ "type": "integer"
+ },
+ "delay": {
+ "default": 0.0,
+ "minimum": 0,
+ "title": "Delay",
+ "type": "number"
+ },
+ "slow_speed": {
+ "$ref": "#/$defs/ByteSizeSerilized",
+ "default": 0
+ },
+ "speed_limit": {
+ "$ref": "#/$defs/ByteSizeSerilized",
+ "default": 0
+ },
+ "jitter": {
+ "default": 0,
+ "minimum": 0,
+ "title": "Jitter",
+ "type": "number"
+ },
+ "skip_and_mark_completed": {
+ "default": false,
+ "title": "Skip And Mark Completed",
+ "type": "boolean"
+ },
+ "concurrent_segments": {
+ "default": 10,
+ "exclusiveMinimum": 0,
+ "title": "Concurrent Segments",
+ "type": "integer"
+ }
+ },
+ "title": "Downloads",
+ "type": "object"
+ },
+ "EmailAuth": {
+ "additionalProperties": false,
+ "properties": {
+ "email": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Email"
+ },
+ "password": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Password"
+ }
+ },
+ "title": "EmailAuth",
+ "type": "object"
+ },
+ "FalsyAsNone_Annotated_Literal__truststore____certifi____truststore_certifi____BeforeValidator__": {
+ "anyOf": [
+ {
+ "enum": [
+ "truststore",
+ "certifi",
+ "truststore+certifi"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "FalsyAsNone_Annotated_float__Gt__": {
+ "anyOf": [
+ {
+ "exclusiveMinimum": 0,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "FalsyAsNone_AppriseURL_": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/AppriseURL"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "FalsyAsNone_FormatStr_": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/FormatStr"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "FalsyAsNone_HttpURL_": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/HttpURL"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "FalsyAsNone_LogLevel_": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/LogLevel"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "FalsyAsNone_Path_": {
+ "anyOf": [
+ {
+ "format": "path",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "FalsyAsNone_Pattern_str__": {
+ "anyOf": [
+ {
+ "format": "regex",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "FalsyAsNone_Timedelta_": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/Timedelta"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "FalsyAsNone_date_": {
+ "anyOf": [
+ {
+ "format": "date",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "FalsyAsTuple_Annotated_int__Ge__": {
+ "items": {
+ "minimum": 0,
+ "type": "integer"
+ },
+ "type": "array"
+ },
+ "FalsyAsTuple_HttpURL_": {
+ "items": {
+ "$ref": "#/$defs/HttpURL"
+ },
+ "type": "array"
+ },
+ "FalsyAsTuple_NonEmptyStr_": {
+ "items": {
+ "$ref": "#/$defs/NonEmptyStr"
+ },
+ "type": "array"
+ },
+ "Filters": {
+ "additionalProperties": false,
+ "properties": {
+ "files": {
+ "$ref": "#/$defs/_FileFilter"
+ },
+ "sizes": {
+ "$ref": "#/$defs/_FileSizes"
+ },
+ "duration": {
+ "$ref": "#/$defs/_DurationLimits"
+ },
+ "before": {
+ "$ref": "#/$defs/FalsyAsNone_date_",
+ "default": null
+ },
+ "after": {
+ "$ref": "#/$defs/FalsyAsNone_date_",
+ "default": null
+ },
+ "filename_regex": {
+ "$ref": "#/$defs/FalsyAsNone_Pattern_str__",
+ "default": null
+ },
+ "only_hosts": {
+ "$ref": "#/$defs/RemoveDuplicates_FalsyAsTuple_NonEmptyStr__",
+ "default": []
+ },
+ "skip_hosts": {
+ "$ref": "#/$defs/RemoveDuplicates_FalsyAsTuple_NonEmptyStr__",
+ "default": []
+ },
+ "allow_files_with_no_extension": {
+ "default": false,
+ "title": "Allow Files With No Extension",
+ "type": "boolean"
+ }
+ },
+ "title": "Filters",
+ "type": "object"
+ },
+ "FormatStr": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "GenericCrawlers": {
+ "additionalProperties": false,
+ "properties": {
+ "wordpress_media": {
+ "$ref": "#/$defs/FalsyAsTuple_HttpURL_",
+ "default": []
+ },
+ "wordpress_html": {
+ "$ref": "#/$defs/FalsyAsTuple_HttpURL_",
+ "default": []
+ },
+ "discourse": {
+ "$ref": "#/$defs/FalsyAsTuple_HttpURL_",
+ "default": []
+ },
+ "chevereto": {
+ "$ref": "#/$defs/FalsyAsTuple_HttpURL_",
+ "default": []
+ }
+ },
+ "title": "GenericCrawlers",
+ "type": "object"
+ },
+ "HashMode": {
+ "enum": [
+ "off",
+ "in_place",
+ "post_download"
+ ],
+ "title": "HashMode",
+ "type": "string"
+ },
+ "Hashing": {
+ "additionalProperties": false,
+ "properties": {
+ "mode": {
+ "$ref": "#/$defs/HashMode",
+ "default": "in_place"
+ },
+ "algorithms": {
+ "default": [
+ "xxh128",
+ "md5",
+ "sha256"
+ ],
+ "items": {
+ "enum": [
+ "xxh128",
+ "md5",
+ "sha256"
+ ],
+ "type": "string"
+ },
+ "title": "Algorithms",
+ "type": "array"
+ },
+ "dedupe": {
+ "$ref": "#/$defs/Dedupe"
+ }
+ },
+ "title": "Hashing",
+ "type": "object"
+ },
+ "HttpURL": {
+ "format": "uri",
+ "type": "string"
+ },
+ "JDownloaderAuth": {
+ "additionalProperties": false,
+ "properties": {
+ "username": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Username"
+ },
+ "password": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Password"
+ },
+ "device": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Device"
+ }
+ },
+ "title": "JDownloaderAuth",
+ "type": "object"
+ },
+ "Jdownloader": {
+ "additionalProperties": false,
+ "properties": {
+ "enabled": {
+ "default": false,
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "autostart": {
+ "default": false,
+ "title": "Autostart",
+ "type": "boolean"
+ },
+ "download_dir": {
+ "$ref": "#/$defs/FalsyAsNone_Path_",
+ "default": null
+ },
+ "whitelist": {
+ "$ref": "#/$defs/RemoveDuplicates_FalsyAsTuple_NonEmptyStr__",
+ "default": []
+ }
+ },
+ "title": "Jdownloader",
+ "type": "object"
+ },
+ "KemonoConfig": {
+ "additionalProperties": false,
+ "properties": {
+ "ignore_ads": {
+ "default": false,
+ "title": "Ignore Ads",
+ "type": "boolean"
+ },
+ "ignore_post_content": {
+ "default": true,
+ "title": "Ignore Post Content",
+ "type": "boolean"
+ }
+ },
+ "title": "KemonoConfig",
+ "type": "object"
+ },
+ "LogFiles": {
+ "additionalProperties": false,
+ "properties": {
+ "main": {
+ "$ref": "#/$defs/LogPath",
+ "default": "downloader.log"
+ },
+ "download_errors": {
+ "$ref": "#/$defs/CSVPath",
+ "default": "Download_Error_URLs.csv"
+ },
+ "scrape_errors": {
+ "$ref": "#/$defs/CSVPath",
+ "default": "Scrape_Error_URLs.csv"
+ },
+ "unsupported": {
+ "$ref": "#/$defs/CSVPath",
+ "default": "Unsupported_URLs.csv"
+ }
+ },
+ "title": "LogFiles",
+ "type": "object"
+ },
+ "LogLevel": {
+ "enum": [
+ "DEBUG",
+ "INFO",
+ "WARNING",
+ "ERROR",
+ "CRITICAL"
+ ],
+ "type": "string"
+ },
+ "LogPath": {
+ "format": "path",
+ "type": "string"
+ },
+ "Logs": {
+ "additionalProperties": false,
+ "properties": {
+ "level": {
+ "$ref": "#/$defs/LogLevel",
+ "default": "DEBUG"
+ },
+ "console_level": {
+ "$ref": "#/$defs/FalsyAsNone_LogLevel_",
+ "default": null
+ },
+ "files": {
+ "$ref": "#/$defs/LogFiles"
+ },
+ "folder": {
+ "default": "AppData/Logs",
+ "format": "path",
+ "title": "Folder",
+ "type": "string"
+ },
+ "expire_after": {
+ "$ref": "#/$defs/FalsyAsNone_Timedelta_",
+ "default": null
+ },
+ "rotate": {
+ "default": false,
+ "title": "Rotate",
+ "type": "boolean"
+ }
+ },
+ "title": "Logs",
+ "type": "object"
+ },
+ "Network": {
+ "additionalProperties": false,
+ "properties": {
+ "dump_responses": {
+ "default": false,
+ "title": "Dump Responses",
+ "type": "boolean"
+ },
+ "flaresolverr": {
+ "$ref": "#/$defs/FalsyAsNone_HttpURL_",
+ "default": null
+ },
+ "proxy": {
+ "$ref": "#/$defs/FalsyAsNone_HttpURL_",
+ "default": null
+ },
+ "rate_limit": {
+ "default": 25,
+ "exclusiveMinimum": 0,
+ "title": "Rate Limit",
+ "type": "number"
+ },
+ "connection_timeout": {
+ "default": 15,
+ "exclusiveMinimum": 0,
+ "title": "Connection Timeout",
+ "type": "number"
+ },
+ "read_timeout": {
+ "$ref": "#/$defs/FalsyAsNone_Annotated_float__Gt__",
+ "default": 300
+ },
+ "ssl_context": {
+ "$ref": "#/$defs/FalsyAsNone_Annotated_Literal__truststore____certifi____truststore_certifi____BeforeValidator__",
+ "default": "truststore+certifi"
+ },
+ "user_agent": {
+ "$ref": "#/$defs/NonEmptyStr",
+ "default": "Mozilla/5.0 (X11; Linux x86_64; rv:150.0) Gecko/20100101 Firefox/150.0"
+ }
+ },
+ "title": "Network",
+ "type": "object"
+ },
+ "NonEmptyStr": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "Notifications": {
+ "additionalProperties": false,
+ "properties": {
+ "apprise": {
+ "default": [],
+ "items": {
+ "$ref": "#/$defs/AppriseURL"
+ },
+ "title": "Apprise",
+ "type": "array"
+ },
+ "webhook": {
+ "$ref": "#/$defs/FalsyAsNone_AppriseURL_",
+ "default": null
+ }
+ },
+ "title": "Notifications",
+ "type": "object"
+ },
+ "RemoveDuplicates_FalsyAsTuple_NonEmptyStr__": {
+ "$ref": "#/$defs/FalsyAsTuple_NonEmptyStr_"
+ },
+ "Sort": {
+ "additionalProperties": false,
+ "properties": {
+ "enabled": {
+ "default": false,
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "input_folder": {
+ "$ref": "#/$defs/FalsyAsNone_Path_",
+ "default": null
+ },
+ "output_folder": {
+ "default": "Downloads/Cyberdrop-DL Sorted Downloads",
+ "format": "path",
+ "title": "Output Folder",
+ "type": "string"
+ },
+ "formats": {
+ "$ref": "#/$defs/SortFormats"
+ }
+ },
+ "title": "Sort",
+ "type": "object"
+ },
+ "SortFormats": {
+ "additionalProperties": false,
+ "properties": {
+ "audio": {
+ "$ref": "#/$defs/FalsyAsNone_FormatStr_",
+ "default": "{sort_dir}/{base_dir}/Audio/{filename}{ext}"
+ },
+ "image": {
+ "$ref": "#/$defs/FalsyAsNone_FormatStr_",
+ "default": "{sort_dir}/{base_dir}/Images/{filename}{ext}"
+ },
+ "non_media": {
+ "$ref": "#/$defs/FalsyAsNone_FormatStr_",
+ "default": "{sort_dir}/{base_dir}/Other/{filename}{ext}"
+ },
+ "video": {
+ "$ref": "#/$defs/FalsyAsNone_FormatStr_",
+ "default": "{sort_dir}/{base_dir}/Videos/{filename}{ext}"
+ },
+ "incrementer": {
+ "$ref": "#/$defs/FormatStr",
+ "default": " ({i})"
+ }
+ },
+ "title": "SortFormats",
+ "type": "object"
+ },
+ "SubFolders": {
+ "additionalProperties": false,
+ "properties": {
+ "create": {
+ "default": true,
+ "title": "Create",
+ "type": "boolean"
+ },
+ "include": {
+ "$ref": "#/$defs/_SubFoldersInclude"
+ },
+ "separate_posts_format": {
+ "$ref": "#/$defs/FormatStr",
+ "default": "{default}"
+ },
+ "separate_posts": {
+ "default": false,
+ "title": "Separate Posts",
+ "type": "boolean"
+ }
+ },
+ "title": "SubFolders",
+ "type": "object"
+ },
+ "TikTokConfig": {
+ "additionalProperties": false,
+ "properties": {
+ "original": {
+ "default": false,
+ "title": "Original",
+ "type": "boolean"
+ }
+ },
+ "title": "TikTokConfig",
+ "type": "object"
+ },
+ "Timedelta": {
+ "format": "duration",
+ "ge": "PT0S",
+ "type": "string"
+ },
+ "UIMode": {
+ "enum": [
+ "disabled",
+ "activity",
+ "simple",
+ "fullscreen"
+ ],
+ "title": "UIMode",
+ "type": "string"
+ },
+ "UIOptions": {
+ "additionalProperties": false,
+ "properties": {
+ "mode": {
+ "$ref": "#/$defs/UIMode",
+ "default": "fullscreen"
+ },
+ "portrait": {
+ "default": false,
+ "title": "Portrait",
+ "type": "boolean"
+ },
+ "refresh_rate": {
+ "default": 10.0,
+ "exclusiveMinimum": 0,
+ "title": "Refresh Rate",
+ "type": "number"
+ }
+ },
+ "title": "UIOptions",
+ "type": "object"
+ },
+ "_DurationLimit": {
+ "additionalProperties": false,
+ "properties": {
+ "min": {
+ "$ref": "#/$defs/Timedelta",
+ "default": "PT0S"
+ },
+ "max": {
+ "$ref": "#/$defs/Timedelta",
+ "default": "PT0S"
+ }
+ },
+ "title": "_DurationLimit",
+ "type": "object"
+ },
+ "_DurationLimits": {
+ "additionalProperties": false,
+ "properties": {
+ "video": {
+ "$ref": "#/$defs/_DurationLimit"
+ },
+ "audio": {
+ "$ref": "#/$defs/_DurationLimit"
+ }
+ },
+ "title": "_DurationLimits",
+ "type": "object"
+ },
+ "_FileFilter": {
+ "additionalProperties": false,
+ "properties": {
+ "audio": {
+ "default": true,
+ "title": "Audio",
+ "type": "boolean"
+ },
+ "images": {
+ "default": true,
+ "title": "Images",
+ "type": "boolean"
+ },
+ "videos": {
+ "default": true,
+ "title": "Videos",
+ "type": "boolean"
+ },
+ "non_media": {
+ "default": true,
+ "title": "Non Media",
+ "type": "boolean"
+ }
+ },
+ "title": "_FileFilter",
+ "type": "object"
+ },
+ "_FileSizes": {
+ "additionalProperties": false,
+ "properties": {
+ "image": {
+ "$ref": "#/$defs/_SizeLimit"
+ },
+ "video": {
+ "$ref": "#/$defs/_SizeLimit"
+ },
+ "audio": {
+ "$ref": "#/$defs/_SizeLimit"
+ },
+ "non_media": {
+ "$ref": "#/$defs/_SizeLimit"
+ }
+ },
+ "title": "_FileSizes",
+ "type": "object"
+ },
+ "_SizeLimit": {
+ "additionalProperties": false,
+ "properties": {
+ "min": {
+ "$ref": "#/$defs/ByteSizeSerilized",
+ "default": 0
+ },
+ "max": {
+ "$ref": "#/$defs/ByteSizeSerilized",
+ "default": 0
+ }
+ },
+ "title": "_SizeLimit",
+ "type": "object"
+ },
+ "_SubFoldersInclude": {
+ "additionalProperties": false,
+ "properties": {
+ "album_id": {
+ "default": false,
+ "title": "Album Id",
+ "type": "boolean"
+ },
+ "thread_id": {
+ "default": false,
+ "title": "Thread Id",
+ "type": "boolean"
+ },
+ "domain": {
+ "default": true,
+ "title": "Domain",
+ "type": "boolean"
+ }
+ },
+ "title": "_SubFoldersInclude",
+ "type": "object"
+ }
+ },
+ "additionalProperties": false,
+ "properties": {
+ "auth": {
+ "$ref": "#/$defs/Authentication"
+ },
+ "cookies": {
+ "anyOf": [
+ {
+ "format": "path",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Cookies"
+ },
+ "crawlers": {
+ "$ref": "#/$defs/Crawlers"
+ },
+ "deep_scrape": {
+ "default": false,
+ "title": "Deep Scrape",
+ "type": "boolean"
+ },
+ "delete_empty_folders": {
+ "default": true,
+ "title": "Delete Empty Folders",
+ "type": "boolean"
+ },
+ "delete_partial_files": {
+ "default": false,
+ "title": "Delete Partial Files",
+ "type": "boolean"
+ },
+ "download_folder": {
+ "default": "Downloads",
+ "format": "path",
+ "title": "Download Folder",
+ "type": "string"
+ },
+ "downloads": {
+ "$ref": "#/$defs/Downloads"
+ },
+ "dump_json": {
+ "default": false,
+ "title": "Dump Json",
+ "type": "boolean"
+ },
+ "filters": {
+ "$ref": "#/$defs/Filters"
+ },
+ "hashing": {
+ "$ref": "#/$defs/Hashing"
+ },
+ "ignore_history": {
+ "default": false,
+ "title": "Ignore History",
+ "type": "boolean"
+ },
+ "jdownloader": {
+ "$ref": "#/$defs/Jdownloader"
+ },
+ "logs": {
+ "$ref": "#/$defs/Logs"
+ },
+ "max_children": {
+ "$ref": "#/$defs/FalsyAsTuple_Annotated_int__Ge__",
+ "default": []
+ },
+ "max_file_name_length": {
+ "default": 95,
+ "exclusiveMinimum": 0,
+ "title": "Max File Name Length",
+ "type": "integer"
+ },
+ "max_folder_name_length": {
+ "default": 60,
+ "exclusiveMinimum": 0,
+ "title": "Max Folder Name Length",
+ "type": "integer"
+ },
+ "max_thread_depth": {
+ "default": 0,
+ "minimum": 0,
+ "title": "Max Thread Depth",
+ "type": "integer"
+ },
+ "max_thread_folder_depth": {
+ "anyOf": [
+ {
+ "minimum": 0,
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Max Thread Folder Depth"
+ },
+ "min_free_space": {
+ "$ref": "#/$defs/ByteSizeSerilized",
+ "default": 5000000000
+ },
+ "mtime": {
+ "default": true,
+ "title": "Mtime",
+ "type": "boolean"
+ },
+ "network": {
+ "$ref": "#/$defs/Network"
+ },
+ "notifications": {
+ "$ref": "#/$defs/Notifications"
+ },
+ "show_stats": {
+ "default": true,
+ "title": "Show Stats",
+ "type": "boolean"
+ },
+ "sort": {
+ "$ref": "#/$defs/Sort"
+ },
+ "subfolders": {
+ "$ref": "#/$defs/SubFolders"
+ },
+ "ui": {
+ "$ref": "#/$defs/UIOptions"
+ }
+ },
+ "title": "cyberdrop-dl config",
+ "type": "object"
+}
diff --git a/cyberdrop_dl/config/settings.py b/cyberdrop_dl/config/settings.py
index 7047e2916..9dcb8e17a 100644
--- a/cyberdrop_dl/config/settings.py
+++ b/cyberdrop_dl/config/settings.py
@@ -1,29 +1,13 @@
-# ruff: noqa: RUF012
-import dataclasses
import datetime
-import functools
import logging
import random
-import re
-from collections.abc import Callable
from enum import auto
from pathlib import Path
-from typing import Annotated, Any, ClassVar, Literal, Self, override
+from typing import Annotated, ClassVar, Literal, override
-import aiohttp
from cyclopts import Parameter
-from pydantic import (
- AfterValidator,
- BaseModel,
- BeforeValidator,
- ByteSize,
- Field,
- NonNegativeFloat,
- PositiveFloat,
- PositiveInt,
- PrivateAttr,
- field_validator,
-)
+from pydantic import BaseModel, Field, PrivateAttr
+from pydantic.types import ByteSize, NonNegativeFloat, PositiveFloat, PositiveInt
from cyberdrop_dl.constants import (
DEFAULT_APP_STORAGE,
@@ -33,33 +17,24 @@ from cyberdrop_dl.constants import (
CIStrEnum,
HashMode,
)
-from cyberdrop_dl.models import AliasModel, ConfigGroup
+from cyberdrop_dl.models import ConfigGroup, DeferedModel
from cyberdrop_dl.models.types import (
ByteSizeSerilized,
+ CSVPath,
+ FalsyAsNone,
+ FalsyAsTuple,
+ FormatStr,
HttpURL,
- ListNonEmptyStr,
- ListPydanticURL,
+ LogLevel,
LogPath,
- MainLogPath,
NonEmptyStr,
- NonEmptyStrOrNone,
- PathOrNone,
+ RemoveDuplicates,
+ Timedelta,
)
-from cyberdrop_dl.models.validators import falsy_as, falsy_as_none, to_timedelta
-from cyberdrop_dl.utils.strings import validate_format_string
-
-
-def _format_validator(valid_keys: set[str]) -> Callable[[str | None], str | None]:
-
- def check(value: str | None) -> str | None:
- if value is not None:
- validate_format_string(value, valid_keys)
- return value
+from cyberdrop_dl.models.validators import strings
- return check
-
-class SubFoldersInclude(AliasModel):
+class _SubFoldersInclude(DeferedModel):
album_id: bool = False
thread_id: bool = False
domain: bool = True
@@ -67,18 +42,18 @@ class SubFoldersInclude(AliasModel):
class SubFolders(ConfigGroup, name=None):
create: Annotated[bool, Parameter(name="--subfolders")] = True
- include: SubFoldersInclude = Field(default_factory=SubFoldersInclude)
+ include: _SubFoldersInclude = Field(default_factory=_SubFoldersInclude)
separate_posts_format: Annotated[
- NonEmptyStr, AfterValidator(_format_validator({"default", "title", "id", "number", "date"}))
+ FormatStr, strings.format_validator({"default", "title", "id", "number", "date"})
] = "{default}"
separate_posts: bool = False
-class LogFiles(AliasModel):
- main: Annotated[MainLogPath, Parameter(alias="--log-file")] = Path("downloader.log")
- download_errors: LogPath = Path("Download_Error_URLs.csv")
- scrape_errors: LogPath = Path("Scrape_Error_URLs.csv")
- unsupported: LogPath = Path("Unsupported_URLs.csv")
+class LogFiles(DeferedModel):
+ main: Annotated[LogPath, Parameter(alias="--log-file")] = Path("downloader.log")
+ download_errors: CSVPath = Path("Download_Error_URLs.csv")
+ scrape_errors: CSVPath = Path("Scrape_Error_URLs.csv")
+ unsupported: CSVPath = Path("Unsupported_URLs.csv")
@property
def jsonl_file(self) -> Path:
@@ -86,25 +61,17 @@ class LogFiles(AliasModel):
class Logs(ConfigGroup, name=None): # noqa: PLW1641
- level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "DEBUG"
+ level: LogLevel = "DEBUG"
"Only log messages of this level or higher to the main log file"
- console_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] | None = None
+ console_level: FalsyAsNone[LogLevel] = None
"Only log messages of this level or higher to the console. An empty or `None` value will use the same level as `log_level`"
files: LogFiles = Field(default_factory=LogFiles)
folder: Path = DEFAULT_APP_STORAGE / "Logs"
- expire_after: datetime.timedelta | None = None
+ expire_after: FalsyAsNone[Timedelta] = None
rotate: bool = False
_created_at: datetime.datetime = PrivateAttr(default_factory=datetime.datetime.now)
- @field_validator("level", "console_level", mode="before")
- @classmethod
- def _normalize_log_level(cls, value: object) -> Any:
- value = falsy_as_none(value)
- if type(value) is str:
- return value.upper()
- return value
-
@property
def effective_level(self) -> int:
return logging.getLevelNamesMapping()[self.level]
@@ -116,12 +83,6 @@ class Logs(ConfigGroup, name=None): # noqa: PLW1641
return logging.getLevelNamesMapping()[self.console_level]
- @field_validator("expire_after", mode="before")
- @staticmethod
- def _parse_logs_duration(input_date: datetime.timedelta | str | int | None) -> datetime.timedelta | str | None:
- if value := falsy_as(input_date, None):
- return to_timedelta(value)
-
def resolve_filenames(self) -> None:
self.folder = self.folder.expanduser().resolve().absolute()
now_file_iso: str = self._created_at.strftime(LOGS_DATETIME_FORMAT)
@@ -163,141 +124,14 @@ class Logs(ConfigGroup, name=None): # noqa: PLW1641
return self.__dict__ == other.__dict__
[email protected](slots=True)
-class Range:
- min: float
- max: float
-
- def __post_init__(self) -> None:
- if not self.max:
- self.max = float("inf")
-
- def __contains__(self, value: float, /) -> bool:
- return self.min <= value <= self.max
-
- @classmethod
- def parse(cls, min: float, max: float) -> Self | None: # noqa: A002
- if not min and not max:
- return None
- return cls(min, max)
-
-
[email protected](slots=True, frozen=True)
-class FileSizeRanges:
- video: Range
- image: Range
- non_media: Range
-
-
-class SizeLimits(ConfigGroup):
- max_image_size: ByteSizeSerilized = ByteSize(0)
- max_non_media_size: ByteSizeSerilized = ByteSize(0)
- max_video_size: ByteSizeSerilized = ByteSize(0)
- min_image_size: ByteSizeSerilized = ByteSize(0)
- min_non_media_size: ByteSizeSerilized = ByteSize(0)
- min_video_size: ByteSizeSerilized = ByteSize(0)
-
- @functools.cached_property
- def ranges(self) -> FileSizeRanges:
- return FileSizeRanges(
- video=Range(
- self.min_video_size,
- self.max_video_size,
- ),
- image=Range(
- self.min_image_size,
- self.max_image_size,
- ),
- non_media=Range(
- self.min_non_media_size,
- self.max_non_media_size,
- ),
- )
-
-
[email protected](slots=True, frozen=True)
-class MediaDurationRanges:
- video: Range | None
- audio: Range | None
-
-
-class MediaDurationLimits(ConfigGroup):
- max_video_duration: datetime.timedelta = datetime.timedelta(seconds=0)
- max_audio_duration: datetime.timedelta = datetime.timedelta(seconds=0)
- min_video_duration: datetime.timedelta = datetime.timedelta(seconds=0)
- min_audio_duration: datetime.timedelta = datetime.timedelta(seconds=0)
-
- @field_validator("*", mode="before")
- @staticmethod
- def parse_runtime_duration(input_date: datetime.timedelta | str | int | None) -> datetime.timedelta | str:
- """Parses `datetime.timedelta`, `str` or `int` into a timedelta format.
- for `str`, the expected format is `value unit`, ex: `5 days`, `10 minutes`, `1 year`
- valid units:
- year(s), week(s), day(s), hour(s), minute(s), second(s), millisecond(s), microsecond(s)
- for `int`, value is assumed as `days`
- """
- if input_date is None:
- return datetime.timedelta(seconds=0)
- return to_timedelta(input_date)
-
- @property
- def needs_ffmpeg(self) -> bool:
- return bool(
- self.min_video_duration or self.max_video_duration or self.min_audio_duration or self.max_audio_duration
- )
-
- @functools.cached_property
- def ranges(self) -> MediaDurationRanges:
- return MediaDurationRanges(
- video=Range.parse(
- self.min_video_duration.total_seconds(),
- self.max_video_duration.total_seconds(),
- ),
- audio=Range.parse(
- self.min_audio_duration.total_seconds(),
- self.max_audio_duration.total_seconds(),
- ),
- )
-
-
-@Parameter(name="*")
-class FileFilter(AliasModel):
- audio: bool = True
- images: bool = True
- videos: bool = True
- non_media: bool = True
-
-
-class Filters(ConfigGroup):
- files: FileFilter = Field(default_factory=FileFilter)
- sizes: SizeLimits = Field(default_factory=SizeLimits)
- before: datetime.date | None = None
- after: datetime.date | None = None
- filename_regex: NonEmptyStrOrNone = None
- only_hosts: ListNonEmptyStr = []
- skip_hosts: ListNonEmptyStr = []
- allow_files_with_no_extension: bool = False
-
- @field_validator("filename_regex")
- @classmethod
- def _is_valid_regex(cls, value: str | None) -> str | None:
- if not value:
- return None
- try:
- _ = re.compile(value)
- except re.error as e:
- raise ValueError("input is not a valid regex") from e
- return value
-
-
class Jdownloader(ConfigGroup, name=None):
enabled: Annotated[bool, Parameter(name="--jdownloader")] = False
autostart: bool = False
- download_dir: PathOrNone = None
- whitelist: ListNonEmptyStr = []
+ download_dir: FalsyAsNone[Path] = None
+ whitelist: RemoveDuplicates[FalsyAsTuple[NonEmptyStr]] = ()
-class SortFormats(AliasModel):
+class SortFormats(DeferedModel):
_COMMON_FIELDS: ClassVar[set[str]] = {
"base_dir",
"ext",
@@ -310,46 +144,45 @@ class SortFormats(AliasModel):
}
audio: Annotated[
- NonEmptyStrOrNone,
- AfterValidator(_format_validator(_COMMON_FIELDS | {"bitrate", "duration", "length", "sample_rate"})),
+ FalsyAsNone[FormatStr],
+ strings.format_validator(_COMMON_FIELDS | {"bitrate", "duration", "length", "sample_rate"}),
] = "{sort_dir}/{base_dir}/Audio/{filename}{ext}"
"Format to generate sorted audio file"
image: Annotated[
- NonEmptyStrOrNone, AfterValidator(_format_validator(_COMMON_FIELDS | {"height", "resolution", "width"}))
+ FalsyAsNone[FormatStr], strings.format_validator(_COMMON_FIELDS | {"height", "resolution", "width"})
] = "{sort_dir}/{base_dir}/Images/{filename}{ext}"
"Format to generate sorted image file"
- non_media: Annotated[NonEmptyStrOrNone, AfterValidator(_format_validator(_COMMON_FIELDS))] = (
+ non_media: Annotated[FalsyAsNone[FormatStr], strings.format_validator(_COMMON_FIELDS)] = (
"{sort_dir}/{base_dir}/Other/{filename}{ext}"
)
"Format to generate sorted files of unknown type"
video: Annotated[
- NonEmptyStrOrNone,
- AfterValidator(
- _format_validator(
- _COMMON_FIELDS
- | {
- "codec",
- "duration",
- "fps",
- "height",
- "length",
- "resolution",
- "width",
- }
- )
+ FalsyAsNone[FormatStr],
+ strings.format_validator(
+ _COMMON_FIELDS
+ | {
+ "codec",
+ "duration",
+ "fps",
+ "height",
+ "length",
+ "resolution",
+ "width",
+ }
),
] = "{sort_dir}/{base_dir}/Videos/{filename}{ext}"
"Format to generate sorted video file"
- incrementer: Annotated[NonEmptyStr, AfterValidator(_format_validator({"i"}))] = " ({i})"
+
+ incrementer: Annotated[FormatStr, strings.format_validator({"i"})] = " ({i})"
"Format for separator on name collisions"
class Sort(ConfigGroup, name=None):
enabled: Annotated[bool, Parameter(name="--sort")] = False
- input_folder: PathOrNone = None
+ input_folder: FalsyAsNone[Path] = None
output_folder: Path = DEFAULT_DOWNLOAD_STORAGE / "Cyberdrop-DL Sorted Downloads"
formats: SortFormats = Field(default_factory=SortFormats)
@@ -358,14 +191,23 @@ class Sort(ConfigGroup, name=None):
return bool(self.enabled and (self.formats.audio or self.formats.video))
-class Dedupe(AliasModel):
+class Dedupe(DeferedModel):
enabled: Annotated[bool, Parameter(name="--hashing.dedupe", alias="--auto-dedupe")] = True
use_trash_bin: bool = True
class Hashing(ConfigGroup, name=None):
mode: Annotated[HashMode, Parameter(name="--hashing")] = HashMode.IN_PLACE
- algorithms: Annotated[tuple[Literal["xxh128", "md5", "sha256"], ...], Parameter(alias="--hashes")] = (
+ algorithms: Annotated[
+ tuple[
+ Annotated[
+ Literal["xxh128", "md5", "sha256"],
+ strings.pre_validator(to_lower=True, strip=True),
+ ],
+ ...,
+ ],
+ Parameter(alias="--hashes"),
+ ] = (
"xxh128",
"md5",
"sha256",
@@ -409,35 +251,25 @@ class Downloads(ConfigGroup):
class Network(ConfigGroup):
dump_responses: bool = False
"""Save text/HTML/JSON responses to disk (flaresolverr responses are excluded)"""
- flaresolverr: HttpURL | None = None
- proxy: HttpURL | None = None
+ flaresolverr: FalsyAsNone[HttpURL] = None
+ proxy: FalsyAsNone[HttpURL] = None
rate_limit: PositiveFloat = 25
connection_timeout: PositiveFloat = 15
- read_timeout: Annotated[PositiveFloat | None, BeforeValidator(falsy_as_none)] = 300
- ssl_context: Literal["truststore", "certifi", "truststore+certifi"] | None = "truststore+certifi"
+ read_timeout: FalsyAsNone[PositiveFloat] = 300
+ ssl_context: FalsyAsNone[
+ Annotated[
+ Literal["truststore", "certifi", "truststore+certifi"],
+ strings.pre_validator(to_lower=True, strip=True),
+ ]
+ ] = "truststore+certifi"
user_agent: NonEmptyStr = "Mozilla/5.0 (X11; Linux x86_64; rv:150.0) Gecko/20100101 Firefox/150.0"
- @field_validator("ssl_context", mode="before")
- @classmethod
- def _ssl(cls, value: str | None) -> str | None:
- if isinstance(value, str):
- value = value.lower().strip()
- return falsy_as(value, None)
-
@property
def curl_timeout(self) -> float | tuple[float, float]:
if self.read_timeout is None:
return self.connection_timeout
return self.connection_timeout, self.read_timeout
- @property
- def aiohttp_timeout(self) -> aiohttp.ClientTimeout:
- return aiohttp.ClientTimeout(
- total=None,
- sock_connect=self.connection_timeout,
- sock_read=self.read_timeout,
- )
-
class UIMode(CIStrEnum):
DISABLED = auto()
@@ -459,10 +291,3 @@ class UIOptions(ConfigGroup):
portrait: bool = False
"force CDL to run with a vertical layout"
refresh_rate: PositiveFloat = 10.0
-
-
-class GenericCrawlers(ConfigGroup):
- wordpress_media: ListPydanticURL = []
- wordpress_html: ListPydanticURL = []
- discourse: ListPydanticURL = []
- chevereto: ListPydanticURL = []
diff --git a/cyberdrop_dl/crawlers/_chibisafe.py b/cyberdrop_dl/crawlers/_chibisafe.py
index ac41b90b5..355e3cbb1 100644
--- a/cyberdrop_dl/crawlers/_chibisafe.py
+++ b/cyberdrop_dl/crawlers/_chibisafe.py
@@ -16,7 +16,7 @@ from typing import TYPE_CHECKING, Any, ClassVar
from pydantic import Field
from cyberdrop_dl.crawlers.crawler import Crawler
-from cyberdrop_dl.models import AliasModel
+from cyberdrop_dl.models import DeferedModel
from cyberdrop_dl.utils import DictDataclass, error_handling_wrapper
from cyberdrop_dl.utils.dates import to_timestamp
@@ -33,7 +33,7 @@ class File(DictDataclass):
original: str | None = None
-class Album(AliasModel):
+class Album(DeferedModel):
id: str = ""
name: str = Field(validation_alias="title")
files: list[File]
diff --git a/cyberdrop_dl/crawlers/box_dot_com.py b/cyberdrop_dl/crawlers/box_dot_com.py
index e5f47ae0c..4addc1d08 100644
--- a/cyberdrop_dl/crawlers/box_dot_com.py
+++ b/cyberdrop_dl/crawlers/box_dot_com.py
@@ -10,7 +10,7 @@ from pydantic import Field
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedDomains, SupportedPaths
from cyberdrop_dl.exceptions import ScrapeError
-from cyberdrop_dl.models import AliasModel
+from cyberdrop_dl.models import DeferedModel
from cyberdrop_dl.url_objects import AbsoluteHttpURL
from cyberdrop_dl.utils import css, error_handling_wrapper
@@ -23,7 +23,7 @@ class ItemType(StrEnum):
file = "file"
-class Item(AliasModel):
+class Item(DeferedModel):
name: str
type: str
id: str = Field(validation_alias="itemID", coerce_numbers_to_str=True)
@@ -32,7 +32,7 @@ class Item(AliasModel):
parent_id: str = Field(validation_alias="parentFolderID", coerce_numbers_to_str=True)
-class SharedFolder(AliasModel):
+class SharedFolder(DeferedModel):
name: str = Field(validation_alias="currentFolderName")
id: str = Field(validation_alias="currentFolderID", coerce_numbers_to_str=True)
items: list[Item]
diff --git a/cyberdrop_dl/crawlers/crawler.py b/cyberdrop_dl/crawlers/crawler.py
index 17a18b673..8146efd03 100644
--- a/cyberdrop_dl/crawlers/crawler.py
+++ b/cyberdrop_dl/crawlers/crawler.py
@@ -24,6 +24,7 @@ from cyberdrop_dl.downloader.http import Downloader
from cyberdrop_dl.exceptions import MaxChildrenError, NoExtensionError, ScrapeError
from cyberdrop_dl.filepath import check_dangerous_filename, check_path_traversal, compose_filename, get_filename_and_ext
from cyberdrop_dl.mediaprops import ISO639Subtitle, Resolution
+from cyberdrop_dl.models.validators import strings
from cyberdrop_dl.url_objects import AbsoluteHttpURL, MediaItem, ScrapeItem, is_absolute_http_url
from cyberdrop_dl.utils import (
css,
@@ -35,7 +36,6 @@ from cyberdrop_dl.utils import (
parse_url,
unique,
)
-from cyberdrop_dl.utils.strings import safe_format
if TYPE_CHECKING:
import datetime
@@ -713,7 +713,7 @@ class Crawler(HTTPMixin, HLSMixin, ABC):
if isinstance(date, int):
date = dates.from_timestamp(date)
- post_title, _ = safe_format(title_format, id=id, number=id, date=date, title=title)
+ post_title, _ = strings.safe_format(title_format, id=id, number=id, date=date, title=title)
return post_title
@classmethod
@@ -1053,7 +1053,7 @@ def _should_skip_by_config(media_item: MediaItem, config: Config) -> bool:
logger.info(f"Download skipped {media_item.url} due to only_hosts config")
return True
- if (regex := filters.filename_regex) and not re.search(regex, media_item.filename):
+ if (regex := filters.filename_regex) and not regex.search(media_item.filename):
logger.info(
"Download skipped %s due to filename regex filter. Filename '%s' does not match config regex",
media_item.url,
diff --git a/cyberdrop_dl/crawlers/kemono.py b/cyberdrop_dl/crawlers/kemono.py
index 520bd8707..1438fef88 100644
--- a/cyberdrop_dl/crawlers/kemono.py
+++ b/cyberdrop_dl/crawlers/kemono.py
@@ -14,7 +14,7 @@ from pydantic import BeforeValidator, Field
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths, auto_task_id
from cyberdrop_dl.exceptions import NoExtensionError, ScrapeError
-from cyberdrop_dl.models import AliasModel
+from cyberdrop_dl.models import DeferedModel
from cyberdrop_dl.models.validators import falsy_as, falsy_as_none
from cyberdrop_dl.url_objects import AbsoluteHttpURL
from cyberdrop_dl.utils import css, error_handling_wrapper
@@ -83,7 +83,7 @@ FileOrNone = Annotated[File | None, BeforeValidator(falsy_as_none)]
Tags = Annotated[list[str], BeforeValidator(lambda x: falsy_as(x, []))]
-class Post(AliasModel):
+class Post(DeferedModel):
id: str
content: str = ""
file: FileOrNone = None
diff --git a/cyberdrop_dl/crawlers/mega_nz.py b/cyberdrop_dl/crawlers/mega_nz.py
index c2e7323d2..38e999a5d 100644
--- a/cyberdrop_dl/crawlers/mega_nz.py
+++ b/cyberdrop_dl/crawlers/mega_nz.py
@@ -58,11 +58,11 @@ class MegaNzCrawler(Crawler, db_path="path_qs_frag"):
@property
def user(self) -> str | None:
- return self.config.auth.meganz.email or None
+ return self.config.auth.mega_nz.email
@property
def password(self) -> str | None:
- return self.config.auth.meganz.password or None
+ return self.config.auth.mega_nz.password
def __post_init__(self) -> None:
self._decryption_keys: dict[AbsoluteHttpURL, tuple[Crypto, int]] = {}
diff --git a/cyberdrop_dl/manager.py b/cyberdrop_dl/manager.py
index 8732f4bfb..1bdca9e4b 100644
--- a/cyberdrop_dl/manager.py
+++ b/cyberdrop_dl/manager.py
@@ -291,9 +291,8 @@ def _log_cli_args(cli_args: CLIargs) -> None:
def _log_config(config: Config) -> None:
- auth = {site: all(credentials.values()) for site, credentials in config.auth.model_dump().items()}
logger.debug("Config file: %s", config.source)
- logger.debug("Auth: \n%s", auth)
+ logger.debug("Auth: \n%s", config.auth.censored_dump())
logger.debug(config.model_dump_json(exclude={"auth"}, indent=2))
diff --git a/cyberdrop_dl/models/__init__.py b/cyberdrop_dl/models/__init__.py
index 78da89a4d..94fae0131 100644
--- a/cyberdrop_dl/models/__init__.py
+++ b/cyberdrop_dl/models/__init__.py
@@ -5,11 +5,23 @@ from typing import Any, ClassVar, TypedDict
from cyclopts import Parameter
from pydantic import AnyUrl, BaseModel, Secret, SerializationInfo, model_serializer, model_validator
+from cyberdrop_dl import env
-class AliasModel(BaseModel, populate_by_name=True, defer_build=True): ...
+class DeferedModel(
+ BaseModel,
+ populate_by_name=True,
+ defer_build=True,
+ allow_inf_nan=False,
+ extra="forbid",
+ url_preserve_empty_path=True,
+ val_temporal_unit="milliseconds",
+ validate_default=env.DEBUG_MODE,
+ validation_error_cause=env.DEBUG_MODE,
+): ...
-class ConfigGroup(AliasModel):
+
+class ConfigGroup(DeferedModel):
def __init_subclass__(cls, *, group: str | None = None, name: str | None = "*") -> None:
_ = Parameter(group=group or cls.__name__, name=name)(cls)
return super().__init_subclass__()
@@ -21,7 +33,7 @@ class _AppriseURLDict(TypedDict):
@Parameter(name="*")
-class AppriseURL(AliasModel):
+class AppriseURL(DeferedModel):
url: Secret[AnyUrl]
tags: set[str] = set()
diff --git a/cyberdrop_dl/models/types.py b/cyberdrop_dl/models/types.py
index e06a1c2d6..83ea9918b 100644
--- a/cyberdrop_dl/models/types.py
+++ b/cyberdrop_dl/models/types.py
@@ -1,45 +1,68 @@
-from __future__ import annotations
-
+import datetime
from pathlib import Path
-from typing import Annotated
+from typing import Annotated, ClassVar, Literal
from pydantic import (
AfterValidator,
+ AnyUrl,
BeforeValidator,
ByteSize,
- HttpUrl,
- NonNegativeInt,
+ Field,
PlainSerializer,
PlainValidator,
StringConstraints,
+ UrlConstraints,
+ WithJsonSchema,
)
-from cyberdrop_dl.models.validators import (
+from cyberdrop_dl.url_objects import AbsoluteHttpURL
+
+from .validators import (
bytesize_to_str,
change_path_suffix,
- falsy_as_list,
falsy_as_none,
+ falsy_as_tuple,
+ remove_duplicates,
+ strings,
+ to_timedelta,
to_yarl_url,
)
-from cyberdrop_dl.url_objects import AbsoluteHttpURL
-# ~~~~~ Strings ~~~~~~~
-NonEmptyStr = Annotated[str, StringConstraints(min_length=1, strip_whitespace=True)]
-NonEmptyStrOrNone = Annotated[NonEmptyStr | None, BeforeValidator(falsy_as_none)]
-ListNonEmptyStr = Annotated[list[NonEmptyStr], BeforeValidator(falsy_as_list)]
+type LogLevel = Annotated[
+ Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], strings.pre_validator(to_upper=True, strip=True)
+]
+type NonEmptyStr = Annotated[str, StringConstraints(min_length=1, strip_whitespace=True)]
+type FormatStr = Annotated[str, StringConstraints(min_length=1)]
+type CSVPath = Annotated[Path, AfterValidator(change_path_suffix(".csv"))]
+type LogPath = Annotated[Path, AfterValidator(change_path_suffix(".log"))]
+type ByteSizeSerilized = Annotated[ByteSize, PlainSerializer(bytesize_to_str, return_type=str, when_used="json")]
+type FalsyAsTuple[T] = Annotated[tuple[T, ...], BeforeValidator(falsy_as_tuple)]
+type FalsyAsNone[T] = Annotated[T | None, BeforeValidator(falsy_as_none)]
+type Timedelta = Annotated[
+ datetime.timedelta,
+ BeforeValidator(to_timedelta),
+ Field(ge=datetime.timedelta(seconds=0)),
+ PlainSerializer(
+ str, return_type=str, when_used="json"
+ ), # Serialize as str to save it as sexageximal (hh:mm:ss) instead of pydantic's ISO duration (PT1H5M26S)
+]
+type RemoveDuplicates[T: tuple[str, ...]] = Annotated[T, AfterValidator(remove_duplicates)]
-# ~~~~~ Paths ~~~~~~~
-PathOrNone = Annotated[Path | None, BeforeValidator(falsy_as_none)]
-LogPath = Annotated[Path, AfterValidator(change_path_suffix(".csv"))]
-MainLogPath = Annotated[LogPath, AfterValidator(change_path_suffix(".log"))]
+class _HttpURL(AnyUrl):
+ _constraints: ClassVar[UrlConstraints] = UrlConstraints(
+ max_length=2083,
+ allowed_schemes=["http", "https"],
+ host_required=True,
+ )
-# URL with pydantic.HttpUrl validation (must be absolute, must be http/https, detailed validation error).
-# In type hints it's a yarl.URL. After validation the result is parsed with `parse_url` so this is also a yarl.URL at runtime
-# Only use for config validation. To parse URLs internally while scraping, call `parse_url` directly
-HttpURL = Annotated[AbsoluteHttpURL, PlainValidator(lambda x: to_yarl_url(HttpUrl(str(x))))]
-# ~~~~~ Others ~~~~~~~
-ByteSizeSerilized = Annotated[ByteSize, PlainSerializer(bytesize_to_str, return_type=str)]
-ListNonNegativeInt = Annotated[list[NonNegativeInt], BeforeValidator(falsy_as_list)]
-ListPydanticURL = Annotated[list[HttpURL], BeforeValidator(falsy_as_list)]
+# Only use this for config validation. To parse URLs internally while scraping, call `parse_url` directly
+type HttpURL = Annotated[
+ AbsoluteHttpURL,
+ PlainValidator(
+ lambda x: to_yarl_url(_HttpURL(str(x))),
+ json_schema_input_type=str,
+ ),
+ WithJsonSchema({"type": "string", "format": "uri"}),
+]
diff --git a/cyberdrop_dl/models/validators.py b/cyberdrop_dl/models/validators/__init__.py
similarity index 88%
rename from cyberdrop_dl/models/validators.py
rename to cyberdrop_dl/models/validators/__init__.py
index e75ededb1..2b1e932bf 100644
--- a/cyberdrop_dl/models/validators.py
+++ b/cyberdrop_dl/models/validators/__init__.py
@@ -7,7 +7,7 @@ from typing import TYPE_CHECKING, Literal, SupportsIndex, SupportsInt
from pydantic import ByteSize, TypeAdapter
if TYPE_CHECKING:
- from collections.abc import Callable
+ from collections.abc import Callable, Iterable
from pathlib import Path
import yarl
@@ -75,7 +75,7 @@ def _str_to_timedelta(input_date: str) -> datetime.timedelta:
return datetime.timedelta(**time_dict)
-def to_timedelta(input_date: datetime.timedelta | str | int) -> datetime.timedelta | str:
+def to_timedelta(input_date: datetime.timedelta | str | int | None) -> datetime.timedelta | str:
"""Parses `datetime.timedelta`, `str` or `int` into a timedelta format.
For `str`, the expected format is `<value> <unit>`, ex: `5 days`, `10 minutes`, `1 year`
@@ -103,9 +103,15 @@ def falsy_as[T, T2](value: T | Literal[""] | None, default: T2) -> T | T2:
return value or default
-def falsy_as_list[T](value: list[T] | Literal[""] | None) -> list[T]:
- return falsy_as(value, [])
+def falsy_as_tuple[T](
+ value: Iterable[T] | Literal[""] | tuple[T, ...] | tuple[()] | None,
+) -> tuple[T, ...] | Iterable[T]:
+ return falsy_as(value, ())
def falsy_as_none[T](value: T | Literal[""] | None) -> T | None:
return falsy_as(value, None)
+
+
+def remove_duplicates[T: str](value: tuple[T, ...]) -> tuple[T, ...]:
+ return tuple(sorted(set(value)))
diff --git a/cyberdrop_dl/utils/strings.py b/cyberdrop_dl/models/validators/strings.py
similarity index 66%
rename from cyberdrop_dl/utils/strings.py
rename to cyberdrop_dl/models/validators/strings.py
index b3894414f..7621f1555 100644
--- a/cyberdrop_dl/utils/strings.py
+++ b/cyberdrop_dl/models/validators/strings.py
@@ -1,6 +1,9 @@
import string
+from collections.abc import Generator
from typing import Any
+from pydantic import AfterValidator, BeforeValidator
+
_FORMATER = string.Formatter()
@@ -10,7 +13,7 @@ class UnknownPlaceholder:
Use this to prevent errors if the user supplied custom formatting for a value that the crawler was not able to scrape"""
def __init__(self, value: str) -> None:
- self.value = value
+ self.value: str = value
def __str__(self) -> str:
return self.value
@@ -43,7 +46,7 @@ def safe_format(format_string: str, **fields: Any) -> tuple[str, set[str]]:
"""
new_kwargs = dict(fields)
- unknown_field_names = get_unknown_field_names(format_string, set(new_kwargs.keys()))
+ unknown_field_names = _get_unknown_field_names(format_string, set(new_kwargs.keys()))
for field_name, value in new_kwargs.items():
if value is None:
@@ -58,8 +61,7 @@ def safe_format(format_string: str, **fields: Any) -> tuple[str, set[str]]:
return _FORMATER.vformat(format_string, (), new_kwargs), unknown_field_names
-# To use with pydantic
-def validate_format_string(format_string: str, valid_keys: set[str]) -> None:
+def validate_format(format_string: str, valid_keys: set[str]) -> None:
msg = "invalid format string. "
for _, field_name, _, _ in _FORMATER.parse(format_string):
if field_name is not None:
@@ -70,7 +72,7 @@ def validate_format_string(format_string: str, valid_keys: set[str]) -> None:
msg += "Operations within a format string are not supported"
raise ValueError(msg)
- if unknown_field_names := get_unknown_field_names(format_string, valid_keys):
+ if unknown_field_names := _get_unknown_field_names(format_string, valid_keys):
msg += " ".join(
(
f"{tuple(sorted(unknown_field_names))}",
@@ -81,16 +83,36 @@ def validate_format_string(format_string: str, valid_keys: set[str]) -> None:
raise ValueError(msg)
-def get_field_names(format_string: str) -> set[str]:
- field_names = set()
-
- # literal_text, field_name, format_spec, conversion
- for _, field_name, _, _ in _FORMATER.parse(format_string):
+def _get_field_names(format_string: str) -> Generator[str]:
+ for _literal_text, field_name, _fmt_spec, _conversion in _FORMATER.parse(format_string):
if field_name and not field_name.isdigit(): # Ignore positional args and empty fields
- field_names.add(field_name)
- return field_names
+ yield field_name
-def get_unknown_field_names(format_string: str, valid_keys: set[str]) -> set[str]:
- field_names = get_field_names(format_string)
+def _get_unknown_field_names(format_string: str, valid_keys: set[str]) -> set[str]:
+ field_names = set(_get_field_names(format_string))
return field_names - valid_keys
+
+
+def pre_validator(*, to_upper: bool = False, to_lower: bool = False, strip: bool = False) -> BeforeValidator:
+ def coerce[T](value: T | str) -> T | str:
+ if not isinstance(value, str):
+ return value
+ if to_upper:
+ value = value.upper()
+ if to_lower:
+ value = value.lower()
+ if strip:
+ value = value.strip()
+ return value
+
+ return BeforeValidator(coerce)
+
+
+def format_validator(valid_keys: set[str]) -> AfterValidator:
+ def check[T](value: T) -> T:
+ if isinstance(value, str):
+ validate_format(value, valid_keys)
+ return value
+
+ return AfterValidator(check)
diff --git a/cyberdrop_dl/scrape_mapper.py b/cyberdrop_dl/scrape_mapper.py
index 65088ac16..5400a2509 100644
--- a/cyberdrop_dl/scrape_mapper.py
+++ b/cyberdrop_dl/scrape_mapper.py
@@ -31,7 +31,7 @@ if TYPE_CHECKING:
from collections.abc import AsyncGenerator, Coroutine, Generator, Iterable, Iterator, Sequence
from pathlib import Path
- from cyberdrop_dl.config.settings import GenericCrawlers
+ from cyberdrop_dl.config.crawlers import GenericCrawlers
from cyberdrop_dl.crawlers.crawler import Crawler
from cyberdrop_dl.manager import Manager
@@ -145,7 +145,7 @@ class ScrapeMapper:
self.crawlers.update(get_crawlers_mapping())
- for crawler in _create_generic_crawlers(self.manager.config.generic_crawlers):
+ for crawler in _create_generic_crawlers(self.manager.config.crawlers.generic):
register_crawler(self.crawlers, crawler, from_user=True)
_disable_crawlers_by_config(self.crawlers, *self.manager.config.crawlers.disabled)
diff --git a/cyberdrop_dl/sorter.py b/cyberdrop_dl/sorter.py
index 9b0e078fc..0b6633d35 100644
--- a/cyberdrop_dl/sorter.py
+++ b/cyberdrop_dl/sorter.py
@@ -14,8 +14,9 @@ import imagesize
from cyberdrop_dl import aio, ffmpeg
from cyberdrop_dl.constants import FileExt, TempExt
+from cyberdrop_dl.models.validators import strings
from cyberdrop_dl.progress.sorting import SortingUI, SortStats
-from cyberdrop_dl.utils import cleanup, strings
+from cyberdrop_dl.utils import cleanup
if TYPE_CHECKING:
from cyberdrop_dl.manager import Manager
diff --git a/tests/test_client.py b/tests/test_client.py
index 0f7c9266a..b5dc03c15 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -56,5 +56,4 @@ async def test_create_aiohttp_session(client: HTTPClient) -> None:
assert session.headers.get("User-agent")
assert session.cookie_jar is client.cookies
assert session._raise_for_status is False
- assert session.timeout == client.config.network.aiohttp_timeout
assert session.requote_redirect_url is False
diff --git a/tests/test_config.py b/tests/test_config.py
index f3d893027..3a5a5667a 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import json
+import os
import time
from pathlib import Path
@@ -8,9 +10,10 @@ from cyclopts.exceptions import UnknownOptionError
from pydantic import BaseModel
import cyberdrop_dl.cli.download
-from cyberdrop_dl.config import Config, _resolve_paths, merge_additive_args, settings
+from cyberdrop_dl.config import Config, Files, _resolve_paths, merge_additive_args, settings
+from cyberdrop_dl.config.auth import Authentication, Notifications
from cyberdrop_dl.exceptions import CDLConfigRuntimeErrorsGroup
-from cyberdrop_dl.models import merge_dicts
+from cyberdrop_dl.models import AppriseURL, merge_dicts
def test_config_equality() -> None:
@@ -153,11 +156,11 @@ def test_default_config_does_not_need_ffmpeg() -> None:
def test_media_durations_need_ffmpeg() -> None:
- config = Config.parse_args(["--max-video-duration", "20 seconds"])
- duration = config.media_duration_limits.max_video_duration
+ config = Config.parse_args(["--video.duration.max", "20 seconds"])
+ duration = config.filters.duration.video.max
assert duration
assert duration.total_seconds() == 20
- assert config.media_duration_limits.needs_ffmpeg
+ assert config.filters.duration.needs_ffmpeg
with pytest.raises(CDLConfigRuntimeErrorsGroup) as exc:
cyberdrop_dl.cli.download._check_ffmpeg(config)
@@ -254,3 +257,59 @@ def test_config_from_file(tmp_cwd: Path) -> None:
assert config_2.source == config_file
config_2._source = None
assert config_1 == config_2
+
+
[email protected](os.name == "nt", reason="pydantic can't generate schema w pathlib.WindowsPath defaults")
+def test_schema_has_not_changed() -> None:
+ schema = Config.model_json_schema()
+ expected_schema = json.loads(Files.SCHEMA.read_text())
+ assert schema == expected_schema, "Validation schema changed"
+
+
+def test_round_trip_parsed_the_same_config() -> None:
+ config = Config()
+ for mode in ("python", "json"):
+ new_config = Config.model_validate(config.model_dump(mode=mode))
+ assert vars(new_config) == vars(config)
+ assert new_config == config
+
+
[email protected](os.name == "nt", reason="OS separators make paths different on Windows")
+def test_config_default_has_not_changed() -> None:
+ config = Config().model_dump(mode="json")
+ expected = json.loads(Files.DEFAULT.read_text())
+ assert config == expected, "Config serialization changed"
+
+
+def test_config_can_be_serialized_as_json() -> None:
+ Config().model_dump_json()
+
+
+def test_config_defaults_are_valid() -> None:
+ class StrictConfig(Config, validate_default=True, validation_error_cause=True): ...
+
+ StrictConfig()
+
+
+class TestCensoredConfig:
+ def test_auth_is_censored_on_repr(self) -> None:
+ api_key = "my_api_key"
+ auth = Authentication.model_validate({"gofile": {"api_key": api_key}})
+ assert api_key not in repr(auth)
+ assert auth.gofile.api_key == api_key
+ assert auth.model_dump()["gofile"]["api_key"] == api_key
+ assert auth.censored_dump()["gofile"] is True
+ assert auth.model_dump(mode="json")["gofile"]["api_key"] == api_key
+
+ def test_apprise_urls_are_censored(self) -> None:
+ url = AppriseURL.model_validate({"url": "https://example.com/a"})
+ assert str(url) == "no_logs=https://example.com/a"
+ assert repr(url) == "AppriseURL(url=Secret('**********'), tags={'no_logs'})"
+ assert url.model_dump() == "no_logs=https://example.com/a"
+ assert url.model_dump(mode="json") == "no_logs=**********"
+
+ def test_notifications_are_censored(self) -> None:
+ url = AppriseURL.model_validate({"url": "https://example.com/a"})
+ noti = Notifications(apprise=(url,))
+ assert "example.com" not in repr(noti)
+ assert "example.com" not in str(noti)