Skip to content

Bulk asynchronous downloader for multiple file hosts

fix: rich live

NTFSvolume3f46cb676f1c
diff --git a/cyberdrop_dl/clients/errors.py b/cyberdrop_dl/clients/errors.py
index 1b2e8bfb0..590353bc9 100644
--- a/cyberdrop_dl/clients/errors.py
+++ b/cyberdrop_dl/clients/errors.py
@@ -93,7 +93,7 @@ class InsufficientFreeSpaceError(CDLBaseError):
class RestrictedFiletypeError(CDLBaseError):
def __init__(self, origin: ScrapeItem | URL | None = None) -> None:
- """This error will be thrown when has a filytpe not allowd by config."""
+ """This error will be thrown when has a filytpe not allowed by config."""
ui_message = "Insufficient Free Space"
super().__init__(ui_message, origin=origin)
diff --git a/cyberdrop_dl/clients/hash_client.py b/cyberdrop_dl/clients/hash_client.py
index d8c1cf121..d44f939b9 100644
--- a/cyberdrop_dl/clients/hash_client.py
+++ b/cyberdrop_dl/clients/hash_client.py
@@ -102,11 +102,11 @@ class HashClient:
log(f"After hash processing failed: {media_item.complete_file} with error {e}", 40, exc_info=True)
async def cleanup_dupes(self) -> None:
- with self.manager.live_manager.get_hash_live():
+ with self.manager.live_manager.get_hash_live(stop=True):
if not self.manager.config_manager.global_settings_data["Dupe_Cleanup_Options"]["delete_after_download"]:
return
file_hashes_dict = await self.get_file_hashes_dict()
- async with self.manager.live_manager.get_remove_file_via_hash_live():
+ with self.manager.live_manager.get_remove_file_via_hash_live(stop=True):
final_candiates_dict = self.get_candiate_per_group(file_hashes_dict)
await self.final_dupe_cleanup(final_candiates_dict)
diff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.py
index 86f9cb50b..6a75c2686 100644
--- a/cyberdrop_dl/main.py
+++ b/cyberdrop_dl/main.py
@@ -36,14 +36,22 @@ def startup() -> Manager:
This will also run the UI for the program
After this function returns, the manager will be ready to use and scraping / downloading can begin.
"""
+ try:
+ manager = Manager()
+ manager.startup()
- manager = Manager()
- manager.startup()
+ if not manager.args_manager.immediate_download:
+ program_ui(manager)
- if not manager.args_manager.immediate_download:
- program_ui(manager)
+ return manager
- return manager
+ except InvalidYamlError as e:
+ print_to_console(e.message_rich)
+ exit(1)
+
+ except KeyboardInterrupt:
+ print_to_console("Exiting...")
+ exit(0)
async def runtime(manager: Manager) -> None:
@@ -88,24 +96,24 @@ def setup_debug_logger(manager: Manager) -> Path | None:
logger_debug = logging.getLogger("cyberdrop_dl_debug")
debug_log_file_path = None
running_in_IDE = os.getenv("PYCHARM_HOSTED") or os.getenv("TERM_PROGRAM") == "vscode"
- import cyberdrop_dl.utils.constants as contants
+ from cyberdrop_dl.utils import constants
if running_in_IDE or manager.config_manager.settings_data["Runtime_Options"]["log_level"] == -1:
manager.config_manager.settings_data["Runtime_Options"]["log_level"] = 10
- contants.DEBUG_VAR = True
+ constants.DEBUG_VAR = True
if running_in_IDE or manager.config_manager.settings_data["Runtime_Options"]["console_log_level"] == -1:
- contants.CONSOLE_DEBUG_VAR = True
+ constants.CONSOLE_DEBUG_VAR = True
- if contants.DEBUG_VAR:
+ if constants.DEBUG_VAR:
logger_debug.setLevel(manager.config_manager.settings_data["Runtime_Options"]["log_level"])
debug_log_file_path = Path(__file__).parent / "cyberdrop_dl_debug.log"
if running_in_IDE:
debug_log_file_path = Path(__file__).parents[1] / "cyberdrop_dl_debug.log"
rich_file_handler_debug = RichHandler(
- **contants.RICH_HANDLER_DEBUG_CONFIG,
- console=Console(file=debug_log_file_path.open("w", encoding="utf8"), width=contants.DEFAULT_CONSOLE_WIDTH),
+ **constants.RICH_HANDLER_DEBUG_CONFIG,
+ console=Console(file=debug_log_file_path.open("w", encoding="utf8"), width=constants.DEFAULT_CONSOLE_WIDTH),
level=manager.config_manager.settings_data["Runtime_Options"]["log_level"],
)
@@ -118,7 +126,7 @@ def setup_debug_logger(manager: Manager) -> Path | None:
def setup_logger(manager: Manager, config_name: str) -> None:
- import cyberdrop_dl.utils.constants as contants
+ from cyberdrop_dl.utils import constants
logger = logging.getLogger("cyberdrop_dl")
if manager.args_manager.all_configs:
@@ -133,20 +141,20 @@ def setup_logger(manager: Manager, config_name: str) -> None:
logger.setLevel(manager.config_manager.settings_data["Runtime_Options"]["log_level"])
- if contants.DEBUG_VAR:
+ if constants.DEBUG_VAR:
manager.config_manager.settings_data["Runtime_Options"]["log_level"] = 10
rich_file_handler = RichHandler(
- **contants.RICH_HANDLER_CONFIG,
+ **constants.RICH_HANDLER_CONFIG,
console=Console(
file=manager.path_manager.main_log.open("w", encoding="utf8"),
- width=contants.DEFAULT_CONSOLE_WIDTH,
+ width=constants.DEFAULT_CONSOLE_WIDTH,
),
level=manager.config_manager.settings_data["Runtime_Options"]["log_level"],
)
logger.addHandler(rich_file_handler)
- contants.CONSOLE_LEVEL = manager.config_manager.settings_data["Runtime_Options"]["console_log_level"]
+ constants.CONSOLE_LEVEL = manager.config_manager.settings_data["Runtime_Options"]["console_log_level"]
async def director(manager: Manager) -> None:
@@ -173,9 +181,19 @@ async def director(manager: Manager) -> None:
log_spacer(20)
log("Starting CDL...\n", 20)
- with manager.live_manager.get_main_live(stop=True):
- await runtime(manager)
- await post_runtime(manager)
+ try:
+ with manager.live_manager.get_main_live(stop=True):
+ await runtime(manager)
+ await post_runtime(manager)
+ except Exception as e:
+ log_with_color(
+ f"An error occurred, please report this to the developer: {e}",
+ "bold red",
+ 50,
+ show_in_stats=False,
+ exc_info=True,
+ )
+ sys.exit(1)
log_spacer(20)
manager.progress_manager.print_stats(start_time)
@@ -198,25 +216,18 @@ def main() -> None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
exit_code = 1
+ manager = startup()
with contextlib.suppress(RuntimeError):
try:
- manager = startup()
asyncio.run(director(manager))
exit_code = 0
- except InvalidYamlError as e:
- print_to_console(e.message_rich)
except KeyboardInterrupt:
+ print_to_console("Trying to Exit ...")
with contextlib.suppress(Exception):
- print_to_console("\nTrying to Exit...")
asyncio.run(manager.close())
- except Exception as e:
- log_with_color(
- f"An error occurred, please report this to the developer: {e}",
- "bold red",
- 50,
- show_in_stats=False,
- exc_info=True,
- )
+ exit(1)
+ loop.close()
+ sys.exit(0)
loop.close()
sys.exit(exit_code)
diff --git a/cyberdrop_dl/managers/live_manager.py b/cyberdrop_dl/managers/live_manager.py
index 1b6074a2b..fb825e65a 100644
--- a/cyberdrop_dl/managers/live_manager.py
+++ b/cyberdrop_dl/managers/live_manager.py
@@ -3,10 +3,10 @@ from __future__ import annotations
from contextlib import contextmanager
from typing import TYPE_CHECKING, Generator
-from rich.console import Console
from rich.live import Live
+from rich.progress import Progress, SpinnerColumn, TextColumn
-from cyberdrop_dl.utils.logger import console, log
+from cyberdrop_dl.utils.logger import console
if TYPE_CHECKING:
from rich.layout import Layout
@@ -21,23 +21,30 @@ class LiveManager:
auto_refresh=True,
refresh_per_second=self.manager.config_manager.global_settings_data["UI_Options"]["refresh_rate"],
console=console,
+ transient=True,
)
+ self.placeholder = Progress(
+ SpinnerColumn(style="green", spinner_name="dots"),
+ TextColumn("Running Cyberdrop-DL"),
+ )
+ self.placeholder.add_task("running with no UI", total=100, completed=0)
+
@contextmanager
def get_live(self, layout: Layout, stop: bool = False) -> Generator[Live]:
+ show = self.placeholder if self.manager.args_manager.no_ui else layout
try:
- if self.manager.args_manager.no_ui:
- yield
- else:
- self.live.start()
- self.live.update(layout, refresh=True)
- yield self.live
+ self.live.start()
+ self.live.update(show, refresh=True)
+ yield self.live
+
+ except Exception as e:
+ msg = f"Issue with rich live {e}"
+ raise Exception(msg) from e
+
+ finally:
if stop:
self.live.stop()
- if not self.manager.args_manager.no_ui:
- Console().clear()
- except Exception as e:
- log(f"Issue with rich live {e}", level=10, exc_info=True)
@contextmanager
def get_main_live(self, stop: bool = False) -> Generator[Live]:
diff --git a/cyberdrop_dl/managers/manager.py b/cyberdrop_dl/managers/manager.py
index c98f101c9..d95e3ea0d 100644
--- a/cyberdrop_dl/managers/manager.py
+++ b/cyberdrop_dl/managers/manager.py
@@ -119,13 +119,13 @@ class Manager:
await self.async_db_hash_startup()
# set files from args
- import cyberdrop_dl.utils.constants as constants
+ from cyberdrop_dl.utils import constants
constants.MAX_NAME_LENGTHS["FILE"] = int(
- self.config_manager.global_settings_data["General"]["max_file_name_length"]
+ self.config_manager.global_settings_data["General"]["max_file_name_length"],
)
constants.MAX_NAME_LENGTHS["FOLDER"] = int(
- self.config_manager.global_settings_data["General"]["max_folder_name_length"]
+ self.config_manager.global_settings_data["General"]["max_folder_name_length"],
)
async def async_db_hash_startup(self) -> None:
diff --git a/cyberdrop_dl/utils/sorting.py b/cyberdrop_dl/utils/sorting.py
index c07520ab4..c9ab2d3b1 100644
--- a/cyberdrop_dl/utils/sorting.py
+++ b/cyberdrop_dl/utils/sorting.py
@@ -99,7 +99,7 @@ class Sorter:
log_with_color("Download Directory does not exist", "red", 40)
return
- download_folders = await self.get_download_folder()
+ download_folders: list[Path] = await self.get_download_folder()
with self.manager.live_manager.get_sort_live(stop=True):
all_scan_folders = list(filter(lambda x: x.is_dir(), self.download_dir.iterdir()))
queue_length = len(all_scan_folders)
diff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.py
index 5ddeef1b2..a7bc5970e 100644
--- a/cyberdrop_dl/utils/utilities.py
+++ b/cyberdrop_dl/utils/utilities.py
@@ -231,7 +231,7 @@ def check_latest_pypi(log_to_console: bool = True, call_from_ui: bool = False) -
message = Text.from_markup(message)
else:
message = Text("You are currently on the latest version of Cyberdrop-DL")
- level = 10
+ level = 20
if call_from_ui:
rich.print(message)