Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: move prompts to their own module
NTFSvolume2988ac398066
diff --git a/cyberdrop_dl/cli/compat.py b/cyberdrop_dl/cli/compat.pyindex 7762fa0ba..4347f5c3e 100644--- a/cyberdrop_dl/cli/compat.py+++ b/cyberdrop_dl/cli/compat.py@@ -26,9 +26,9 @@ def _check_for_v9_database() -> None:)logger.warning(msg, db, default.db_file)- from cyberdrop_dl.program_ui import _ask_confirmation+ from cyberdrop_dl.prompts import ask_confirmation- if _ask_confirmation("Do you want to move the database to the new default location?"):+ if ask_confirmation("Do you want to move the database to the new default location?"):_move_database(db, default.db_file)returndiff --git a/cyberdrop_dl/program_ui.py b/cyberdrop_dl/program_ui.pyindex dfca3a1d5..4ecc2b74a 100644--- a/cyberdrop_dl/program_ui.py+++ b/cyberdrop_dl/program_ui.py@@ -1,65 +1,29 @@from __future__ import annotations-import osimport sys-from pathlib import Path-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKINGimport aiohttp-import inquirer-import inquirer.questions-from inquirer.themes import BlueComposure-from rich.console import Consolefrom rich.markdown import Markdown-from rich.text import Textfrom cyberdrop_dl import __version__, aio, statsfrom cyberdrop_dl.hasher import Hasher, hash_directoryfrom cyberdrop_dl.progress import hyperlink+from cyberdrop_dl.prompts import ask_choices, ask_confirmation, ask_dir, console, enter_to_continuefrom cyberdrop_dl.sorter import Sorterfrom cyberdrop_dl.utils import text_editorif TYPE_CHECKING:- from collections.abc import Callable, Iterable+ from collections.abc import Callable+ from pathlib import Pathfrom cyberdrop_dl.manager import Manager-_ERROR = Text("ERROR: ", style="bold red")-_WARNING = Text("WARNING:", style="bold yellow")_CHANGELOG_URL = "https://raw.githubusercontent.com/Cyberdrop-DL/cyberdrop-dl/refs/heads/main/CHANGELOG.md"_changelog_content: str = ""-class _ConsoleWrapper:- def __init__(self, console: Console | None = None) -> None:- self.console: Console = console or Console()-- def info(self, *objects: object) -> None:- self.console.print(*objects)-- def warning(self, *objects: object) -> None:- self.console.print(_WARNING, *objects)-- def error(self, *objects: object) -> None:- self.console.print(_ERROR, *objects)-- def rule(self, color: str = "blue") -> None:- self.console.rule(style=color)-- def line(self, count: int = 1) -> None:- self.console.line(count)-- def input(self, msg: str = "") -> None:- self.console.input(msg)-- def clear(self) -> None:- _ = os.system("cls" if os.name == "nt" else "clear") # noqa: S605---_console = _ConsoleWrapper()--def _changelog() -> str:global _changelog_content # noqa: PLW0603if not _changelog_content:@@ -81,36 +45,33 @@ def run(manager: Manager) -> None:while True:_app_header(manager)- answer = _ask_choices(choices)+ answer = ask_choices(choices)done = choices[answer](manager)if done:breakdef _scan_and_create_hashes(manager: Manager) -> None:- path = _ask_dir(- "Select the directory to scan",- default=manager.config.download_folder,- )+ path = ask_dir("Select the directory to scan", default=manager.config.download_folder)hasher = Hasher.create(manager.config, manager.database, path)hash_stats = aio.run(hash_directory(hasher))stats.print(hash_stats)- _enter_to_continue()+ enter_to_continue()def _sort_files(manager: Manager) -> None:sorter = Sorter.from_manager(manager)- _console.warning(+ console.warning(f"You are about to sort files from '{sorter.input_dir}' to '{sorter.output_dir}'",)- if _ask_confirmation(explicit=True):+ if ask_confirmation(explicit=True):aio.run(sorter.run())- _enter_to_continue()+ enter_to_continue()def _should_create_config(file: Path) -> bool:- _console.warning("A default config file does not exists")- return _ask_confirmation(f"Do you want to create it at '{file}'?")+ console.warning("A default config file does not exists")+ return ask_confirmation(f"Do you want to create it at '{file}'?")def _edit_config(manager: Manager) -> None:@@ -124,20 +85,20 @@ def _edit_config(manager: Manager) -> None:try:text_editor.open(file)except ValueError as e:- _console.error(str(e))+ console.error(str(e))else:- _console.warning("You must restart cyberdrop-dl for config changes to take effect")+ console.warning("You must restart cyberdrop-dl for config changes to take effect")finally:- _enter_to_continue()+ enter_to_continue()def _edit_urls(manager: Manager) -> None:try:text_editor.open(manager.input_file)except ValueError as e:- _console.error(str(e))+ console.error(e)- _enter_to_continue()+ enter_to_continue()async def _fetch_changelog() -> str:@@ -150,22 +111,22 @@ async def _fetch_changelog() -> str:def _view_changelog() -> None:- _console.clear()+ console.clear()try:content = _changelog()except Exception as e: # noqa: BLE001- _console.error("UNABLE TO GET CHANGELOG INFORMATION", repr(e))- _enter_to_continue()+ console.error("UNABLE TO GET CHANGELOG INFORMATION", repr(e))+ enter_to_continue()return- with _console.console.pager(links=True):- _console.info(Markdown(content, justify="left"))+ with console.console.pager(links=True):+ console.info(Markdown(content, justify="left"))def _app_header(manager: Manager) -> None:- _console.clear()- _console.info(f"[bold]cyberdrop-dl ([blue]v{__version__!s}[/blue])[/bold]")- _console.rule()+ console.clear()+ console.info(f"[bold]cyberdrop-dl ([blue]v{__version__!s}[/blue])[/bold]")+ console.rule()paths = {"Config file": manager.config.source,"Database file": manager.appdata.db_file,@@ -176,92 +137,6 @@ def _app_header(manager: Manager) -> None:}padding = max(map(len, paths))for name, file in paths.items():- _console.info(f"{name:<{padding}} :", hyperlink(file) if file else None)-- _console.line()---def _ask_choices[T](choices: Iterable[T]) -> T:- return _ask( # pyright: ignore[reportAny]- inquirer.List(- "main",- message="What would you like to do",- choices=list(choices),- )- )-+ console.info(f"{name:<{padding}} :", hyperlink(file) if file else None)-def _ask(question: inquirer.questions.Question) -> Any:- answers = inquirer.prompt(- [question],- raise_keyboard_interrupt=True,- theme=BlueComposure(),- )- assert answers- return next(iter(answers.values()))---def _ask_text(text: str) -> str:- return _ask(inquirer.Text("text", message=text))---def _ask_confirmation(text: str = "", *, explicit: bool = False) -> bool:- if explicit:- msg = "Type 'YES' to proceed"- answer = _ask_text(f"{text}. {msg}" if text else msg)- return answer.strip().casefold() == "yes"- return _ask(inquirer.Confirm("text", message=text))---def _ask_dir(message: str = "Select dir path", default: Path | None = None) -> Path:-- def is_dir(path: Path) -> None:- if not path.is_dir():- raise NotADirectoryError(str(path))-- return _ask_path(message, default, validate=is_dir)---def _ask_file(message: str = "Select file", default: Path | None = None) -> Path:-- def is_file(path: Path) -> None:- if not path.is_file():- raise IsADirectoryError(str(path))-- return _ask_path(message, default, validate=is_file)---def _ask_path(- message: str = "Select path",- default: Path | None = None,- *,- validate: Callable[[Path], None] | None = None,- must_exists: bool = True,-) -> Path:- while True:- try:- answer = _ask(- inquirer.Text(- "path",- message=message,- default=default or Path.home(),- )- )-- path = Path(answer).expanduser()- if must_exists and not path.exists():- raise FileNotFoundError(answer)- if validate:- validate(path)-- except OSError as e:- _console.error(repr(e))- else:- return path.resolve()---def _enter_to_continue() -> None:- if "pytest" in sys.modules:- return- _console.rule()- _console.input("Press <ENTER> to continue")+ console.line()diff --git a/cyberdrop_dl/prompts.py b/cyberdrop_dl/prompts.pynew file mode 100644index 000000000..c83476e40--- /dev/null+++ b/cyberdrop_dl/prompts.py@@ -0,0 +1,117 @@+from __future__ import annotations++import os+import sys+from pathlib import Path+from typing import TYPE_CHECKING, Any++import inquirer+import inquirer.questions+from inquirer.themes import BlueComposure+from rich.console import Console+from rich.text import Text++if TYPE_CHECKING:+ from collections.abc import Callable, Iterable+++_ERROR = Text("ERROR: ", style="bold red")+_WARNING = Text("WARNING:", style="bold yellow")+++class _ConsoleWrapper:+ def __init__(self, console: Console | None = None) -> None:+ self.console: Console = console or Console()++ def info(self, *objects: object) -> None:+ self.console.print(*objects)++ def warning(self, *objects: object) -> None:+ self.console.print(_WARNING, *objects)++ def error(self, *objects: object) -> None:+ self.console.print(_ERROR, *objects)++ def rule(self, color: str = "blue") -> None:+ self.console.rule(style=color)++ def line(self, count: int = 1) -> None:+ self.console.line(count)++ def input(self, msg: str = "") -> None:+ self.console.input(msg)++ def clear(self) -> None:+ _ = os.system("cls" if os.name == "nt" else "clear") # noqa: S605+++console = _ConsoleWrapper()+++def enter_to_continue() -> None:+ if "pytest" in sys.modules:+ return+ console.rule()+ console.input("Press <ENTER> to continue")+++def ask(question: inquirer.questions.Question) -> Any:+ answers = inquirer.prompt([question], raise_keyboard_interrupt=True, theme=BlueComposure())+ assert answers+ return next(iter(answers.values()))+++def ask_choices[T](choices: Iterable[T]) -> T:+ return ask(inquirer.List("main", message="What would you like to do", choices=list(choices)))+++def ask_text(text: str, default: object | None = None) -> str:+ return ask(inquirer.Text("text", message=text, default=default))+++def ask_confirmation(text: str = "", *, explicit: bool = False) -> bool:+ if explicit:+ msg = "Type 'YES' to proceed"+ answer = ask_text(f"{text}. {msg}" if text else msg)+ return answer.strip().casefold() == "yes"+ return ask(inquirer.Confirm("text", message=text))+++def ask_dir(message: str = "Select dir path", default: Path | None = None) -> Path:++ def is_dir(path: Path) -> None:+ if not path.is_dir():+ raise NotADirectoryError(str(path))++ return ask_path(message, default, validate=is_dir)+++def ask_file(message: str = "Select file", default: Path | None = None) -> Path:++ def is_file(path: Path) -> None:+ if not path.is_file():+ raise IsADirectoryError(str(path))++ return ask_path(message, default, validate=is_file)+++def ask_path(+ message: str = "Select path",+ default: Path | None = None,+ *,+ validate: Callable[[Path], None] | None = None,+ must_exists: bool = True,+) -> Path:+ while True:+ try:+ answer = ask_text(message, default=default or Path.home())+ path = Path(answer).expanduser()+ if must_exists and not path.exists():+ raise FileNotFoundError(answer)+ if validate:+ validate(path)++ except OSError as e:+ console.error(repr(e))+ else:+ return path.resolve()