Skip to content

Bulk asynchronous downloader for multiple file hosts

fix: `in_place` hashing (#1375)

NTFSvolume83f6fc00d30b
diff --git a/cyberdrop_dl/clients/hash_client.py b/cyberdrop_dl/clients/hash_client.py
index 011b1b30a..59312e86c 100644
--- a/cyberdrop_dl/clients/hash_client.py
+++ b/cyberdrop_dl/clients/hash_client.py
@@ -61,12 +61,14 @@ class HashClient:
async def hash_directory(self, path: Path) -> None:
path = Path(path)
- with self.manager.live_manager.get_hash_live(stop=True):
- self.manager.progress_manager.hash_progress.base_dir = path
+ with (
+ self.manager.live_manager.get_hash_live(stop=True),
+ self.manager.progress_manager.hash_progress.currently_hashing_dir(path),
+ ):
if not await asyncio.to_thread(path.is_dir):
raise NotADirectoryError
for file in path.rglob("*"):
- await self.update_db_and_retrive_hash(file)
+ _ = await self.update_db_and_retrive_hash(file)
async def hash_item(self, media_item: MediaItem) -> None:
if media_item.is_segment:
diff --git a/cyberdrop_dl/managers/config_manager.py b/cyberdrop_dl/managers/config_manager.py
index 15dc04783..d38051aa2 100644
--- a/cyberdrop_dl/managers/config_manager.py
+++ b/cyberdrop_dl/managers/config_manager.py
@@ -217,6 +217,6 @@ def is_in_file(search_value: str, file: Path) -> bool:
if not file.is_file():
return False
try:
- return search_value.casefold() in file.read_text().casefold()
+ return search_value.casefold() in file.read_text(encoding="utf8").casefold()
except Exception as e:
raise InvalidYamlError(file, e) from e
diff --git a/cyberdrop_dl/ui/progress/hash_progress.py b/cyberdrop_dl/ui/progress/hash_progress.py
index d9cd92e1f..252dfe74f 100644
--- a/cyberdrop_dl/ui/progress/hash_progress.py
+++ b/cyberdrop_dl/ui/progress/hash_progress.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import contextlib
from pathlib import Path
from typing import TYPE_CHECKING
@@ -26,7 +27,7 @@ class HashProgress:
self._remove_progress = _generic_progress()
self._match_progress = _generic_progress()
self._file_info = Progress("{task.description}")
- self._base_dir: Path
+ self._base_dir: Path | None = None
# hashing
self._computed_hashes = self._prev_hashed = 0
@@ -57,16 +58,6 @@ class HashProgress:
total=None,
)
- @property
- def base_dir(self) -> Path:
- return self._base_dir
-
- @base_dir.setter
- def base_dir(self, path: Path) -> None:
- self._base_dir = path
- desc = "[green]Base dir: [blue]" + escape(f"{self._base_dir}")
- self._file_info.update(self._base_dir_task_id, description=desc)
-
@property
def hashed_files(self) -> int:
return int(self._computed_hashes / len(self._tasks))
@@ -88,7 +79,20 @@ class HashProgress:
"""Returns the progress bar."""
return Panel(self.removed_progress_group, border_style="green", padding=(1, 1))
+ @contextlib.contextmanager
+ def currently_hashing_dir(self, path: Path):
+ self._base_dir = path
+ desc = "[green]Base dir: [blue]" + escape(f"{self._base_dir}")
+ self._file_info.update(self._base_dir_task_id, description=desc)
+ try:
+ yield
+ finally:
+ self._base_dir = None
+ self._file_info.update(self._base_dir_task_id, description="")
+
def update_currently_hashing(self, file: Path) -> None:
+ if not self._base_dir:
+ return
file_size = ByteSize(Path(file).stat().st_size)
size_text = file_size.human_readable(decimal=True)
path = file.relative_to(self._base_dir)
diff --git a/cyberdrop_dl/utils/logger.py b/cyberdrop_dl/utils/logger.py
index f606b3135..92219ec26 100644
--- a/cyberdrop_dl/utils/logger.py
+++ b/cyberdrop_dl/utils/logger.py
@@ -4,6 +4,7 @@ import contextlib
import json
import logging
import queue
+import sys
from functools import wraps
from logging.handlers import QueueHandler, QueueListener
from pathlib import Path
@@ -236,7 +237,7 @@ def log_with_color(message: Text | str, style: str, level: int = 20, show_in_sta
"""Simple logging function with color."""
text = message if isinstance(message, Text) else Text(message, style=style)
log(text.plain, level, **kwargs)
- if constants.CONSOLE_LEVEL >= 50:
+ if constants.CONSOLE_LEVEL >= 50 and "pytest" not in sys.modules:
_DEFAULT_CONSOLE.print(text)
if show_in_stats:
constants.LOG_OUTPUT_TEXT.append_text(text.append("\n"))
@@ -267,8 +268,9 @@ def _setup_startup_logger() -> Generator[None]:
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)
+ if "pytest" not in sys.modules:
+ console_handler = LogHandler(level=10)
+ startup_logger.addHandler(console_handler)
try:
yield
diff --git a/pyproject.toml b/pyproject.toml
index edb012a66..2fb4c08cd 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -90,11 +90,13 @@ requires-poetry = ">=2.2.0"
addopts = ["-s"]
asyncio_default_fixture_loop_scope = "function"
asyncio_mode = "auto"
+filterwarnings = [
+ "ignore:Proactor event loop does not implement add_reader:UserWarning"
+]
markers = [
"crawler_test_case: tests that do full run with a crawler (making actual network requests)"
]
minversion = "8.4.1"
-testpaths = ["tests"]
[tool.ruff]
exclude = ["cyberdrop_dl/dependencies/_browser_cookie3.py"]
diff --git a/tests/test_cli.py b/tests/test_cli.py
index b095cb4bf..82dd498ab 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -35,10 +35,10 @@ def test_startup_logger_should_not_be_created_on_invalid_cookies(tmp_cwd: Path)
director = _create_director("--download")
cookies_file = director.manager.path_manager.cookies_dir / "cookies.txt"
- cookies_file.write_bytes(b"Not a cookie file")
+ cookies_file.write_text("Not a cookie file", encoding="utf8")
catch_exceptions(director.run)()
- logs = director.manager.path_manager.main_log.read_text()
+ logs = director.manager.path_manager.main_log.read_text(encoding="utf8")
assert "does not look like a Netscape format cookies file" in logs
startup_file = Path.cwd() / "startup.log"
@@ -59,7 +59,7 @@ def test_startup_logger_is_created_on_yaml_error(tmp_cwd: Path) -> None:
startup_file = Path.cwd() / "startup.log"
assert startup_file.exists()
- logs = startup_file.read_text()
+ logs = startup_file.read_text(encoding="utf8")
assert "Unable to read file" in logs
@@ -73,7 +73,7 @@ def test_startup_logger_is_created_on_yaml_error(tmp_cwd: Path) -> None:
],
)
def test_startup_logger_when_manager_startup_fails(
- tmp_cwd: Path, exception: Exception | type[Exception], exists: bool
+ tmp_cwd: Path, exception: Exception | type[Exception], exists: bool, capsys: pytest.CaptureFixture[str]
) -> None:
with mock.patch("cyberdrop_dl.managers.manager.Manager.set_constants", side_effect=exception):
try:
diff --git a/tests/test_startup.py b/tests/test_startup.py
index 1470379b2..ec04f2945 100644
--- a/tests/test_startup.py
+++ b/tests/test_startup.py
@@ -20,8 +20,7 @@ def test_startup(tmp_cwd: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.
assert msg in output
-def test_async_startup(tmp_cwd: Path, capsys: pytest.CaptureFixture[str]) -> None:
+def test_async_startup(tmp_cwd: Path, caplog: pytest.LogCaptureFixture) -> None:
+ caplog.set_level(10)
run(("--download",))
- captured = capsys.readouterr()
- output = captured.out
- assert "Finished downloading. Enjoy :)" in output
+ assert "Finished downloading. Enjoy :)" in caplog.text