Skip to content

Bulk asynchronous downloader for multiple file hosts

feat: add hash subcommand (#1984)

NTFSvolume06283d2f9d15
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 838d859cd..c2b002193 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -36,11 +36,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- New `--hashes` option to control which hashes CDL computes for new downloads
- New `--database-file` option
- New `--cache-file` option
+- New `hash` subcommand
+- New `report` subcommand
### Changed
-- The config file format has completely changed. All configs (`Auth`, `Global` and `Setttings`) are now a single file. Several options have new names, new defaults and new groups
-- A default config file will not be created by default. You can manually create a default one from the `Edit config` option on the main menu
+- The config file format has changed. All configs (`Auth`, `Global` and `Setttings`) are now a single file. Several options have new names, new defaults and new groups
+- A default config file will noo longer be created. You can manually create a default one from the `Edit config` option on the main menu
- Validate config in strict mode. If a config has an unknown entry, CDL will refuse to run instead of ignoring it
- Apprise URLs are now part of the main config file instead of a dedicated `apprise.txt` file
- Refuse to start if the current database schema is older than `v9.15.0`
diff --git a/cyberdrop_dl/cli/__init__.py b/cyberdrop_dl/cli/__init__.py
index 3e8c35746..ed3b9177f 100644
--- a/cyberdrop_dl/cli/__init__.py
+++ b/cyberdrop_dl/cli/__init__.py
@@ -40,6 +40,7 @@ def register_commands() -> None:
from cyberdrop_dl.cli.clean_up import app as cleanup
from cyberdrop_dl.cli.database import app as database
from cyberdrop_dl.cli.download import download
+ from cyberdrop_dl.cli.hash import compute_hashes
from cyberdrop_dl.cli.report import report
from cyberdrop_dl.cli.show import show
@@ -48,6 +49,7 @@ def register_commands() -> None:
app.command(show)
app.command(cleanup)
app.command(report)
+ app.command(compute_hashes, name="hash")
register_commands()
diff --git a/cyberdrop_dl/cli/download.py b/cyberdrop_dl/cli/download.py
index ee296ef59..a96edaecb 100644
--- a/cyberdrop_dl/cli/download.py
+++ b/cyberdrop_dl/cli/download.py
@@ -67,7 +67,7 @@ async def _post_runtime(manager: Manager) -> None:
and manager.config.hashing.dedupe.enabled
and not manager.config.ignore_history
):
- file_hashes = await manager.hasher.run()
+ file_hashes = await manager.hasher.run(manager.completed_downloads)
await manager.deduper.run(file_hashes)
if manager.config.sort.enabled:
diff --git a/cyberdrop_dl/cli/hash.py b/cyberdrop_dl/cli/hash.py
new file mode 100644
index 000000000..f2c4c910f
--- /dev/null
+++ b/cyberdrop_dl/cli/hash.py
@@ -0,0 +1,26 @@
+from typing import Literal
+
+from cyclopts.types import ExistingDirectory, ExistingFile
+
+
+async def compute_hashes(
+ folder: ExistingDirectory,
+ /,
+ *,
+ database_file: ExistingFile | None = None,
+ hashes: tuple[Literal["xxh128", "md5", "sha256"], ...] = ("xxh128", "md5", "sha256"),
+) -> None:
+ """Compute and save hashes of every file inside `folder` (recursively)"""
+
+ from cyberdrop_dl import stats
+ from cyberdrop_dl.config.appdata import AppData
+ from cyberdrop_dl.database import Database
+ from cyberdrop_dl.hasher import Hasher, hash_directory
+
+ folder = folder.expanduser().resolve().absolute()
+ database = Database(database_file or AppData.default().db_file)
+ extra_hashes = set(hashes)
+ extra_hashes.discard("xxh128")
+ hasher = Hasher(tuple(extra_hashes), database, folder) # pyright: ignore[reportArgumentType]
+ hash_stats = await hash_directory(hasher)
+ stats.print(hash_stats)
diff --git a/cyberdrop_dl/clients/downloads.py b/cyberdrop_dl/clients/downloads.py
index e80609cc0..9590c74e6 100644
--- a/cyberdrop_dl/clients/downloads.py
+++ b/cyberdrop_dl/clients/downloads.py
@@ -11,8 +11,9 @@ from aiohttp import hdrs
from cyberdrop_dl import aio, constants, ffmpeg, storage
from cyberdrop_dl.clients import etag
-from cyberdrop_dl.constants import FileExt
+from cyberdrop_dl.constants import FileExt, HashMode
from cyberdrop_dl.exceptions import DownloadError, InvalidContentTypeError, SlowDownloadError
+from cyberdrop_dl.hasher import compute_in_place_hash
from cyberdrop_dl.utils import dates
if TYPE_CHECKING:
@@ -247,12 +248,15 @@ class DownloadClient:
async def handle_media_item_completion(self, media_item: MediaItem, *, downloaded: bool = False) -> None:
"""Sends to hash client to handle hashing and marks as completed/current download."""
+ media_item.downloaded = downloaded
try:
- media_item.downloaded = downloaded
- await self.manager.hasher.hash_item_during_download(media_item)
- self.manager.add_completed(media_item)
+ if media_item.is_segment or self.manager.config.hashing.mode != HashMode.IN_PLACE:
+ return
+ await compute_in_place_hash(self.manager.hasher, media_item)
except Exception:
- logger.exception(f"Error handling media item completion of: {media_item.path}")
+ logger.exception(f"Unable to compute hashes of: {media_item.path}")
+ finally:
+ self.manager.add_completed(media_item)
def get_download_dir(self, media_item: MediaItem) -> Path:
"""Returns the download directory for the media item."""
diff --git a/cyberdrop_dl/hasher.py b/cyberdrop_dl/hasher.py
index 5ea63370a..bf470651e 100644
--- a/cyberdrop_dl/hasher.py
+++ b/cyberdrop_dl/hasher.py
@@ -6,16 +6,19 @@ import hashlib
import logging
from collections import defaultdict
from pathlib import Path
-from typing import TYPE_CHECKING, Final, Literal
+from typing import TYPE_CHECKING, Final, Literal, Self
import xxhash
-from cyberdrop_dl import aio, stats
-from cyberdrop_dl.constants import HashMode, TempExt
+from cyberdrop_dl import aio
+from cyberdrop_dl.constants import TempExt
from cyberdrop_dl.progress.hashing import HashingStats, HashingUI
if TYPE_CHECKING:
- from cyberdrop_dl.manager import Manager
+ from collections.abc import Iterable
+
+ from cyberdrop_dl.config import Config
+ from cyberdrop_dl.database._db import Database
from cyberdrop_dl.url_objects import AbsoluteHttpURL, MediaItem
FileHashes = dict[str, dict[int, set[Path]]]
@@ -42,51 +45,57 @@ def _compute_hash(file: Path, algorithm: Literal["xxh128", "md5", "sha256"]) ->
return hasher.hexdigest()
-async def hash_directory_scanner(manager: Manager, path: Path) -> None:
- async with manager.database:
- hash_stats = await hash_directory(manager, path)
-
- stats.print(hash_stats)
-
-
-async def hash_directory(manager: Manager, path: Path) -> HashingStats:
- hasher = Hasher(manager)
- hasher._tui = tui = HashingUI(path)
- with tui():
- if not await aio.is_dir(path):
- raise NotADirectoryError(None, path)
+async def hash_directory(hasher: Hasher) -> HashingStats:
+ if not await aio.is_dir(hasher.path):
+ raise NotADirectoryError(None, hasher.path)
- async with asyncio.TaskGroup() as tg:
- async for file in aio.rglob(path, "*"):
- _ = tg.create_task(hasher.update_db_and_retrive_hash(file))
+ async with hasher.database:
+ with hasher.tui():
+ async with asyncio.TaskGroup() as tg:
+ async for file in aio.rglob(hasher.path, "*"):
+ _ = tg.create_task(hasher.update_db_and_retrive_hash(file))
- return tui.stats
+ return hasher.stats
@dataclasses.dataclass(slots=True)
class Hasher:
- manager: Manager
- hashed_media_items: list[MediaItem] = dataclasses.field(init=False, repr=False, default_factory=list)
- hashes_dict: FileHashes = dataclasses.field(
+ extra_hashes: tuple[Literal["md5", "sha256"], ...]
+ database: Database
+ path: Path
+ tui: HashingUI = dataclasses.field(init=False, repr=False)
+
+ _cwd: Path = dataclasses.field(init=False, default_factory=Path.cwd)
+ _hashes_map: FileHashes = dataclasses.field(
init=False,
repr=False,
default_factory=lambda: defaultdict(lambda: defaultdict(set)),
)
- _sem: asyncio.BoundedSemaphore = dataclasses.field(init=False, default_factory=lambda: asyncio.BoundedSemaphore(20))
- _cwd: Path = dataclasses.field(init=False, default_factory=Path.cwd)
- _hashed_items: set[tuple[str, ...]] = dataclasses.field(default_factory=set, repr=False)
- _tui: HashingUI = dataclasses.field(init=False)
+ _sem: asyncio.BoundedSemaphore = dataclasses.field(
+ init=False,
+ repr=False,
+ default_factory=lambda: asyncio.BoundedSemaphore(20),
+ )
+ _hashed_items: set[tuple[str, ...]] = dataclasses.field(
+ init=False,
+ repr=False,
+ default_factory=set,
+ )
def __post_init__(self) -> None:
- self._tui = HashingUI(self.download_folder)
-
- @property
- def download_folder(self) -> Path:
- return self.manager.config.download_folder.expanduser().resolve().absolute()
+ self.tui = HashingUI(self.path)
+
+ @classmethod
+ def create(cls, config: Config, db: Database, path: Path | None = None) -> Self:
+ return cls(
+ config.hashing.extra_hashes,
+ db,
+ path=(path or config.download_folder).expanduser().resolve().absolute(),
+ )
@property
- def stats(self):
- return self._tui.stats
+ def stats(self) -> HashingStats:
+ return self.tui.stats
async def hash_file(self, filename: Path | str, hash_type: Literal["xxh128", "md5", "sha256"]) -> str:
file_path = self._cwd / filename
@@ -102,22 +111,6 @@ class Hasher:
)
await self.save_hash_data(media_item, hash_value)
- async def hash_item_during_download(self, media_item: MediaItem) -> None:
- if media_item.is_segment:
- return
-
- if self.manager.config.hashing.mode != HashMode.IN_PLACE:
- return
-
- try:
- assert media_item.original_filename
- hash_value = await self.update_db_and_retrive_hash(
- media_item.path, media_item.original_filename, media_item.referer
- )
- await self.save_hash_data(media_item, hash_value)
- except Exception:
- logger.exception("After hash processing failed: '%s'", media_item.path)
-
async def update_db_and_retrive_hash(
self,
file: Path | str,
@@ -139,11 +132,11 @@ class Hasher:
return tg.create_task(self._update_db_and_retrive_hash(file, original_filename, referer, algo))
async with self._sem:
- with self._tui.new_file(file):
+ with self.tui.new_file(file):
async with asyncio.TaskGroup() as tg:
logger.info("Computing hashes of '%s'", file)
xxxhash = compute_hash("xxh128")
- for algo in self.manager.config.hashing.extra_hashes:
+ for algo in self.extra_hashes:
_ = compute_hash(algo)
return xxxhash.result()
@@ -157,21 +150,21 @@ class Hasher:
) -> str | None:
"""Generates hash of a file."""
- hash_value = await self.manager.database.hash.get_file_hash_exists(file, hash_type)
+ hash_value = await self.database.hash.get_file_hash_exists(file, hash_type)
try:
if not hash_value:
hash_value = await self.hash_file(file, hash_type)
- await self.manager.database.hash.insert_or_update_hash_db(
+ await self.database.hash.insert_or_update_hash_db(
hash_value,
hash_type,
file,
original_filename,
referer,
)
- self._tui.add_completed(hash_type)
+ self.tui.add_completed(hash_type)
else:
- self._tui.stats.prev_hashed += 1
- await self.manager.database.hash.insert_or_update_hash_db(
+ self.tui.stats.prev_hashed += 1
+ await self.database.hash.insert_or_update_hash_db(
hash_value,
hash_type,
file,
@@ -190,25 +183,18 @@ class Hasher:
absolute_path = await aio.resolve(media_item.path)
size = await aio.get_size(media_item.path)
assert size
- self.hashed_media_items.append(media_item)
if hash_value:
media_item.xxhash = hash_value
- self.hashes_dict[hash_value][size].add(absolute_path)
+ self._hashes_map[hash_value][size].add(absolute_path)
self._hashed_items.add(media_item.id)
- async def run(self) -> FileHashes:
- with self._tui():
- return await self._get_file_hashes_dict()
+ async def run(self, downloads: Iterable[MediaItem]) -> FileHashes:
+ with self.tui():
+ return await self._get_file_hashes_dict(downloads)
- async def _get_file_hashes_dict(self) -> FileHashes:
+ async def _get_file_hashes_dict(self, downloads: Iterable[MediaItem]) -> FileHashes:
- async def exists(item: MediaItem) -> MediaItem | None:
- if await aio.is_file(item.path):
- return item
-
- results = await aio.gather(
- *(exists(item) for item in self.manager.completed_downloads if item.id not in self._hashed_items)
- )
+ results = await aio.gather(*(_exists(item) for item in downloads if item.id not in self._hashed_items))
for media_item in results:
if media_item is None:
continue
@@ -216,4 +202,20 @@ class Hasher:
await self.hash_item(media_item)
except Exception:
logger.exception(msg=f"Unable to hash '{media_item.path}'")
- return self.hashes_dict
+ return self._hashes_map
+
+
+async def _exists(item: MediaItem) -> MediaItem | None:
+ if await aio.is_file(item.path):
+ return item
+
+
+async def compute_in_place_hash(hasher: Hasher, media_item: MediaItem) -> None:
+ try:
+ assert media_item.original_filename
+ hash_value = await hasher.update_db_and_retrive_hash(
+ media_item.path, media_item.original_filename, media_item.referer
+ )
+ await hasher.save_hash_data(media_item, hash_value)
+ except Exception:
+ logger.exception("After hash processing failed: '%s'", media_item.path)
diff --git a/cyberdrop_dl/manager.py b/cyberdrop_dl/manager.py
index 0afdce890..42a3d9764 100644
--- a/cyberdrop_dl/manager.py
+++ b/cyberdrop_dl/manager.py
@@ -55,7 +55,7 @@ class Manager:
self._input_file: Path | None = input_file
self._completed_downloads: list[MediaItem] = []
- self.hasher: Hasher = Hasher(self)
+ self._hasher: Hasher | None = None
self.logs: CSVLogsManager = CSVLogsManager.from_config(self.config)
self.http_client: HTTPClient = HTTPClient.from_manager(self)
self.download_client: DownloadClient = DownloadClient(self)
@@ -65,6 +65,12 @@ class Manager:
self.deduper: Czkawka
self.sorter: Sorter
+ @property
+ def hasher(self) -> Hasher:
+ if self._hasher is None:
+ self._hasher = Hasher.create(self.config, self.database)
+ return self._hasher
+
@property
def input_file(self) -> Path:
if self._input_file is None:
diff --git a/cyberdrop_dl/program_ui.py b/cyberdrop_dl/program_ui.py
index 2e7d6f145..b07531184 100644
--- a/cyberdrop_dl/program_ui.py
+++ b/cyberdrop_dl/program_ui.py
@@ -14,8 +14,8 @@ from rich.console import Console
from rich.markdown import Markdown
from rich.text import Text
-from cyberdrop_dl import __version__
-from cyberdrop_dl.hasher import hash_directory_scanner
+from cyberdrop_dl import __version__, stats
+from cyberdrop_dl.hasher import Hasher, hash_directory
from cyberdrop_dl.progress import hyperlink
from cyberdrop_dl.sorter import Sorter
from cyberdrop_dl.utils import text_editor
@@ -65,7 +65,9 @@ def _scan_and_create_hashes(manager: Manager) -> None:
"Select the directory to scan",
default=manager.config.download_folder,
)
- asyncio.run(hash_directory_scanner(manager, path))
+ hasher = Hasher.create(manager.config, manager.database, path)
+ hash_stats = asyncio.run(hash_directory(hasher))
+ stats.print(hash_stats)
_enter_to_continue()
diff --git a/tests/test_hashing.py b/tests/test_hashing.py
index 951fd1e97..8ec37f250 100644
--- a/tests/test_hashing.py
+++ b/tests/test_hashing.py
@@ -3,11 +3,11 @@ from __future__ import annotations
import sqlite3
from collections import Counter
from pathlib import Path
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Literal
import pytest
-from cyberdrop_dl.hasher import hash_directory_scanner
+from cyberdrop_dl.hasher import Hasher, _compute_hash, hash_directory
if TYPE_CHECKING:
from cyberdrop_dl.manager import Manager
@@ -59,10 +59,10 @@ async def test_hash_directory_scanner(manager: Manager, expected_results: set[tu
manager.config.download_folder.mkdir(parents=True)
db_path = manager.appdata.db_file
- await hash_directory_scanner(manager, manager.config.download_folder)
+ await hash_directory(Hasher.create(manager.config, manager.database))
assert not get_hashes(db_path)
create_files(manager.config.download_folder, n_files)
- await hash_directory_scanner(manager, manager.config.download_folder)
+ await hash_directory(Hasher.create(manager.config, manager.database))
results = get_hashes(db_path)
assert len(results) == len(expected_results)
assert results == expected_results
@@ -79,4 +79,20 @@ async def test_hash_directory_does_not_crash_with_subfolders(tmp_cwd: Path, mana
for file in files:
file.parent.mkdir(parents=True, exist_ok=True)
file.touch()
- await hash_directory_scanner(manager, hash_folder)
+ await hash_directory(Hasher.create(manager.config, manager.database, hash_folder))
+
+
+ ("algo", "expected"),
+ [
+ ("xxh128", "ae6ea5d955361e9dd7d91f1432616dcc"),
+ ("md5", "1ebbd3e34237af26da5dc08a4e440464"),
+ ("sha256", "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986"),
+ ],
+)
+def test_compute_hash(tmp_cwd: Path, algo: Literal["xxh128", "md5", "sha256"], expected: str) -> None:
+ license_file = Path(__file__).parent.parent / "LICENSE"
+ file = tmp_cwd / "license"
+ file.write_bytes(license_file.read_text("utf8").encode()) # Remove windows EOL
+ result = _compute_hash(file, algo)
+ assert result == expected