Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: decouple interative menu from main scrape logic

NTFSvolume28d535b406fd
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 4bbb29bc6..6ea18d0ce 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -126,8 +126,8 @@ and base your crawler on that. A simple crawler to use as base is [CloudFlareStr
- You **MAY** use HTTP code `422` (Unprocessable entity) for **expected** errors if no other HTTP code feels adequate
- You **MAY** use a short string instead of an HTTP code to convey a better context for an error (if required)
The string **SHOULD** be at most 20 characters long as it will be shown on the `Scrape Errors` sections of the TUI
-- You **SHOULD NOT** write logic in a defensive way for **unexpected** errors. If you need to perform an operation that **MAY** fail
- but is not **expected** to fail (ex: a dictionary key lookup on an API response), do not try to catch the exception, let it bubble up
+- You **SHOULD NOT** write logic in a defensive way for **unexpected** errors. If you need to perform an operation that could fail
+ but is not **expected** to fail (ex: a dictionary key lookup on an API response), do not try to catch the exception, let it bubble up.
It will eventually be logged by the `error_handling_wrapper`
- You **SHOULD** model site specific data into dataclasses, if possible
- You **MUST** create a new task for any coroutine whose result is not needed to complete the current task
diff --git a/cyberdrop_dl/commands/__init__.py b/cyberdrop_dl/commands/__init__.py
index a466753da..8c20eb969 100644
--- a/cyberdrop_dl/commands/__init__.py
+++ b/cyberdrop_dl/commands/__init__.py
@@ -23,7 +23,7 @@ type SQLiteFile = Annotated[Path, file_validator(".db")]
@Parameter(name="*")
[email protected](slots=True, frozen=True)
[email protected](slots=True)
class CLIarguments:
urls: Annotated[tuple[HttpURL, ...], Parameter(show=False)] = ()
diff --git a/cyberdrop_dl/commands/clean_up.py b/cyberdrop_dl/commands/clean_up.py
index 09a91f45b..1819ab04a 100644
--- a/cyberdrop_dl/commands/clean_up.py
+++ b/cyberdrop_dl/commands/clean_up.py
@@ -4,8 +4,6 @@ from typing import Annotated
from cyclopts import App, Parameter
from cyclopts.types import ResolvedExistingDirectory
-from cyberdrop_dl.utils import cleanup
-
app = App(name="cleanup", help="Perform maintenance tasks")
logger = logging.getLogger(__name__)
@@ -19,6 +17,7 @@ def files(
/,
) -> None:
"""Delete partial (`.cdl_hls` and `.part`) files, empty folders and empty files inside `path` (recursive)"""
+ from cyberdrop_dl.utils import cleanup
logger.info("Deleting partial downloads...")
cleanup.rm_partial_files(path)
diff --git a/cyberdrop_dl/commands/config.py b/cyberdrop_dl/commands/config.py
index d70685fc8..edc3afdb2 100644
--- a/cyberdrop_dl/commands/config.py
+++ b/cyberdrop_dl/commands/config.py
@@ -2,6 +2,7 @@ import logging
from cyclopts import App
+from cyberdrop_dl.commands import CLIarguments
from cyberdrop_dl.config import Config
from cyberdrop_dl.config.appdata import AppData
from cyberdrop_dl.prompts import ask_should_create_config
@@ -11,21 +12,23 @@ logger = logging.getLogger(__name__)
@app.command()
-def file() -> None:
- "Show the default config file path"
- app.console.print(AppData.default().config_file)
+def file(*, cli: CLIarguments | None = None) -> None:
+ "Show path to the config file"
+ app.console.print(cli.config_file if cli else AppData.default().config_file)
@app.command()
-def edit() -> None:
+def edit(*, cli: CLIarguments | None = None) -> None:
"Open the default config file on a text editor"
from cyberdrop_dl.utils import text_editor
- file = AppData.default().config_file
- if not file.exists():
- if not ask_should_create_config(file):
- return
- Config().save_to(file)
+ file = cli.config_file if cli else None
+ if not file:
+ file = AppData.default().config_file
+ if not file.exists():
+ if not ask_should_create_config(file):
+ return
+ Config().save_to(file)
text_editor.open(file)
diff --git a/cyberdrop_dl/commands/database.py b/cyberdrop_dl/commands/database.py
index 116251386..99b929023 100644
--- a/cyberdrop_dl/commands/database.py
+++ b/cyberdrop_dl/commands/database.py
@@ -1,8 +1,8 @@
from typing import Annotated
from cyclopts import App, Parameter
-from cyclopts.types import ResolvedExistingFile
+from cyberdrop_dl.commands import CLIarguments, SQLiteFile
from cyberdrop_dl.config.appdata import AppData
app = App(name="database", help="Commands for managing the database")
@@ -10,8 +10,8 @@ app = App(name="database", help="Commands for managing the database")
@app.command()
def transfer(
- db_path: Annotated[
- ResolvedExistingFile,
+ database_file: Annotated[
+ SQLiteFile,
Parameter(help="Path to the SQLite database file to migrate"),
],
*,
@@ -25,10 +25,10 @@ def transfer(
"""Migrate an old database to the latest schema version."""
from cyberdrop_dl.database.transfer import run as transfer_db
- transfer_db(db_path, force=force)
+ transfer_db(database_file, force=force)
@app.command()
-def file() -> None:
- "Show path of default database"
- app.console.print(AppData.default().db_file)
+def file(*, cli: CLIarguments | None = None) -> None:
+ "Show file path to the database"
+ app.console.print(cli.database_file if cli else AppData.default().db_file)
diff --git a/cyberdrop_dl/commands/scrape.py b/cyberdrop_dl/commands/scrape.py
index d048d27ba..b89be83bd 100644
--- a/cyberdrop_dl/commands/scrape.py
+++ b/cyberdrop_dl/commands/scrape.py
@@ -1,7 +1,6 @@
from __future__ import annotations
import logging
-from contextvars import ContextVar
from pathlib import Path
from typing import TYPE_CHECKING, Annotated
@@ -19,7 +18,6 @@ from cyberdrop_dl.models import merge_models
from cyberdrop_dl.models.types import HttpURL # noqa: TC001
from cyberdrop_dl.utils import cleanup
-INTERACTIVE: ContextVar[bool] = ContextVar("_INTERACTIVE", default=False)
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
@@ -91,28 +89,11 @@ async def _notify(config: Config, stats_summary: str) -> None:
await apprise.notify(urls, stats_summary)
-def _show_interactive_ui(manager: Manager) -> None:
- if not INTERACTIVE.get():
- return
-
- from cyberdrop_dl import program_ui
-
- program_ui.run(manager)
-
-
def _main(manager: Manager) -> None:
from cyberdrop_dl import aio
- set_console_level(manager.config.logs.effective_console_level)
- manager.appdata.mkdirs()
- with manager():
- _show_interactive_ui(manager)
-
- with setup_file_logging(
- manager.config.logs.files.main,
- level=manager.config.logs.effective_level,
- ):
- aio.run(_scrape(manager))
+ with setup_file_logging(manager.config.logs.files.main, level=manager.config.logs.effective_level):
+ aio.run(_scrape(manager))
def _validate_inputs(args: ArgumentCollection) -> None:
@@ -140,8 +121,11 @@ def interactive(
cli: CLIarguments | None = None,
) -> None:
"Show a TUI menu equivalent to the CLI commands"
- INTERACTIVE.set(True)
- download(input_file=input_file, cli=cli or CLIarguments())
+ with _prepare_manager((), input_file, cli, cli_overrides=None)() as manager:
+ from cyberdrop_dl import program_ui
+
+ program_ui.run(manager)
+ _main(manager)
def download(
@@ -168,6 +152,13 @@ def download(
cli_overrides: Config | None = None,
) -> None:
"Download URLs"
+ with _prepare_manager(urls, input_file, cli, cli_overrides)() as manager:
+ _main(manager)
+
+
+def _prepare_manager(
+ urls: tuple[HttpURL, ...], input_file: Path | None, cli: CLIarguments | None, cli_overrides: Config | None
+) -> Manager:
check_for_v9_files()
if input_file:
input_file = input_file.resolve().absolute()
@@ -177,7 +168,10 @@ def download(
cli = cli or CLIarguments()
cli.urls = urls
appdata, config = _prepare_appdata_and_config(cli, cli_overrides)
- _main(Manager(cli, appdata, config, input_file))
+ manager = Manager(cli, appdata, config, input_file)
+ set_console_level(manager.config.logs.effective_console_level)
+ manager.appdata.mkdirs()
+ return manager
def _prepare_appdata_and_config(cli: CLIarguments, cli_overrides: Config | None = None) -> tuple[AppData, Config]: