Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: remove hash manager (#114)

NTFSvolume91865d0e9c98
diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.py
index 3748c4373..8c030d7ad 100644
--- a/cyberdrop_dl/clients/download_client.py
+++ b/cyberdrop_dl/clients/download_client.py
@@ -336,7 +336,7 @@ class DownloadClient:
"""Sends to hash client to handle hashing and marks as completed/current download."""
try:
media_item.downloaded = downloaded
- await self.manager.hash_manager.hash_client.hash_item_during_download(media_item)
+ await self.manager.hasher.hash_item_during_download(media_item)
self.manager.add_completed(media_item)
except Exception:
logger.exception(f"Error handling media item completion of: {media_item.path}")
diff --git a/cyberdrop_dl/clients/hash_client.py b/cyberdrop_dl/clients/hash_client.py
index 10c421fc6..e69de29bb 100644
--- a/cyberdrop_dl/clients/hash_client.py
+++ b/cyberdrop_dl/clients/hash_client.py
@@ -1,241 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import logging
-from collections import defaultdict
-from pathlib import Path
-from typing import TYPE_CHECKING, Literal
-
-from send2trash import send2trash
-
-from cyberdrop_dl import aio, constants
-from cyberdrop_dl.constants import Hashing
-
-if TYPE_CHECKING:
- from yarl import URL
-
- from cyberdrop_dl.config.config_model import DupeCleanup
- from cyberdrop_dl.data_structures.url_objects import MediaItem
- from cyberdrop_dl.managers.manager import Manager
-
-logger = logging.getLogger(__name__)
-
-
-async def hash_directory_scanner(manager: Manager, path: Path) -> None:
- manager.async_db_hash_startup()
- async with manager.database:
- await manager.hash_manager.hash_client.hash_directory(path)
- manager.progress_manager.print_dedupe_stats()
- manager.progress_manager.hash_progress.reset()
-
-
-class HashClient:
- """Manage hashes and db insertion."""
-
- def __init__(self, manager: Manager) -> None:
- self.manager = manager
- self.xxhash = "xxh128"
- self.md5 = "md5"
- self.sha256 = "sha256"
- self.hashed_media_items: list[MediaItem] = []
- self.hashes_dict: defaultdict[str, defaultdict[int, set[Path]]] = defaultdict(lambda: defaultdict(set))
- self._sem = asyncio.BoundedSemaphore(20)
-
- @property
- def _to_trash(self) -> bool:
- return self.dupe_cleanup_options.send_deleted_to_trash
-
- @property
- def _deleted_file_suffix(self) -> Literal["Sent to trash", "Permanently deleted"]:
- return "Sent to trash" if self._to_trash else "Permanently deleted"
-
- @property
- def dupe_cleanup_options(self) -> DupeCleanup:
- return self.manager.config.dupe_cleanup_options
-
- 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.currently_hashing_dir(path),
- ):
- if not await aio.is_dir(path):
- raise NotADirectoryError
- async for file in aio.rglob(path, "*"):
- _ = await self.update_db_and_retrive_hash(file)
-
- async def hash_item(self, media_item: MediaItem) -> None:
- if media_item.is_segment:
- return
- hash = 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)
-
- async def hash_item_during_download(self, media_item: MediaItem) -> None:
- if media_item.is_segment:
- return
- if self.manager.config_manager.settings_data.dupe_cleanup_options.hashing != Hashing.IN_PLACE:
- return
-
- try:
- assert media_item.original_filename
- hash = 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)
- except Exception as e:
- logger.exception(f"After hash processing failed: '{media_item.path}' with error {e}")
-
- async def update_db_and_retrive_hash(
- self, file: Path | str, original_filename: str | None = None, referer: URL | None = None
- ) -> str | None:
- file = Path(file)
-
- if file.suffix in constants.TempExt:
- return
-
- if not await aio.get_size(file):
- return
-
- hash = await self._update_db_and_retrive_hash_helper(file, original_filename, referer, hash_type=self.xxhash)
- if self.manager.config_manager.settings_data.dupe_cleanup_options.add_md5_hash:
- await self._update_db_and_retrive_hash_helper(file, original_filename, referer, hash_type=self.md5)
- if self.manager.config_manager.settings_data.dupe_cleanup_options.add_sha256_hash:
- await self._update_db_and_retrive_hash_helper(file, original_filename, referer, hash_type=self.sha256)
- return hash
-
- async def _update_db_and_retrive_hash_helper(
- self,
- file: Path | str,
- original_filename: str | None,
- referer: URL | None,
- hash_type: str,
- ) -> str | None:
- """Generates hash of a file."""
- self.manager.progress_manager.hash_progress.update_currently_hashing(file)
- hash = await self.manager.database.hash.get_file_hash_exists(file, hash_type)
- try:
- if not hash:
- hash = await self.manager.hash_manager.hash_file(file, hash_type)
- await self.manager.database.hash.insert_or_update_hash_db(
- hash,
- hash_type,
- file,
- original_filename,
- referer,
- )
- self.manager.progress_manager.hash_progress.add_new_completed_hash(hash_type)
- else:
- self.manager.progress_manager.hash_progress.add_prev_hash()
- await self.manager.database.hash.insert_or_update_hash_db(
- hash,
- hash_type,
- file,
- original_filename,
- referer,
- )
- except Exception as e:
- logger.exception(f"Error hashing '{file}' : {e}")
- else:
- return hash
-
- async def save_hash_data(self, media_item: MediaItem, hash: str | None) -> None:
- if not hash:
- return
- 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:
- media_item.hash = hash
- self.hashes_dict[hash][size].add(absolute_path)
-
- async def cleanup_dupes_after_download(self) -> None:
- if self.manager.config_manager.settings_data.dupe_cleanup_options.hashing == Hashing.OFF:
- return
- if not self.manager.config_manager.settings_data.dupe_cleanup_options.auto_dedupe:
- return
- if self.manager.config_manager.settings_data.runtime_options.ignore_history:
- return
- with self.manager.live_manager.get_hash_live(stop=True):
- file_hashes_dict = await self.get_file_hashes_dict()
- with self.manager.live_manager.get_remove_file_via_hash_live(stop=True):
- await self.final_dupe_cleanup(file_hashes_dict)
-
- async def final_dupe_cleanup(self, final_dict: dict[str, dict]) -> None:
- """cleanup files based on dedupe setting"""
-
- get_matches = self.manager.database.hash.get_files_with_hash_matches
- async with asyncio.TaskGroup() as tg:
-
- async def delete_dupes(hash_value: str, size: int) -> None:
- db_matches = await get_matches(hash_value, size, "xxh128")
- for row in db_matches[1:]:
- file = Path(row["folder"], row["download_filename"])
- await self._sem.acquire()
- tg.create_task(self._delete_and_log(file, hash_value))
-
- for hash_value, size_dict in final_dict.items():
- for size in size_dict:
- tg.create_task(delete_dupes(hash_value, size))
-
- async def _delete_and_log(self, file: Path, xxh128_value: str) -> None:
- hash_string = f"xxh128:{xxh128_value}"
- try:
- deleted = await _delete_file(file, self._to_trash)
- except OSError as e:
- logger.exception(f"Unable to remove '{file}' ({hash_string}): {e}")
- else:
- if not deleted:
- return
-
- msg = (
- f"Removed new download '{file}' [{self._deleted_file_suffix}]. "
- f"File hash matches with a previous download ({hash_string})"
- )
- logger.info(msg)
- self.manager.progress_manager.hash_progress.add_removed_file()
-
- finally:
- self._sem.release()
-
- async def get_file_hashes_dict(self) -> dict:
- """Get a dictionary of files based on matching file hashes and file size."""
- downloads = self.manager.completed_downloads
-
- async def exists(item: MediaItem) -> MediaItem | None:
- if await aio.is_file(item.path):
- return item
-
- results = await asyncio.gather(*(exists(item) for item in downloads))
- for media_item in results:
- if media_item is None:
- continue
- try:
- await self.hash_item(media_item)
- except Exception:
- logger.exception(msg=f"Unable to hash '{media_item.path}'")
- return self.hashes_dict
-
-
-async def _delete_file(path: Path, to_trash: bool = True) -> bool:
- """Deletes a file and return `True` on success, `False` is the file was not found.
-
- Any other exception is propagated"""
-
- if to_trash:
- coro = asyncio.to_thread(send2trash, path)
- else:
- coro = aio.unlink(path)
-
- try:
- await coro
- return True
- except FileNotFoundError:
- pass
- except OSError as e:
- # send2trash raises everything as a bare OSError. We should only ignore FileNotFound and raise everything else
- msg = str(e)
- if "File not found" not in msg:
- raise
-
- return False
diff --git a/cyberdrop_dl/constants.py b/cyberdrop_dl/constants.py
index bf62acd34..96265d8e0 100644
--- a/cyberdrop_dl/constants.py
+++ b/cyberdrop_dl/constants.py
@@ -1,18 +1,18 @@
+from __future__ import annotations
+
import re
-from dataclasses import field
from datetime import UTC, datetime
from enum import auto
from pathlib import Path
from typing import TYPE_CHECKING, Final, final
-from aiohttp.resolver import AsyncResolver, ThreadedResolver
from rich.text import Text
from cyberdrop_dl import env
from cyberdrop_dl.compat import CIStrEnum, Enum, StrEnum
if TYPE_CHECKING:
- from cyberdrop_dl.utils.logger import LogHandler
+ from aiohttp.resolver import AsyncResolver, ThreadedResolver
# TIME
STARTUP_TIME = datetime.now()
@@ -45,7 +45,6 @@ REGEX_LINKS = re.compile(r"(?:http.*?)(?=($|\n|\r\n|\r|\s|\"|\[/URL]|']\[|]\[|\[
HTTP_REGEX_LINKS = re.compile(
r"https?://(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,12}\b([-a-zA-Z0-9@:%_+.~#?&/=]*)"
)
-console_handler: "LogHandler"
class TempExt(StrEnum):
@@ -82,7 +81,6 @@ class BlockedDomains:
DEFAULT_APP_STORAGE = Path("./AppData")
DEFAULT_DOWNLOAD_STORAGE = Path("./Downloads")
RESERVED_CONFIG_NAMES = ["all", "default"]
-NOT_DEFINED = field(init=False)
class HashType(StrEnum):
diff --git a/cyberdrop_dl/director.py b/cyberdrop_dl/director.py
index 574629d8c..37fc33e1a 100644
--- a/cyberdrop_dl/director.py
+++ b/cyberdrop_dl/director.py
@@ -78,7 +78,7 @@ async def _post_runtime(manager: Manager) -> None:
log_spacer()
logger.info("Running Post-Download Processes", extra={"color": "green"})
- await manager.hash_manager.hash_client.cleanup_dupes_after_download()
+ await manager.hasher.cleanup_dupes_after_download()
if manager.config_manager.settings_data.sorting.sort_downloads and not manager.parsed_args.cli_only_args.retry_any:
sorter = Sorter.from_manager(manager)
diff --git a/cyberdrop_dl/hasher.py b/cyberdrop_dl/hasher.py
new file mode 100644
index 000000000..8ca908e3a
--- /dev/null
+++ b/cyberdrop_dl/hasher.py
@@ -0,0 +1,273 @@
+from __future__ import annotations
+
+import asyncio
+import dataclasses
+import hashlib
+import logging
+from collections import defaultdict
+from pathlib import Path
+from typing import TYPE_CHECKING, Final, Literal
+
+import xxhash
+from send2trash import send2trash
+
+from cyberdrop_dl import aio
+from cyberdrop_dl.constants import Hashing, TempExt
+
+if TYPE_CHECKING:
+ from yarl import URL
+
+ from cyberdrop_dl.config.config_model import DupeCleanup
+ from cyberdrop_dl.data_structures.url_objects import MediaItem
+ from cyberdrop_dl.managers.manager import Manager
+
+
+_HASHERS: Final = {
+ "md5": hashlib.md5,
+ "xxh128": xxhash.xxh128,
+ "sha256": hashlib.sha256,
+}
+_CHUNK_SIZE: Final = 1024 * 1024 # 1MB
+
+
+logger = logging.getLogger(__name__)
+
+
+def _compute_hash(file: Path, algorithm: Literal["xxh128", "md5", "sha256"]) -> str:
+ with file.open("rb") as fp:
+ hash = _HASHERS[algorithm]()
+ buffer = bytearray(_CHUNK_SIZE)
+ mem_view = memoryview(buffer)
+ while size := fp.readinto(buffer):
+ hash.update(mem_view[:size])
+
+ return hash.hexdigest()
+
+
+async def hash_directory_scanner(manager: Manager, path: Path) -> None:
+ manager.async_db_hash_startup()
+ async with manager.database:
+ await manager.hasher.hash_directory(path)
+ manager.progress_manager.print_dedupe_stats()
+ manager.progress_manager.hash_progress.reset()
+
+
[email protected](slots=True)
+class Hasher:
+ manager: Manager
+ hashed_media_items: list[MediaItem] = dataclasses.field(init=False, default_factory=list)
+ hashes_dict: dict[str, dict[int, set[Path]]] = dataclasses.field(
+ init=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)
+
+ @property
+ def config(self) -> DupeCleanup:
+ return self.manager.config.dupe_cleanup_options
+
+ async def hash_file(self, filename: Path | str, hash_type: Literal["xxh128", "md5", "sha256"]) -> str:
+ file_path = self._cwd / filename
+ return await asyncio.to_thread(_compute_hash, file_path, hash_type)
+
+ @property
+ def _to_trash(self) -> bool:
+ return self.config.send_deleted_to_trash
+
+ @property
+ def _deleted_file_suffix(self) -> Literal["Sent to trash", "Permanently deleted"]:
+ return "Sent to trash" if self._to_trash else "Permanently deleted"
+
+ 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.currently_hashing_dir(path),
+ ):
+ if not await aio.is_dir(path):
+ raise NotADirectoryError(None, path)
+
+ async for file in aio.rglob(path, "*"):
+ _ = await self.update_db_and_retrive_hash(file)
+
+ async def hash_item(self, media_item: MediaItem) -> None:
+ if media_item.is_segment:
+ return
+ hash = 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)
+
+ async def hash_item_during_download(self, media_item: MediaItem) -> None:
+ if media_item.is_segment:
+ return
+
+ if self.config.hashing != Hashing.IN_PLACE:
+ return
+
+ try:
+ assert media_item.original_filename
+ hash = 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)
+ except Exception as e:
+ logger.exception(f"After hash processing failed: '{media_item.path}' with error {e}")
+
+ async def update_db_and_retrive_hash(
+ self,
+ file: Path | str,
+ original_filename: str | None = None,
+ referer: URL | None = None,
+ ) -> str | None:
+ file = Path(file)
+
+ if file.suffix in TempExt:
+ return
+
+ if not await aio.get_size(file):
+ return
+
+ hash = await self._update_db_and_retrive_hash(file, original_filename, referer, hash_type="xxh128")
+ if self.config.add_md5_hash:
+ await self._update_db_and_retrive_hash(file, original_filename, referer, hash_type="md5")
+ if self.config.add_sha256_hash:
+ await self._update_db_and_retrive_hash(file, original_filename, referer, hash_type="sha256")
+
+ return hash
+
+ async def _update_db_and_retrive_hash(
+ self,
+ file: Path,
+ original_filename: str | None,
+ referer: URL | None,
+ hash_type: Literal["xxh128", "md5", "sha256"],
+ ) -> str | None:
+ """Generates hash of a file."""
+ self.manager.progress_manager.hash_progress.update_currently_hashing(file)
+ hash = await self.manager.database.hash.get_file_hash_exists(file, hash_type)
+ try:
+ if not hash:
+ hash = await self.hash_file(file, hash_type)
+ await self.manager.database.hash.insert_or_update_hash_db(
+ hash,
+ hash_type,
+ file,
+ original_filename,
+ referer,
+ )
+ self.manager.progress_manager.hash_progress.add_new_completed_hash(hash_type)
+ else:
+ self.manager.progress_manager.hash_progress.add_prev_hash()
+ await self.manager.database.hash.insert_or_update_hash_db(
+ hash,
+ hash_type,
+ file,
+ original_filename,
+ referer,
+ )
+ except Exception as e:
+ logger.exception(f"Error hashing '{file}' : {e}")
+ else:
+ return hash
+
+ async def save_hash_data(self, media_item: MediaItem, hash: str | None) -> None:
+ if not hash:
+ return
+
+ 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:
+ media_item.hash = hash
+ self.hashes_dict[hash][size].add(absolute_path)
+
+ async def cleanup_dupes_after_download(self) -> None:
+ if self.config.hashing == Hashing.OFF:
+ return
+ if not self.config.auto_dedupe:
+ return
+ if self.manager.config.runtime_options.ignore_history:
+ return
+ with self.manager.live_manager.get_hash_live(stop=True):
+ file_hashes_dict = await self.get_file_hashes_dict()
+ with self.manager.live_manager.get_remove_file_via_hash_live(stop=True):
+ await self.final_dupe_cleanup(file_hashes_dict)
+
+ async def final_dupe_cleanup(self, final_dict: dict[str, dict[int, set[Path]]]) -> None:
+ """cleanup files based on dedupe setting"""
+
+ get_matches = self.manager.database.hash.get_files_with_hash_matches
+ async with asyncio.TaskGroup() as tg:
+
+ async def delete_dupes(hash_value: str, size: int) -> None:
+ db_matches = await get_matches(hash_value, size, "xxh128")
+ for row in db_matches[1:]:
+ file = Path(row["folder"], row["download_filename"])
+ await self._sem.acquire()
+ tg.create_task(self._delete_and_log(file, hash_value))
+
+ for hash_value, size_dict in final_dict.items():
+ for size in size_dict:
+ tg.create_task(delete_dupes(hash_value, size))
+
+ async def _delete_and_log(self, file: Path, xxh128_value: str) -> None:
+ hash_string = f"xxh128:{xxh128_value}"
+ try:
+ deleted = await _delete_file(file, self._to_trash)
+ except OSError as e:
+ logger.exception(f"Unable to remove '{file}' ({hash_string}): {e}")
+
+ else:
+ if not deleted:
+ return
+
+ msg = (
+ f"Removed new download '{file}' [{self._deleted_file_suffix}]. "
+ f"File hash matches with a previous download ({hash_string})"
+ )
+ logger.info(msg)
+ self.manager.progress_manager.hash_progress.add_removed_file()
+
+ finally:
+ self._sem.release()
+
+ async def get_file_hashes_dict(self) -> dict[str, dict[int, set[Path]]]:
+ downloads = self.manager.completed_downloads
+
+ async def exists(item: MediaItem) -> MediaItem | None:
+ if await aio.is_file(item.path):
+ return item
+
+ results = await asyncio.gather(*(exists(item) for item in downloads))
+ for media_item in results:
+ if media_item is None:
+ continue
+ try:
+ await self.hash_item(media_item)
+ except Exception:
+ logger.exception(msg=f"Unable to hash '{media_item.path}'")
+ return self.hashes_dict
+
+
+async def _delete_file(path: Path, to_trash: bool = True) -> bool:
+ """Deletes a file and return `True` on success, `False` is the file was not found.
+
+ Any other exception is propagated"""
+
+ if to_trash:
+ coro = asyncio.to_thread(send2trash, path)
+ else:
+ coro = aio.unlink(path)
+
+ try:
+ await coro
+ return True
+ except FileNotFoundError:
+ pass
+ except OSError as e:
+ # send2trash raises everything as a bare OSError. We should only ignore FileNotFound and raise everything else
+ msg = str(e)
+ if "File not found" not in msg:
+ raise
+
+ return False
diff --git a/cyberdrop_dl/managers/hash_manager.py b/cyberdrop_dl/managers/hash_manager.py
deleted file mode 100644
index 8a24d46c4..000000000
--- a/cyberdrop_dl/managers/hash_manager.py
+++ /dev/null
@@ -1,41 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import hashlib
-from pathlib import Path
-from typing import TYPE_CHECKING, Final, Literal
-
-import xxhash
-
-from cyberdrop_dl.clients.hash_client import HashClient
-
-if TYPE_CHECKING:
- from cyberdrop_dl.managers.manager import Manager
-
-_HASHERS: Final = {
- "md5": hashlib.md5,
- "xxh128": xxhash.xxh128,
- "sha256": hashlib.sha256,
-}
-_CHUNK_SIZE: Final = 1024 * 1024 # 1MB
-
-
-class HashManager:
- def __init__(self, manager: Manager) -> None:
- self._cwd: Path = Path.cwd()
- self.hash_client: HashClient = HashClient(manager)
-
- async def hash_file(self, filename: Path | str, hash_type: Literal["xxh128", "md5", "sha256"]) -> str:
- file_path = self._cwd / filename
- return await asyncio.to_thread(_compute_hash, file_path, hash_type)
-
-
-def _compute_hash(file: Path, algorithm: Literal["xxh128", "md5", "sha256"]) -> str:
- with file.open("rb") as file_io:
- hash = _HASHERS[algorithm]()
- buffer = bytearray(_CHUNK_SIZE) # Reusable buffer to reduce allocations
- mem_view = memoryview(buffer)
- while size := file_io.readinto(buffer):
- hash.update(mem_view[:size])
-
- return hash.hexdigest()
diff --git a/cyberdrop_dl/managers/live_manager.py b/cyberdrop_dl/managers/live_manager.py
index bab9bc58e..6f2b50b28 100644
--- a/cyberdrop_dl/managers/live_manager.py
+++ b/cyberdrop_dl/managers/live_manager.py
@@ -7,7 +7,6 @@ from typing import TYPE_CHECKING
from rich.live import Live
-from cyberdrop_dl import constants
from cyberdrop_dl.cli import is_terminal_in_portrait
if TYPE_CHECKING:
@@ -62,13 +61,12 @@ class LiveManager:
orientation_task = None
try:
- with self.replace_console():
- self.live.start()
- if layout:
- self.live.update(layout, refresh=True)
- if self.current_layout in ("vertical_layout", "horizontal_layout"):
- orientation_task = asyncio.create_task(self.watch_orientation(stop_event))
- yield self.live
+ self.live.start()
+ if layout:
+ self.live.update(layout, refresh=True)
+ if self.current_layout in ("vertical_layout", "horizontal_layout"):
+ orientation_task = asyncio.create_task(self.watch_orientation(stop_event))
+ yield self.live
finally:
stop_event.set()
if orientation_task:
@@ -76,14 +74,3 @@ class LiveManager:
if stop:
self.live.update("")
self.live.stop()
-
- @contextmanager
- def replace_console(self) -> Generator[None]:
- """Disable the default console, replacing it with the internal live's console"""
-
- default_console = constants.console_handler.console
- try:
- constants.console_handler.console = self.live.console
- yield
- finally:
- constants.console_handler.console = default_console
diff --git a/cyberdrop_dl/managers/manager.py b/cyberdrop_dl/managers/manager.py
index 13ba14053..0ab772cf3 100644
--- a/cyberdrop_dl/managers/manager.py
+++ b/cyberdrop_dl/managers/manager.py
@@ -10,17 +10,16 @@ from typing import TYPE_CHECKING, Any, Self, TypeVar
from pydantic import BaseModel
-from cyberdrop_dl import __version__, constants, ffmpeg, yaml
+from cyberdrop_dl import __version__, ffmpeg, yaml
from cyberdrop_dl.cli import ParsedArgs, parse_args
from cyberdrop_dl.database import Database
+from cyberdrop_dl.hasher import Hasher
from cyberdrop_dl.managers.client_manager import ClientManager
from cyberdrop_dl.managers.config_manager import ConfigManager
-from cyberdrop_dl.managers.hash_manager import HashManager
from cyberdrop_dl.managers.live_manager import LiveManager
from cyberdrop_dl.managers.logs import LogManager
from cyberdrop_dl.managers.progress_manager import ProgressManager
from cyberdrop_dl.utils import filepath
-from cyberdrop_dl.utils.logger import LogHandler, QueuedLogger
from cyberdrop_dl.utils.utilities import get_system_information
if TYPE_CHECKING:
@@ -30,6 +29,7 @@ if TYPE_CHECKING:
from cyberdrop_dl.data_structures.url_objects import MediaItem
from cyberdrop_dl.scraper.scrape_mapper import ScrapeMapper
+ from cyberdrop_dl.utils.logger import QueuedLogger
logger = logging.getLogger(__name__)
@@ -43,7 +43,6 @@ class Manager:
self.parsed_args: ParsedArgs = field(init=False)
self.cache: dict[str, Any] = {}
self.config_manager: ConfigManager = field(init=False)
- self.hash_manager: HashManager = field(init=False)
self.logs: LogManager = field(init=False)
self.database: Database = field(init=False)
@@ -65,8 +64,7 @@ class Manager:
self._appdata: AppData | None = None
self._completed_downloads: list[MediaItem] = []
-
- constants.console_handler = LogHandler(level=constants.CONSOLE_LEVEL)
+ self.hasher: Hasher = Hasher(self)
@property
def config(self):
@@ -138,7 +136,6 @@ class Manager:
self.config.runtime_options.ignore_history,
)
- self.hash_manager = HashManager(self)
self.live_manager = LiveManager(self)
self.progress_manager = ProgressManager(self)
diff --git a/cyberdrop_dl/ui/program_ui.py b/cyberdrop_dl/ui/program_ui.py
index 94dd85db7..d38880fb2 100644
--- a/cyberdrop_dl/ui/program_ui.py
+++ b/cyberdrop_dl/ui/program_ui.py
@@ -15,7 +15,7 @@ from rich.markdown import Markdown
from rich.text import Text
from cyberdrop_dl import __version__
-from cyberdrop_dl.clients.hash_client import hash_directory_scanner
+from cyberdrop_dl.hasher import hash_directory_scanner
from cyberdrop_dl.progress import hyperlink
from cyberdrop_dl.utils import text_editor
from cyberdrop_dl.utils.sorting import Sorter
diff --git a/tests/test_hashing.py b/tests/test_hashing.py
index 8eb90603b..e11330773 100644
--- a/tests/test_hashing.py
+++ b/tests/test_hashing.py
@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING
import pytest
-from cyberdrop_dl.clients.hash_client import hash_directory_scanner
+from cyberdrop_dl.hasher import hash_directory_scanner
if TYPE_CHECKING:
from pathlib import Path