Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: simplify yaml module (#36)
NTFSvolumed0476a869249
diff --git a/cyberdrop_dl/cli/__init__.py b/cyberdrop_dl/cli/__init__.pyindex d7d1af189..c0f1efd10 100644--- a/cyberdrop_dl/cli/__init__.py+++ b/cyberdrop_dl/cli/__init__.py@@ -6,7 +6,7 @@ from argparse import SUPPRESS, ArgumentParser, RawDescriptionHelpFormatterfrom shutil import get_terminal_sizefrom typing import TYPE_CHECKING, Any, Final, NoReturn-from pydantic import BaseModel, ValidationError+from pydantic import BaseModelfrom cyberdrop_dl import __version__, envfrom cyberdrop_dl.cli import arguments@@ -104,15 +104,10 @@ def make_parser() -> CLIParser:def parse_args(args: Sequence[str] | None = None) -> ParsedArgs:"""Parses the command line arguments passed into the program."""- from cyberdrop_dl.utils.yaml import handle_validation_errorparsed_args = make_parser().parse_args(args)- try:- model = ParsedArgs.model_validate(parsed_args, extra="forbid")- except ValidationError as e:- handle_validation_error(e, title="CLI arguments")- sys.exit(1)+ model = ParsedArgs.model_validate(parsed_args, extra="forbid")if model.cli_only_args.show_supported_sites:show_supported_sites()diff --git a/cyberdrop_dl/config/_common.py b/cyberdrop_dl/config/_common.pyindex 997bb9b7e..debbbe48c 100755--- a/cyberdrop_dl/config/_common.py+++ b/cyberdrop_dl/config/_common.py@@ -3,9 +3,9 @@ from typing import Selffrom pydantic import BaseModel+from cyberdrop_dl import yamlfrom cyberdrop_dl.exceptions import InvalidYamlErrorfrom cyberdrop_dl.models import AliasModel, get_model_fields-from cyberdrop_dl.utils import yamlclass ConfigModel(AliasModel):diff --git a/cyberdrop_dl/director.py b/cyberdrop_dl/director.pyindex dab7167ac..bbbdbbc53 100644--- a/cyberdrop_dl/director.py+++ b/cyberdrop_dl/director.py@@ -3,15 +3,12 @@ from __future__ import annotationsimport asyncioimport contextlibimport logging-import sysfrom datetime import datetimefrom enum import IntEnumfrom functools import wrapsfrom pathlib import Pathfrom typing import TYPE_CHECKING, ParamSpec, TypeVar-from pydantic import ValidationError-from cyberdrop_dl import aio, constants, env, storagefrom cyberdrop_dl.dependencies import browser_cookie3from cyberdrop_dl.managers.manager import Manager@@ -29,7 +26,6 @@ from cyberdrop_dl.utils.sorting import Sorterfrom cyberdrop_dl.utils.updates import check_latest_pypifrom cyberdrop_dl.utils.utilities import check_partials_and_empty_foldersfrom cyberdrop_dl.utils.webhook import send_webhook_message-from cyberdrop_dl.utils.yaml import handle_validation_errorif TYPE_CHECKING:from collections.abc import Callable, Coroutine, Sequence@@ -194,21 +190,11 @@ def _setup_manager(args: Sequence[str] | None = None) -> Manager:"""manager = Manager(args)- try:- manager.startup()-- if not manager.parsed_args.cli_only_args.download:- ProgramUI(manager)- except ValidationError as e:- file = {- "GlobalSettings": manager.config_manager.global_settings,- "ConfigSettings": manager.config_manager.settings,- "AuthSettings": manager.config_manager.authentication_settings,- }.get(e.title)+ manager.startup()- handle_validation_error(e, file=file)- sys.exit(_C.ERROR)+ if not manager.parsed_args.cli_only_args.download:+ ProgramUI(manager)return managerdiff --git a/cyberdrop_dl/exceptions.py b/cyberdrop_dl/exceptions.pyindex 06fb0fb22..9957edaa5 100644--- a/cyberdrop_dl/exceptions.py+++ b/cyberdrop_dl/exceptions.py@@ -5,12 +5,11 @@ from http import HTTPStatusfrom pathlib import Pathfrom typing import TYPE_CHECKING-from yaml import YAMLErrorfrom yarl import URL-from cyberdrop_dl.constants import VALIDATION_ERROR_FOOTER-if TYPE_CHECKING:+ from yaml import YAMLError+from cyberdrop_dl.data_structures.url_objects import MediaItem, ScrapeItem@@ -209,20 +208,17 @@ class JDownloaderError(CDLBaseError):class InvalidYamlError(CDLBaseError):- def __init__(self, file: Path, e: Exception) -> None:+ def __init__(self, file: Path, e: YAMLError) -> None:"""This error will be thrown when a yaml config file has invalid values."""- file_path = file.resolve()+ file = file.resolve()ui_failure = "Invalid YAML"- msg = f"Unable to read file '{file_path}'"- if isinstance(e, YAMLError):- msg = f"File '{file_path}' is not a valid YAML file"- mark = getattr(e, "problem_mark", None)- if mark:+ msg = f"File '{file}' is not a valid YAML file"++ if mark := getattr(e, "problem_mark", None):msg += f"\n\nThe error was found in this line: \n {mark}"- problem = getattr(e, "problem", str(e))- msg += f"\n\n{problem.capitalize()}"- msg += f"\n\n{VALIDATION_ERROR_FOOTER}"+ problem = getattr(e, "problem", str(e)).capitalize()+ msg += f"\n\n{problem}\n\nPlease delete the file or fix the errors"super().__init__(ui_failure, message=msg, origin=file)diff --git a/cyberdrop_dl/managers/cache_manager.py b/cyberdrop_dl/managers/cache_manager.pyindex 104fcab37..9c1a3ff54 100644--- a/cyberdrop_dl/managers/cache_manager.py+++ b/cyberdrop_dl/managers/cache_manager.py@@ -4,7 +4,7 @@ from dataclasses import fieldfrom typing import TYPE_CHECKING, Anyfrom cyberdrop_dl import __version__ as current_version-from cyberdrop_dl.utils import yaml+from cyberdrop_dl import yamlif TYPE_CHECKING:from pathlib import Pathdiff --git a/cyberdrop_dl/managers/config_manager.py b/cyberdrop_dl/managers/config_manager.pyindex 23981a74a..e67b3c020 100644--- a/cyberdrop_dl/managers/config_manager.py+++ b/cyberdrop_dl/managers/config_manager.py@@ -6,10 +6,10 @@ from dataclasses import fieldfrom time import sleepfrom typing import TYPE_CHECKING+from cyberdrop_dl import yamlfrom cyberdrop_dl.config import AuthSettings, ConfigSettings, GlobalSettingsfrom cyberdrop_dl.exceptions import InvalidYamlErrorfrom cyberdrop_dl.managers.log_manager import LogManager-from cyberdrop_dl.utils import yamlfrom cyberdrop_dl.utils.apprise import get_apprise_urlsif TYPE_CHECKING:diff --git a/cyberdrop_dl/utils/apprise.py b/cyberdrop_dl/utils/apprise.pyindex 654d3c0ee..3418c505e 100644--- a/cyberdrop_dl/utils/apprise.py+++ b/cyberdrop_dl/utils/apprise.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport asyncioimport jsonimport shutil-import sysimport tempfilefrom dataclasses import dataclassfrom enum import IntEnum@@ -12,14 +11,12 @@ from pathlib import Pathfrom typing import TYPE_CHECKING, Anyimport rich-from pydantic import ValidationErrorfrom rich.text import Textfrom cyberdrop_dl import constantsfrom cyberdrop_dl.dependencies import apprisefrom cyberdrop_dl.models import AppriseURLModelfrom cyberdrop_dl.utils.logger import log, log_debug, log_spacer-from cyberdrop_dl.utils.yaml import handle_validation_errorif TYPE_CHECKING:from cyberdrop_dl.managers.manager import Manager@@ -85,12 +82,8 @@ def get_apprise_urls(*, file: Path | None = None, urls: list[str] | None = None)if apprise is None:log("Found apprise URLs for notifications but apprise is not installed. Ignoring", 30)return []- try:- return _simplify_urls([AppriseURLModel.model_validate({"url": url}) for url in set(urls)])- except ValidationError as e:- handle_validation_error(e, title="Apprise", file=file)- sys.exit(1)+ return _simplify_urls([AppriseURLModel.model_validate({"url": url}) for url in set(urls)])def _simplify_urls(apprise_urls: list[AppriseURLModel]) -> list[AppriseURL]:diff --git a/cyberdrop_dl/utils/yaml.py b/cyberdrop_dl/utils/yaml.pydeleted file mode 100644index eefc4b527..000000000--- a/cyberdrop_dl/utils/yaml.py+++ /dev/null@@ -1,106 +0,0 @@-from __future__ import annotations--import logging-import sys-from datetime import date, timedelta-from enum import Enum-from pathlib import Path, PurePath-from typing import TYPE_CHECKING, Any--import yaml-from pydantic import BaseModel, ValidationError-from yarl import URL--from cyberdrop_dl.constants import CLI_VALIDATION_ERROR_FOOTER, VALIDATION_ERROR_FOOTER-from cyberdrop_dl.exceptions import InvalidYamlError--if TYPE_CHECKING:- from pydantic_core import ErrorDetails---class TimedeltaSerializer(BaseModel):- duration: timedelta---def _save_as_str(dumper: yaml.Dumper, value: object):- if isinstance(value, Enum):- return dumper.represent_str(value.name)- return dumper.represent_str(str(value))---def _save_date(dumper: yaml.Dumper, value: date):- return dumper.represent_str(value.isoformat())---def _save_timedelta(dumper: yaml.Dumper, value: timedelta):- timespan = TimedeltaSerializer(duration=value).model_dump(mode="json")- return dumper.represent_str(timespan["duration"])---yaml.add_multi_representer(PurePath, _save_as_str)-yaml.add_multi_representer(Enum, _save_as_str)-yaml.add_multi_representer(date, _save_date)-yaml.add_representer(timedelta, _save_timedelta)-yaml.add_representer(URL, _save_as_str)---def save(file: Path, data: BaseModel | dict[str, Any]) -> None:- """Saves a dict to a yaml file."""- if isinstance(data, BaseModel):- data = data.model_dump()- file.parent.mkdir(parents=True, exist_ok=True)- file.write_text(- yaml.dump(data, default_flow_style=False),- encoding="utf8",- )---def load(file: Path, *, create: bool = False) -> dict[str, Any]:- """Loads a yaml file and returns it as a dict."""- if create:- file.parent.mkdir(parents=True, exist_ok=True)- if not file.is_file():- file.touch()- try:- yaml_values = yaml.safe_load(file.read_text(encoding="utf8"))- return yaml_values or {}- except KeyboardInterrupt:- raise- except Exception as e:- raise InvalidYamlError(file, e) from None---def handle_validation_error(e: ValidationError, *, title: str = "", file: Path | None = None):- """Logs the validation error details and exits the program."""-- startup_logger = logging.getLogger("cyberdrop_dl_startup")- error_count = e.error_count()- msg = ""- if file:- msg += f"File '{file}' has an invalid config\n\n"-- show_title = title or e.title- msg += f"Found {error_count} error{'s' if error_count > 1 else ''} [{show_title}]:"- from_cli = title == "CLI arguments"- footer = CLI_VALIDATION_ERROR_FOOTER if from_cli else VALIDATION_ERROR_FOOTER- for error in e.errors(include_url=False):- option_name = get_field_name(error, from_cli)- msg += f"\n\nOption '{option_name}' with value '{error['input']}' is invalid:\n"- msg += f" {error['msg']}"-- msg += "\n\n" + footer- startup_logger.error(msg)- sys.exit(1)---def get_field_name(error: ErrorDetails, from_cli: bool = False) -> str:- """Get a human readable representation of the field that raised this error"""-- if not from_cli:- return ".".join(map(str, error["loc"]))-- option_name: str | int = error["loc"][-1]- if isinstance(option_name, int):- option_name = ".".join(map(str, error["loc"][-2:]))- option_name = option_name.replace("_", "-")- return f"--{option_name}"diff --git a/cyberdrop_dl/yaml.py b/cyberdrop_dl/yaml.pynew file mode 100644index 000000000..9ef215fd7--- /dev/null+++ b/cyberdrop_dl/yaml.py@@ -0,0 +1,53 @@+from __future__ import annotations++from datetime import date, timedelta+from enum import Enum+from pathlib import Path, PurePath+from typing import TYPE_CHECKING, Any++import yaml+from yarl import URL++from cyberdrop_dl.exceptions import InvalidYamlError++if TYPE_CHECKING:+ from pydantic import BaseModel+ from yaml.nodes import ScalarNode+++def _str(dumper: yaml.Dumper, value: object) -> ScalarNode:+ return dumper.represent_str(str(value))+++def _enum(dumper: yaml.Dumper, value: Enum) -> ScalarNode:+ return dumper.represent_str(value.name)+++def _date(dumper: yaml.Dumper, value: date) -> ScalarNode:+ return dumper.represent_str(value.isoformat())+++yaml.add_multi_representer(PurePath, _str)+yaml.add_multi_representer(Enum, _enum)+yaml.add_multi_representer(date, _date)+yaml.add_representer(timedelta, _str)+yaml.add_representer(URL, _str)+++def save(file: Path, /, data: BaseModel | dict[str, Any]) -> None:+ """Saves a dict to a yaml file."""+ if not isinstance(data, dict):+ data = data.model_dump()++ file.parent.mkdir(parents=True, exist_ok=True)+ with file.open("w", encoding="utf8") as file_io:+ yaml.dump(data, file_io, default_flow_style=False)+++def load(file: Path, /) -> dict[str, Any]:+ try:+ with file.open("r", encoding="utf8") as file_io:+ return yaml.safe_load(file_io) or {}++ except yaml.YAMLError as e:+ raise InvalidYamlError(file, e) from ediff --git a/tests/test_cli.py b/tests/test_cli.pyindex 6fc36026f..ff6922554 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -1,11 +1,10 @@from pathlib import Path-from unittest import mockimport pytestfrom pydantic import ValidationErrorfrom cyberdrop_dl.cli import parse_args-from cyberdrop_dl.main import _create_director, run+from cyberdrop_dl.main import run@pytest.mark.parametrize(@@ -24,75 +23,6 @@ def test_command_by_console_output(tmp_cwd: Path, capsys: pytest.CaptureFixture[assert text in output-def test_startup_logger_should_not_be_created_on_a_successful_run(tmp_cwd: Path) -> None:- run("--download")- startup_file = tmp_cwd / "startup.log"- assert not startup_file.exists()---def test_startup_logger_should_not_be_created_on_invalid_cookies(tmp_cwd: Path) -> None:- from cyberdrop_dl.utils.logger import catch_exceptions-- director = _create_director("--download")- cookies_file = director.manager.path_manager.cookies_dir / "cookies.txt"- cookies_file.write_text("Not a cookie file", encoding="utf8")- catch_exceptions(director.run)()-- logs = director.manager.path_manager.main_log.read_text(encoding="utf8")- assert "does not look like a Netscape format cookies file" in logs-- startup_file = tmp_cwd / "startup.log"- assert not startup_file.exists()---def test_startup_logger_is_created_on_yaml_error(tmp_cwd: Path) -> None:- from cyberdrop_dl.exceptions import InvalidYamlError-- with mock.patch(- "cyberdrop_dl.director.Director._run", side_effect=InvalidYamlError(Path("fake_file.yaml"), ValueError())- ):- try:- run("--download")- except SystemExit:- pass-- startup_file = tmp_cwd / "startup.log"- assert startup_file.exists()-- logs = startup_file.read_text(encoding="utf8")- assert "Unable to read file" in logs--- "exception, exists",- [- (ValueError, True),- (OSError, True),- (KeyboardInterrupt, False),- (ValidationError("", []), False),- ],-)-def test_startup_logger_when_manager_startup_fails(- tmp_cwd: Path, exception: Exception | type[Exception], exists: bool, capsys: pytest.CaptureFixture[str]-) -> None:- with mock.patch("cyberdrop_dl.managers.manager.Manager.args_consolidation", side_effect=exception):- try:- run("--download")- except SystemExit:- pass- startup_file = tmp_cwd / "startup.log"- assert startup_file.exists() == exists---def test_startup_logger_should_not_be_created_when_using_invalid_cli_args(tmp_cwd: Path) -> None:- try:- run("--invalid-command")- except SystemExit:- pass- startup_file = tmp_cwd / "startup.log"- assert not startup_file.exists()--def test_impersonate_defaults_to_true_with_no_args() -> None:result = parse_args(["--download"])assert result.cli_only_args.impersonate is None@@ -106,5 +36,5 @@ def test_impersonate_accepts_valid_targets() -> None:def test_impersonate_does_not_accepts_invalid_values() -> None:- with pytest.raises(SystemExit):+ with pytest.raises(ValidationError):parse_args(["--impersonate", "not_a_browser"])