Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
fix: some exceptions not being logged (#1366)
NTFSvolumeeba187e470b8
diff --git a/cyberdrop_dl/director.py b/cyberdrop_dl/director.pyindex a2f0311dc..9ed25738b 100644--- a/cyberdrop_dl/director.py+++ b/cyberdrop_dl/director.py@@ -14,16 +14,21 @@ from time import perf_counterfrom typing import TYPE_CHECKING, ParamSpec, TypeVarfrom pydantic import ValidationError-from rich import print as rich_printfrom cyberdrop_dl import constants, envfrom cyberdrop_dl.dependencies import browser_cookie3-from cyberdrop_dl.exceptions import InvalidYamlErrorfrom cyberdrop_dl.managers.manager import Managerfrom cyberdrop_dl.scraper.scrape_mapper import ScrapeMapperfrom cyberdrop_dl.ui.program_ui import ProgramUIfrom cyberdrop_dl.utils.apprise import send_apprise_notifications-from cyberdrop_dl.utils.logger import LogHandler, QueuedLogger, log, log_spacer, log_with_color+from cyberdrop_dl.utils.logger import (+ LogHandler,+ QueuedLogger,+ log,+ log_spacer,+ log_with_color,+ startup_logger,+)from cyberdrop_dl.utils.sorting import Sorterfrom cyberdrop_dl.utils.updates import check_latest_pypifrom cyberdrop_dl.utils.utilities import check_partials_and_empty_folders@@ -31,22 +36,11 @@ from cyberdrop_dl.utils.webhook import send_webhook_messagefrom cyberdrop_dl.utils.yaml import handle_validation_errorif TYPE_CHECKING:- from collections.abc import Callable, Coroutine, Generator+ from collections.abc import Callable, Coroutine, SequenceP = ParamSpec("P")R = TypeVar("R")-startup_logger = logging.getLogger("cyberdrop_dl_startup")---def new_startup_log_file() -> Path:- file = Path.cwd().joinpath("startup.log")- file.unlink(missing_ok=True)- return file---STARTUP_LOGGER_FILE = new_startup_log_file()-class ExitCode(IntEnum):OK = 0@@ -182,18 +176,16 @@ def _setup_debug_logger(manager: Manager) -> Path | None:settings_data.runtime_options.log_level = log_leveldebug_logger.setLevel(log_level)debug_log_file_path = Path(__file__).parents[1] / "cyberdrop_dl_debug.log"- with _startup_logging():- if env.DEBUG_LOG_FOLDER:- debug_log_folder = Path(env.DEBUG_LOG_FOLDER)- if not debug_log_folder.is_dir():- msg = "Value of env var 'CDL_DEBUG_LOG_FOLDER' is invalid."- msg += f" Folder '{debug_log_folder}' does not exists"- startup_logger.error(msg)- sys.exit(_C.ERROR)- date = datetime.now().strftime("%Y%m%d_%H%M%S")- debug_log_file_path = debug_log_folder / f"cyberdrop_dl_debug_{date}.log"-- file_io = debug_log_file_path.open("w", encoding="utf8")+ if env.DEBUG_LOG_FOLDER:+ debug_log_folder = Path(env.DEBUG_LOG_FOLDER)+ if not debug_log_folder.is_dir():+ msg = "Value of env var 'CDL_DEBUG_LOG_FOLDER' is invalid."+ msg += f" Folder '{debug_log_folder}' does not exists"+ raise FileNotFoundError(None, msg, env.DEBUG_LOG_FOLDER)+ date = datetime.now().strftime("%Y%m%d_%H%M%S")+ debug_log_file_path = debug_log_folder / f"cyberdrop_dl_debug_{date}.log"++ file_io = debug_log_file_path.open("w", encoding="utf8")file_handler = LogHandler(level=log_level, file=file_io, width=settings_data.logs.log_line_width, debug=True)queued_logger = QueuedLogger(manager, file_handler, "debug")@@ -213,17 +205,16 @@ def _setup_debug_logger(manager: Manager) -> Path | None:def _setup_main_logger(manager: Manager, config_name: str) -> None:logger = logging.getLogger("cyberdrop_dl")queued_logger = manager.loggers.pop("main", None)- with _startup_logging():- if manager.multiconfig and queued_logger:- log(f"Picking new config: '{config_name}' ...", 20)- try:- manager.config_manager.change_config(config_name)- log(f"Changed config to '{config_name}'...", 20)- finally:- logger.removeHandler(queued_logger.handler)- queued_logger.stop()-- file_io = manager.path_manager.main_log.open("w", encoding="utf8")+ if manager.multiconfig and queued_logger:+ log(f"Picking new config: '{config_name}' ...", 20)+ try:+ manager.config_manager.change_config(config_name)+ log(f"Changed config to '{config_name}'...", 20)+ finally:+ logger.removeHandler(queued_logger.handler)+ queued_logger.stop()++ file_io = manager.path_manager.main_log.open("w", encoding="utf8")settings_data = manager.config_manager.settings_datalog_level = settings_data.runtime_options.log_level@@ -239,104 +230,40 @@ def _setup_main_logger(manager: Manager, config_name: str) -> None:logger.addHandler(queued_logger.handler)-def _setup_startup_logger(*, first_time_setup: bool = False) -> None:- global STARTUP_LOGGER_FILE- if first_time_setup:- # Get startup logger again in case the CWD changed after the module was imported (for pytest)- STARTUP_LOGGER_FILE = new_startup_log_file()- _destroy_startup_logger()- startup_logger.setLevel(10)- console_handler = LogHandler(level=10)- startup_logger.addHandler(console_handler)-- file_io = STARTUP_LOGGER_FILE.open("a", encoding="utf8")- file_handler = LogHandler(level=10, file=file_io, width=constants.DEFAULT_CONSOLE_WIDTH)- startup_logger.addHandler(file_handler)---def _destroy_startup_logger(remove_all_handlers: bool = True) -> None:- handlers: list[LogHandler] = startup_logger.handlers # type: ignore- for handler in handlers[:]: # create copy- if not (handler.console._file or remove_all_handlers):- continue- if handler.console._file:- handler.console._file.close()- startup_logger.removeHandler(handler)- handler.close()-- if STARTUP_LOGGER_FILE.is_file() and STARTUP_LOGGER_FILE.stat().st_size > 0:- return- STARTUP_LOGGER_FILE.unlink(missing_ok=True)---def _startup_logging(*, first_time_setup: bool = False) -> Generator:- exit_code = _C.ERROR- try:- _setup_startup_logger(first_time_setup=first_time_setup)- yield-- except InvalidYamlError as e:- startup_logger.error(e.message)-- except browser_cookie3.BrowserCookieError:- startup_logger.exception("")-- except OSError as e:- startup_logger.exception(str(e))-- except KeyboardInterrupt:- startup_logger.info("Exiting...")- exit_code = _C.OK-- except Exception:- msg = "An error occurred, please report this to the developer with your logs file:"- startup_logger.exception(msg)-- else:- return-- finally:- _destroy_startup_logger()-- sys.exit(exit_code)---def _setup_manager(args: tuple[str, ...] | None = None) -> Manager:+def _setup_manager(args: Sequence[str] | None = None) -> Manager:"""Starts the program and returns the manager.This will also run the UI for the programAfter this function returns, the manager will be ready to use and scraping / downloading can begin."""- with _startup_logging(first_time_setup=True):- manager = Manager(args)- try:- manager.startup()- if manager.parsed_args.cli_only_args.multiconfig:- startup_logger.info("validating all configs, please wait...")- manager.validate_all_configs()- if not manager.parsed_args.cli_only_args.download:- ProgramUI(manager)+ manager = Manager(args)+ try:+ manager.startup()+ if manager.parsed_args.cli_only_args.multiconfig:+ startup_logger.info("validating all configs, please wait...")+ manager.validate_all_configs()++ if not manager.parsed_args.cli_only_args.download:+ ProgramUI(manager)- except ValidationError as e:- sources = {- "GlobalSettings": manager.config_manager.global_settings,- "ConfigSettings": manager.config_manager.settings,- "AuthSettings": manager.config_manager.authentication_settings,- }+ 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)- file = sources.get(e.title)- handle_validation_error(e, file=file)- sys.exit(_C.ERROR)+ handle_validation_error(e, file=file)+ sys.exit(_C.ERROR)- return manager+ return managerclass Director:"""Creates a manager and runs it"""- def __init__(self, args: tuple[str, ...] | None = None) -> None:+ def __init__(self, args: Sequence[str] | None = None) -> None:if os.name == "nt":asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())self.loop = asyncio.new_event_loop()@@ -348,15 +275,17 @@ class Director:def run(self) -> int:return self._run()+ async def async_run(self) -> None:+ try:+ await _run_manager(self.manager)+ finally:+ await self.manager.close()+def _run(self) -> int:exit_code = _C.ERRORwith contextlib.suppress(Exception):- try:- asyncio.run(_run_manager(self.manager))- exit_code = _C.OK- except KeyboardInterrupt:- rich_print("Trying to Exit ...")- finally:- asyncio.run(self.manager.close())+ asyncio.run(self.async_run())+ exit_code = _C.OK+self.loop.close()return exit_codediff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.pyindex a6219245c..d448196a5 100644--- a/cyberdrop_dl/main.py+++ b/cyberdrop_dl/main.py@@ -1,18 +1,32 @@+from __future__ import annotations+import sys+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from collections.abc import Sequence++ from cyberdrop_dl.director import Director+++def main(args: Sequence[str] | None = None) -> None:+ sys.exit(run(args))+++def run(args: Sequence[str] | None = None) -> str | int | None:+ from cyberdrop_dl.utils.logger import catch_exceptions+ @catch_exceptions+ def run_() -> int:+ return _create_director(args).run()-def main() -> None:- sys.exit(run())+ return run_()-def run(args: tuple[str, ...] | None = None) -> str | int:- try:- from cyberdrop_dl.director import Director+def _create_director(args: Sequence[str] | None = None) -> Director:+ from cyberdrop_dl.director import Director- director = Director(args)- return director.run()- except KeyboardInterrupt:- return "\nKeyboardInterrupt"+ return Director(args)if __name__ == "__main__":diff --git a/cyberdrop_dl/managers/manager.py b/cyberdrop_dl/managers/manager.pyindex 955196a5c..7485bc5cc 100644--- a/cyberdrop_dl/managers/manager.py+++ b/cyberdrop_dl/managers/manager.py@@ -27,6 +27,7 @@ from cyberdrop_dl.utils.utilities import close_if_defined, get_system_informatioif TYPE_CHECKING:from asyncio import TaskGroup+ from collections.abc import Sequencefrom cyberdrop_dl.scraper.scrape_mapper import ScrapeMapper@@ -37,7 +38,10 @@ class AsyncioEvents(NamedTuple):class Manager:- def __init__(self, args: tuple[str, ...] | None = None) -> None:+ def __init__(self, args: Sequence[str] | None = None) -> None:+ if isinstance(args, str):+ args = [args]+self.parsed_args: ParsedArgs = field(init=False)self.cache_manager: CacheManager = CacheManager(self)self.path_manager: PathManager = field(init=False)diff --git a/cyberdrop_dl/utils/logger.py b/cyberdrop_dl/utils/logger.pyindex 26007d716..f606b3135 100644--- a/cyberdrop_dl/utils/logger.py+++ b/cyberdrop_dl/utils/logger.py@@ -1,11 +1,13 @@from __future__ import annotations+import contextlibimport jsonimport loggingimport queue+from functools import wrapsfrom logging.handlers import QueueHandler, QueueListenerfrom pathlib import Path-from typing import IO, TYPE_CHECKING+from typing import IO, TYPE_CHECKING, ParamSpecfrom rich._log_render import LogRenderfrom rich.console import Console, Group@@ -16,40 +18,61 @@ from rich.padding import Paddingfrom rich.text import Text, TextTypefrom cyberdrop_dl import constants, env+from cyberdrop_dl.dependencies import browser_cookie3+from cyberdrop_dl.exceptions import InvalidYamlErrorlogger = logging.getLogger("cyberdrop_dl")logger_debug = logging.getLogger("cyberdrop_dl_debug")+startup_logger = logging.getLogger("cyberdrop_dl_startup")_DEFAULT_CONSOLE = Console()-ERROR_PREFIX = "\n[bold red]ERROR: [/bold red]"-USER_NAME = Path.home().resolve().parts[-1]-NEW_ISSUE_URL = "https://github.com/jbsparrow/CyberDropDownloader/issues/new/choose"+_USER_NAME = Path.home().resolve().name+_NEW_ISSUE_URL = "https://github.com/jbsparrow/CyberDropDownloader/issues/new/choose"if TYPE_CHECKING:- from collections.abc import Callable, Iterable+ from collections.abc import Callable, Generator, Iterablefrom datetime import datetimefrom rich.console import ConsoleRenderablefrom cyberdrop_dl.managers.manager import Manager+ _P = ParamSpec("_P")+ _ExitCode = str | int | None-EXCLUDE_PATH_LOGGING_FROM = "logger.py", "base.py", "session.py", "cache_control.py"+class RedactedConsole(Console):+ """Custom console to remove username from logs"""++ def _render_buffer(self, buffer) -> str:+ output: str = super()._render_buffer(buffer)+ return _redact_message(output)+++class JsonLogRecord(logging.LogRecord):+ def getMessage(self) -> str: # noqa: N802+ """`dicts` will be logged as json, lazily"""++ msg = str(self._proccess_msg(self.msg))+ if self.args:+ args = map(self._proccess_msg, self.args)+ try:+ return msg.format(*args)+ except Exception:+ return msg % args++ return msg-def get_log_level_text(name: str, color: str) -> Text:- # From markup to prevent applying the color to the entire line- return Text.from_markup(f"[{color}]{name}[/{color}]") if color else Text(name)+ @staticmethod+ def _proccess_msg(msg: object) -> object:+ # TODO: Use our custom decoder to support more types+ if isinstance(msg, dict):+ return json.dumps(msg, indent=2, ensure_ascii=False, default=str)+ return msg-RICH_LOG_LEVELS = {- 10: get_log_level_text("DEBUG ", "cyan"),- 20: get_log_level_text("INFO ", ""),- 30: get_log_level_text("WARNING ", "yellow"),- 40: get_log_level_text("ERROR ", "bold red"),- 50: get_log_level_text("CRITICAL ", "bold red"),-}+logging.setLogRecordFactory(JsonLogRecord)class LogHandler(RichHandler):@@ -109,7 +132,8 @@ class QueuedLogger:class NoPaddingLogRender(LogRender):- cdl_padding = 0+ cdl_padding: int = 0+ EXCLUDE_PATH_LOGGING_FROM: tuple[str, ...] = "logger.py", "base.py", "session.py", "cache_control.py"def __call__( # type: ignore[reportIncompatibleMethodOverride]self,@@ -143,9 +167,9 @@ class NoPaddingLogRender(LogRender):output.pad_right(1)if not self.cdl_padding:- self.cdl_padding = get_renderable_length(output)+ self.cdl_padding = _get_renderable_length(output)- if self.show_path and path and not any(path.startswith(p) for p in EXCLUDE_PATH_LOGGING_FROM):+ if self.show_path and path and not any(path.startswith(p) for p in self.EXCLUDE_PATH_LOGGING_FROM):path_text = Text(style="log.path")path_text.append(path, style=f"link file://{link_path}" if link_path else "")if line_no:@@ -161,7 +185,7 @@ class NoPaddingLogRender(LogRender):for renderable in Renderables(renderables): # type: ignoreif isinstance(renderable, Text):- renderable = indent_text(renderable, console, self.cdl_padding)+ renderable = _indent_text(renderable, console, self.cdl_padding)renderable.stylize("log.message")output.append(renderable)continue@@ -170,12 +194,12 @@ class NoPaddingLogRender(LogRender):return Group(output, *padded_lines)-def get_renderable_length(renderable) -> int:+def _get_renderable_length(renderable) -> int:measurement = Measurement.get(_DEFAULT_CONSOLE, _DEFAULT_CONSOLE.options, renderable)return measurement.maximum-def indent_text(text: Text, console: Console, indent: int = 30) -> Text:+def _indent_text(text: Text, console: Console, indent: int = 30) -> Text:"""Indents each line of a Text object except the first one."""indent_str = Text("\n" + (" " * indent))new_text = Text()@@ -190,51 +214,22 @@ def indent_text(text: Text, console: Console, indent: int = 30) -> Text:return first_line.append(new_text)-def indent_string(text: str, indent_level: int = 9) -> str:- """Indents each line of a string object except the first one."""- indentation = " " * indent_level- lines = text.splitlines()- if len(lines) <= 1:- return text- indented_lines = [lines[0]] + [indentation + line for line in lines[1:]]- return "\n".join(indented_lines)---class RedactedConsole(Console):- """Custom console to remove username from logs"""-- def _render_buffer(self, buffer) -> str:- output: str = super()._render_buffer(buffer)- return _redact_message(output)---def process_log_msg(message: object) -> object:- if isinstance(message, dict):- return json.dumps(message, indent=4, ensure_ascii=False)- return message---def create_rich_log_msg(msg: str, level: int = 10) -> Text:- """Create a rich text where the level has color"""- rich_level = RICH_LOG_LEVELS.get(level) or RICH_LOG_LEVELS[10]- return rich_level + indent_string(msg)--def log(message: object, level: int = 10, bug: bool = False, **kwargs) -> None:"""Simple logging function."""- msg = process_log_msg(message)- log_debug(msg, level, **kwargs)+ log_debug(message, level, **kwargs)if bug:- msg = f"{msg}. Please open a bug report at {NEW_ISSUE_URL}"+ args = message, f"Please open a bug report at {_NEW_ISSUE_URL}"+ message = "{}. {}"level = 30- logger.log(level, msg, **kwargs)+ else:+ args = ()+ logger.log(level, message, *args, **kwargs)def log_debug(message: object, level: int = 10, **kwargs) -> None:"""Simple logging function."""if env.DEBUG_VAR:- msg = process_log_msg(message)- logger_debug.log(level, msg, **kwargs)+ logger_debug.log(level, message, **kwargs)def log_with_color(message: Text | str, style: str, level: int = 20, show_in_stats: bool = True, **kwargs) -> None:@@ -260,7 +255,70 @@ def _redact_message(message: Exception | Text | str) -> str:redacted = str(message)separators = ["\\", "\\\\", "/"]for sep in separators:- as_tail = sep + USER_NAME- as_part = USER_NAME + sep+ as_tail = sep + _USER_NAME+ as_part = _USER_NAME + sepredacted = redacted.replace(as_tail, f"{sep}[REDACTED]").replace(as_part, f"[REDACTED]{sep}")return redacted+++def _setup_startup_logger() -> Generator[None]:+ """Context manager to add a file handler to the startup logger++ It will only add it if we have an exception, to prevent creating an empty file"""+ startup_logger.setLevel(10)+ console_handler = LogHandler(level=10)+ startup_logger.addHandler(console_handler)+ try:+ yield++ except Exception:+ try:+ file = Path.cwd() / "startup.log"+ file_handler = LogHandler(+ level=10,+ file=file.open("w", encoding="utf8"),+ width=constants.DEFAULT_CONSOLE_WIDTH,+ )+ startup_logger.addHandler(file_handler)+ except OSError:+ # We could not create the file for some reason+ # Ignore this and just log to the console+ pass+ raise+++def catch_exceptions(func: Callable[_P, _ExitCode]) -> Callable[_P, _ExitCode]:+ """Decorator to automatically log uncaught exceptions.++ Exceptions will be logged to a file in the current working directory+ because the manager setup itself may have failed, therefore we don't know+ what the proper log file path is.+ """++ @wraps(func)+ def catch(*args, **kwargs) -> _ExitCode | None:+ try:+ with _setup_startup_logger():+ return func(*args, **kwargs)++ except InvalidYamlError as e:+ startup_logger.error(e.message)++ except browser_cookie3.BrowserCookieError:+ startup_logger.exception("")++ except OSError as e:+ startup_logger.exception(str(e))++ except KeyboardInterrupt:+ startup_logger.info("Exiting...")+ return++ except Exception:+ msg = "An error occurred, please report this to the developer with your logs file:"+ startup_logger.exception(msg)++ return 1++ return catchdiff --git a/tests/test_cli.py b/tests/test_cli.pyindex 94e00f825..0f0f0081b 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -1,8 +1,10 @@from pathlib import Path+from unittest import mockimport pytest+from pydantic import ValidationError-from cyberdrop_dl.main import run+from cyberdrop_dl.main import _create_director, run@pytest.mark.parametrize(@@ -14,9 +16,77 @@ from cyberdrop_dl.main import run)def test_command_by_console_output(tmp_cwd: Path, capsys: pytest.CaptureFixture[str], command: str, text: str) -> None:try:- run(tuple(command.split()))+ run(command.split())except SystemExit:pass- captured = capsys.readouterr()- output = captured.out+ output = capsys.readouterr().outassert text in output+++def test_startup_logger_should_not_be_created_on_a_successful_run(tmp_cwd: Path) -> None:+ run("--download")+ startup_file = Path.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_bytes(b"Not a cookie file")+ catch_exceptions(director.run)()++ logs = director.manager.path_manager.main_log.read_text()+ assert "does not look like a Netscape format cookies file" in logs++ startup_file = Path.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 = Path.cwd() / "startup.log"+ assert startup_file.exists()++ logs = startup_file.read_text()+ 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+) -> None:+ with mock.patch("cyberdrop_dl.managers.manager.Manager.set_constants", side_effect=exception):+ try:+ run("--download")+ except SystemExit:+ pass+ startup_file = Path.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 = Path.cwd() / "startup.log"+ assert not startup_file.exists()