Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: panic if config requires ffmpeg but it's not installed (#1935)

NTFSvolume7c504863fd0f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 770ce51b0..8082811b3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
+- Hard fail if any config option requires `ffmpeg` but `ffmpeg` is not installed
+
### Deprecated
### Removed
diff --git a/cyberdrop_dl/__main__.py b/cyberdrop_dl/__main__.py
index 5b12b773b..440a92f51 100644
--- a/cyberdrop_dl/__main__.py
+++ b/cyberdrop_dl/__main__.py
@@ -3,17 +3,34 @@ from __future__ import annotations
import sys
from typing import TYPE_CHECKING
-from cyclopts import CycloptsPanel
-
from cyberdrop_dl import tracebacks
from cyberdrop_dl.cli import app
+from cyberdrop_dl.exceptions import CDLConfigRuntimeErrorsGroup
if TYPE_CHECKING:
from collections.abc import Sequence
+ from rich.console import RenderableType
+ from rich.panel import Panel
+
tracebacks.install_exception_hook()
+def _error_panel(message: RenderableType, title: str = "Error") -> Panel:
+ # Based on the default cyclopts panel
+ from rich import box
+ from rich.panel import Panel
+
+ return Panel(
+ message,
+ title=title,
+ box=box.ROUNDED,
+ border_style="red",
+ expand=True,
+ title_align="left",
+ )
+
+
def run_cdl(args: Sequence[str] | None = None) -> int:
from cyberdrop_dl.logs import setup_console_logging
@@ -21,9 +38,9 @@ def run_cdl(args: Sequence[str] | None = None) -> int:
try:
app(args)
- except* ValueError as exc_group:
- msg = "\n" + "\n".join(map(str, exc_group.exceptions))
- app.console.print(CycloptsPanel(msg, title=exc_group.message))
+ except CDLConfigRuntimeErrorsGroup as exc_group:
+ tb = tracebacks.from_exception(exc_group, chain_traceback=False)
+ app.console.print(_error_panel(tb, title="Invalid Config"))
else:
return 0
diff --git a/cyberdrop_dl/cli/download.py b/cyberdrop_dl/cli/download.py
index 3013a651b..969734109 100644
--- a/cyberdrop_dl/cli/download.py
+++ b/cyberdrop_dl/cli/download.py
@@ -7,6 +7,7 @@ from cyclopts import Parameter
from cyberdrop_dl.cli import CLIargs
from cyberdrop_dl.config import Config
+from cyberdrop_dl.exceptions import CDLConfigRuntimeErrorsGroup
from cyberdrop_dl.logs import log_spacer, set_console_level, setup_file_logging
from cyberdrop_dl.models.types import HttpURL # noqa: TC001
@@ -17,7 +18,7 @@ if TYPE_CHECKING:
async def _scrape(manager: Manager) -> None:
- from cyberdrop_dl import webhook
+ from cyberdrop_dl import ffmpeg, webhook
from cyberdrop_dl.scrape_mapper import ScrapeMapper
from cyberdrop_dl.updates import check_latest_pypi
from cyberdrop_dl.utils import apprise
@@ -27,6 +28,9 @@ async def _scrape(manager: Manager) -> None:
level=manager.config.settings.runtime_options.effective_log_level,
):
manager.log_config_settings()
+ if not ffmpeg.is_installed():
+ _check_ffmpeg(manager.config)
+
log_spacer()
async with manager.database:
log_spacer()
@@ -118,3 +122,19 @@ def download(
manager = Manager(cli, appdata, config)
_main(manager)
+
+
+def _check_ffmpeg(config: Config) -> None:
+ errors: list[Exception] = []
+ if config.settings.sorting.needs_ffmpeg:
+ exc = RuntimeError("Sorting media files requires 'ffmpeg' to be installed")
+ exc.add_note("Disable sorting or install ffmpeg")
+ errors.append(exc)
+
+ if config.settings.media_duration_limits.needs_ffmpeg:
+ exc = RuntimeError("Filtering files by duration requires 'ffmpeg' to be installed")
+ exc.add_note("Disable media duration limits or install ffmpeg")
+ errors.append(exc)
+
+ if errors:
+ raise CDLConfigRuntimeErrorsGroup("Some config options are impossible to fulfill", errors)
diff --git a/cyberdrop_dl/config/settings.py b/cyberdrop_dl/config/settings.py
index 3e4f17c3a..9709c0d7f 100644
--- a/cyberdrop_dl/config/settings.py
+++ b/cyberdrop_dl/config/settings.py
@@ -224,6 +224,15 @@ class MediaDurationLimits(SettingsGroup):
return timedelta(seconds=0)
return to_timedelta(input_date)
+ @property
+ def needs_ffmpeg(self) -> bool:
+ return bool(
+ self.minimum_video_duration
+ or self.maximum_video_duration
+ or self.minimum_audio_duration
+ or self.maximum_audio_duration
+ )
+
@cached_property
def ranges(self) -> MediaDurationRanges:
return MediaDurationRanges(
@@ -321,6 +330,10 @@ class Sorting(SettingsGroup):
sorted_other: NonEmptyStrOrNone = "{sort_dir}/{base_dir}/Other/{filename}{ext}"
sorted_video: NonEmptyStrOrNone = "{sort_dir}/{base_dir}/Videos/{filename}{ext}"
+ @property
+ def needs_ffmpeg(self) -> bool:
+ return bool(self.sort_downloads and (self.sorted_audio or self.sorted_image or self.sorted_video))
+
@field_validator("sort_incrementer_format", mode="after")
@classmethod
def valid_sort_incrementer_format(cls, value: str | None) -> str | None:
diff --git a/cyberdrop_dl/exceptions.py b/cyberdrop_dl/exceptions.py
index e74d0c3a2..097307810 100644
--- a/cyberdrop_dl/exceptions.py
+++ b/cyberdrop_dl/exceptions.py
@@ -286,3 +286,6 @@ class ErrorLogMessage:
ui_failure = create_error_msg(e_status) if e_status else "Unknown"
log_msg = _format_error(ui_failure, e_message or str(e))
return ErrorLogMessage(ui_failure, log_msg)
+
+
+class CDLConfigRuntimeErrorsGroup(ExceptionGroup): ...
diff --git a/cyberdrop_dl/logs.py b/cyberdrop_dl/logs.py
index 0e926590d..e7872b6cb 100644
--- a/cyberdrop_dl/logs.py
+++ b/cyberdrop_dl/logs.py
@@ -20,6 +20,7 @@ from rich.text import Text, TextType
from typing_extensions import override
from cyberdrop_dl import env
+from cyberdrop_dl.exceptions import CDLConfigRuntimeErrorsGroup
from cyberdrop_dl.utils import dates
if TYPE_CHECKING:
@@ -351,6 +352,10 @@ def setup_file_logging(file: Path, /, *, level: int = logging.DEBUG) -> Generato
logger.info(f"Debug log file: {debug_log_file}")
try:
yield
+ except CDLConfigRuntimeErrorsGroup as e:
+ with _enter_context(_LOG_TO_CONSOLE, False):
+ logger.critical("Unrecoverable error", exc_info=e.with_traceback(None))
+ raise
except Exception:
with _enter_context(_LOG_TO_CONSOLE, False):
logger.critical("Unrecoverable error", exc_info=True)
diff --git a/cyberdrop_dl/tracebacks.py b/cyberdrop_dl/tracebacks.py
index 464f4f21f..e24b7ce97 100644
--- a/cyberdrop_dl/tracebacks.py
+++ b/cyberdrop_dl/tracebacks.py
@@ -6,6 +6,7 @@ if TYPE_CHECKING:
from collections.abc import Callable
from rich.pretty import Node
+ from rich.traceback import Traceback
_original_traverse = None
@@ -58,3 +59,9 @@ def install_exception_hook(*, show_locals: bool = False) -> None:
max_frames=30,
show_locals=show_locals,
)
+
+
+def from_exception(exc: Exception, *, chain_traceback: bool = True) -> Traceback:
+ from rich.traceback import Traceback
+
+ return Traceback.from_exception(type(exc), exc, None if not chain_traceback else exc.__traceback__)
diff --git a/cyberdrop_dl/utils/apprise.py b/cyberdrop_dl/utils/apprise.py
index 5c2a9b4df..5224c6a37 100644
--- a/cyberdrop_dl/utils/apprise.py
+++ b/cyberdrop_dl/utils/apprise.py
@@ -11,6 +11,7 @@ from typing import TYPE_CHECKING
from pydantic import ValidationError
from cyberdrop_dl import aio
+from cyberdrop_dl.exceptions import CDLConfigRuntimeErrorsGroup
from cyberdrop_dl.logs import MAIN_LOG_FILE, borrow_logger, export_logs, log_spacer
from cyberdrop_dl.models import AppriseURL
@@ -64,7 +65,7 @@ def _parse_apprise_url(*urls: str) -> tuple[AppriseURL, ...]:
errors.append(ValueError(f"Not a valid apprise URL: {e.errors(include_url=False)[0]['input']}"))
if errors:
- raise BaseExceptionGroup("Invalid Apprise file", errors)
+ raise CDLConfigRuntimeErrorsGroup("Invalid Apprise file", errors)
return tuple(models)
diff --git a/tests/test_config.py b/tests/test_config.py
index 73bd5e09c..1ef7f256c 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -5,8 +5,10 @@ import time
import pytest
from cyclopts.exceptions import UnknownOptionError
+import cyberdrop_dl.cli.download
from cyberdrop_dl.config import Config, settings
from cyberdrop_dl.config.merge import merge_dicts
+from cyberdrop_dl.exceptions import CDLConfigRuntimeErrorsGroup
def test_config_equality() -> None:
@@ -148,3 +150,21 @@ class TestRuntimeLogsConfig:
config = self.parse(a, b)
assert config.effective_log_level == a
assert config.effective_console_log_level == a
+
+
+def test_default_config_does_not_need_ffmpeg() -> None:
+ cyberdrop_dl.cli.download._check_ffmpeg(Config())
+
+
+def test_media_durations_need_ffmpeg() -> None:
+ config = Config.parse_args(["--maximum-video-duration", "20 seconds"])
+ duration = config.settings.media_duration_limits.maximum_video_duration
+ assert duration
+ assert duration.total_seconds() == 20
+ assert config.settings.media_duration_limits.needs_ffmpeg
+ with pytest.raises(CDLConfigRuntimeErrorsGroup) as exc:
+ cyberdrop_dl.cli.download._check_ffmpeg(config)
+
+ assert len(exc.value.exceptions) == 1
+ assert type(exc.value.exceptions[0]) is RuntimeError
+ assert str(exc.value.exceptions[0]) == "Filtering files by duration requires 'ffmpeg' to be installed"