Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: better error messages for invalid configs (#675)
NTFSvolume944e53c90c7a
diff --git a/cyberdrop_dl/clients/errors.py b/cyberdrop_dl/clients/errors.pyindex 7356b1fb8..a3630d840 100644--- a/cyberdrop_dl/clients/errors.py+++ b/cyberdrop_dl/clients/errors.py@@ -5,13 +5,13 @@ from http import HTTPStatusfrom pathlib import Pathfrom typing import TYPE_CHECKING+from yaml import YAMLErrorfrom yarl import URLfrom cyberdrop_dl.utils.constants import VALIDATION_ERROR_FOOTERif TYPE_CHECKING:from requests import Response- from yaml.constructor import ConstructorErrorfrom cyberdrop_dl.scraper.crawler import ScrapeItemfrom cyberdrop_dl.utils.data_enums_classes.url_objects import MediaItem@@ -189,11 +189,20 @@ class JDownloaderError(CDLBaseError):class InvalidYamlError(CDLBaseError):- def __init__(self, file: Path, e: ConstructorError) -> None:+ def __init__(self, file: Path, e: Exception) -> None:"""This error will be thrown when a yaml config file has invalid values."""- mark = e.problem_mark if hasattr(e, "problem_mark") else e- message = f"File '{file.resolve()}' has an invalid config. \n Please verify and edit it manually\n {mark}\n\n{VALIDATION_ERROR_FOOTER}"- super().__init__("Invalid YAML", message=message, origin=file)+ file_path = file.resolve()+ 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"\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}"+ super().__init__("Invalid YAML", message=msg, origin=file)@singledispatchdiff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.pyindex 7681e9e3f..ab315b0f4 100644--- a/cyberdrop_dl/main.py+++ b/cyberdrop_dl/main.py@@ -62,7 +62,9 @@ def startup() -> Manager | None:"ConfigSettings": manager.config_manager.settings,"AuthSettings": manager.config_manager.authentication_settings,}- handle_validation_error(e, sources=sources)++ file = sources.get(e.title)+ handle_validation_error(e, file=file)except KeyboardInterrupt:startup_logger.info("Exiting...")diff --git a/cyberdrop_dl/managers/config_manager.py b/cyberdrop_dl/managers/config_manager.pyindex 9fd783fd7..0a3aff7da 100644--- a/cyberdrop_dl/managers/config_manager.py+++ b/cyberdrop_dl/managers/config_manager.py@@ -8,6 +8,7 @@ from dataclasses import fieldfrom time import sleepfrom typing import TYPE_CHECKING+from cyberdrop_dl.clients.errors import InvalidYamlErrorfrom cyberdrop_dl.config_definitions import AuthSettings, ConfigSettings, GlobalSettingsfrom cyberdrop_dl.managers.log_manager import LogManagerfrom cyberdrop_dl.utils import yaml@@ -217,4 +218,7 @@ class ConfigManager:def is_in_file(search_value: str, file: Path) -> bool:if not file.is_file():return False- return search_value.casefold() in file.read_text().casefold()+ try:+ return search_value.casefold() in file.read_text().casefold()+ except Exception as e:+ raise InvalidYamlError(file, e) from ediff --git a/cyberdrop_dl/utils/apprise.py b/cyberdrop_dl/utils/apprise.pyindex ce03ac823..3f826e9be 100644--- a/cyberdrop_dl/utils/apprise.py+++ b/cyberdrop_dl/utils/apprise.py@@ -88,8 +88,7 @@ def get_apprise_urls(*, file: Path | None = None, urls: list[str] | None = None)return _simplify_urls([AppriseURLModel(url=url) for url in set(urls)])except ValidationError as e:- sources = {"AppriseURLModel": file} if file else None- handle_validation_error(e, sources=sources)+ handle_validation_error(e, title="Apprise", file=file)def _simplify_urls(apprise_urls: list[AppriseURLModel]) -> list[AppriseURL]:diff --git a/cyberdrop_dl/utils/constants.py b/cyberdrop_dl/utils/constants.pyindex 0cecfbcac..3d99a4fb2 100644--- a/cyberdrop_dl/utils/constants.py+++ b/cyberdrop_dl/utils/constants.py@@ -19,10 +19,13 @@ RICH_HANDLER_DEBUG_CONFIG = {"tracebacks_extra_lines": 2,"locals_max_length": 20,}-VALIDATION_ERROR_FOOTER = """Please read the documentation for guidance on how to resolve this error: https://script-ware.gitbook.io/cyberdrop-dl/reference/configuration-options-This is not a bug. Do not open issues related to this"""+VALIDATION_ERROR_FOOTER = """Please delete the file or fix the errors. Read the documentation to learn what's the expected format and values: https://script-ware.gitbook.io/cyberdrop-dl/reference/configuration-options+\nThis is not a bug. Do not open issues related to this"""+CLI_VALIDATION_ERROR_FOOTER = """Please read the documentation to learn about the expected values: https://script-ware.gitbook.io/cyberdrop-dl/reference/configuration-options+\nThis is not a bug. Do not open issues related to this"""+# regexRAR_MULTIPART_PATTERN = re.compile(r"^part\d+")SANITIZE_FILENAME_PATTERN = re.compile(r'[<>:"/\\|?*\']')diff --git a/cyberdrop_dl/utils/yaml.py b/cyberdrop_dl/utils/yaml.pyindex a800a3b59..ae9931adb 100644--- a/cyberdrop_dl/utils/yaml.py+++ b/cyberdrop_dl/utils/yaml.py@@ -5,14 +5,17 @@ import sysfrom datetime import date, timedeltafrom enum import Enumfrom pathlib import Path, PurePath+from typing import TYPE_CHECKINGimport yamlfrom pydantic import BaseModel, ValidationError-from yaml.error import YAMLErrorfrom yarl import URLfrom cyberdrop_dl.clients.errors import InvalidYamlError-from cyberdrop_dl.utils.constants import VALIDATION_ERROR_FOOTER+from cyberdrop_dl.utils.constants import CLI_VALIDATION_ERROR_FOOTER, VALIDATION_ERROR_FOOTER++if TYPE_CHECKING:+ from pydantic_core import ErrorDetailsclass TimedeltaSerializer(BaseModel):@@ -60,27 +63,43 @@ def load(file: Path, *, create: bool = False) -> dict:with file.open(encoding="utf8") as yaml_file:yaml_values = yaml.safe_load(yaml_file.read())return yaml_values if yaml_values else {}- except YAMLError as e:+ except KeyboardInterrupt:+ raise+ except Exception as e:raise InvalidYamlError(file, e) from None-def handle_validation_error(e: ValidationError, *, title: str | None = None, sources: dict[str, Path] | None = 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()- source = sources.get(e.title) if sources else None- title = title or e.title- source = f"from {source.resolve()}" if source else ""- msg = f"Found {error_count} error{'s' if error_count > 1 else ''} parsing {title} {source}"- startup_logger.error(msg)+ msg = ""+ if file:+ msg += f"File '{file.resolve()}' 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_FOOTERfor error in e.errors(include_url=False):- loc = ".".join(map(str, error["loc"]))- if title == "CLI arguments":- loc = error["loc"][-1]- if isinstance(error["loc"][-1], int):- loc = ".".join(map(str, error["loc"][-2:]))- loc = f"--{loc}"- msg = f"Value of '{loc}' is invalid:\n"- msg += f" {error['msg']} (input_value='{error['input']}', input_type='{error['type']}')\n"- startup_logger.error(msg)- startup_logger.error(VALIDATION_ERROR_FOOTER)+ 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}"