Skip to content

Bulk asynchronous downloader for multiple file hosts

add hashing client add hash_manager for creating hashes add menu option for hashing a directory

datawhores50f56ee05f75
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
index ca751700f..e2d67f6c7 100644
--- a/.github/FUNDING.yml
+++ b/.github/FUNDING.yml
@@ -1,4 +1,4 @@
# These are supported funding model platforms
-github: [Jules-WinnfieldX]
-custom: ['https://www.buymeacoffee.com/juleswinnft']
+github: [jbsparrow]
+custom: ['https://buymeacoffee.com/jbsparrow']
diff --git a/.gitignore b/.gitignore
index 1866efcbe..0b37df4ac 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,6 @@
# Python cache
__pycache__
+
+.venv
+.vscode
diff --git a/cyberdrop_dl/clients/hash_client.py b/cyberdrop_dl/clients/hash_client.py
new file mode 100644
index 000000000..def81aac2
--- /dev/null
+++ b/cyberdrop_dl/clients/hash_client.py
@@ -0,0 +1,30 @@
+import pathlib
+from contextlib import asynccontextmanager
+from cyberdrop_dl.managers.db_manager import DBManager
+import asyncio
+
+
+class HashClient:
+ """Manage hashes and db insertion"""
+ def __init__(self,manager):
+ self.manager=manager
+
+ @asynccontextmanager
+ async def _manager_context(self):
+ await self.manager.async_db_hash_startup()
+ yield
+ await self.manager.close()
+
+ def hash_directory(self,path):
+ asyncio.run(self.hash_directory_helper(path))
+
+ async def hash_directory_helper(self,path):
+ async with self._manager_context():
+ if not pathlib.Path(path).is_dir():
+ raise Exception("Path is not a directory")
+ for file in pathlib.Path(path).glob("**/*"):
+ if await self.manager.db_manager.hash_table.check_file_hash_exists(file):
+ continue
+ else:
+ hash = await self.manager.hash_manager.hash_file(file)
+ await self.manager.db_manager.hash_table.insert_or_update_hash_db(hash, file.stat().st_size, file.name, file.parent)
diff --git a/cyberdrop_dl/managers/db_manager.py b/cyberdrop_dl/managers/db_manager.py
index 04c71cbf7..feb98b9f2 100644
--- a/cyberdrop_dl/managers/db_manager.py
+++ b/cyberdrop_dl/managers/db_manager.py
@@ -6,6 +6,7 @@ import aiosqlite
from cyberdrop_dl.utils.database.tables.history_table import HistoryTable
from cyberdrop_dl.utils.database.tables.temp_table import TempTable
+from cyberdrop_dl.utils.database.tables.hash_table import HashTable
if TYPE_CHECKING:
from cyberdrop_dl.managers.manager import Manager
@@ -20,6 +21,7 @@ class DBManager:
self.ignore_history: bool = False
self.history_table: HistoryTable = field(init=False)
+ self.hash_table: HashTable = field(init=False)
self.temp_table: TempTable = field(init=False)
async def startup(self) -> None:
@@ -29,6 +31,7 @@ class DBManager:
self.ignore_history = self.manager.config_manager.settings_data['Runtime_Options']['ignore_history']
self.history_table = HistoryTable(self._db_conn)
+ self.hash_table=HashTable(self._db_conn)
self.temp_table = TempTable(self._db_conn)
self.history_table.ignore_history = self.ignore_history
@@ -36,6 +39,7 @@ class DBManager:
await self._pre_allocate()
await self.history_table.startup()
+ await self.hash_table.startup()
await self.temp_table.startup()
async def close(self) -> None:
diff --git a/cyberdrop_dl/managers/hash_manager.py b/cyberdrop_dl/managers/hash_manager.py
index 6cfea36b2..88df80aa5 100644
--- a/cyberdrop_dl/managers/hash_manager.py
+++ b/cyberdrop_dl/managers/hash_manager.py
@@ -1,23 +1,25 @@
-
-class Hasher:
+import os # Import os for file path manipulation
+import aiofiles
+class HashManager:
def __init__(self):
- pass
-
- def hash_file(filename):
- file_hash = self.hasher()
- with self.path.open("rb") as fp:
- CHUNK_SIZE = 1024 * 1024 # 1 mb
- filedata = fp.read(CHUNK_SIZE)
- while filedata:
- file_hash.update(filedata)
- filedata = fp.read(CHUNK_SIZE)
- return file_hash.digest()
- @property
- def hasher():
- hasher: Callable
- try:
- import xxhash
- return xxhash.xxh128
- except ImportError:
- import hashlib
- return hashlib.md5
+ self.hasher = self._get_hasher() # Initialize hasher in constructor
+
+ def _get_hasher(self):
+ """Tries to import xxhash, otherwise falls back to hashlib.md5"""
+ try:
+ import xxhash
+ return xxhash.xxh128
+ except ImportError:
+ import hashlib
+ return hashlib.md5
+
+ async def hash_file(self, filename):
+ file_path = os.path.join(os.getcwd(), filename) # Construct full file path
+ async with aiofiles.open(file_path, "rb") as fp:
+ CHUNK_SIZE = 1024 * 1024 # 1 mb
+ filedata = await fp.read(CHUNK_SIZE)
+ hasher = self.hasher() # Use the initialized hasher
+ while filedata:
+ hasher.update(filedata)
+ filedata = await fp.read(CHUNK_SIZE)
+ return hasher.hexdigest()
diff --git a/cyberdrop_dl/managers/manager.py b/cyberdrop_dl/managers/manager.py
index 0cb562fa6..377e81cdc 100644
--- a/cyberdrop_dl/managers/manager.py
+++ b/cyberdrop_dl/managers/manager.py
@@ -13,6 +13,8 @@ from cyberdrop_dl.managers.download_manager import DownloadManager
from cyberdrop_dl.managers.log_manager import LogManager
from cyberdrop_dl.managers.path_manager import PathManager
from cyberdrop_dl.managers.progress_manager import ProgressManager
+from cyberdrop_dl.managers.hash_manager import HashManager
+
from cyberdrop_dl.utils.args import config_definitions
from cyberdrop_dl.utils.dataclasses.supported_domains import SupportedDomains
from cyberdrop_dl.utils.transfer.first_time_setup import TransitionManager
@@ -25,6 +27,8 @@ class Manager:
self.cache_manager: CacheManager = CacheManager(self)
self.path_manager: PathManager = field(init=False)
self.config_manager: ConfigManager = field(init=False)
+ self.hash_manager: HashManager = field(init=False)
+
self.log_manager: LogManager = field(init=False)
self.db_manager: DBManager = field(init=False)
self.client_manager: ClientManager = field(init=False)
@@ -67,6 +71,7 @@ class Manager:
"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
+
async def async_startup(self) -> None:
"""Async startup process for the manager"""
await self.args_consolidation()
@@ -88,6 +93,15 @@ class Manager:
MAX_NAME_LENGTHS['FILE'] = int(self.config_manager.global_settings_data['General']['max_file_name_length'])
MAX_NAME_LENGTHS['FOLDER'] = int(self.config_manager.global_settings_data['General']['max_folder_name_length'])
+ async def async_db_hash_startup(self):
+ #start up the db manager and hash manager only
+ if not isinstance(self.db_manager, DBManager):
+ self.db_manager = DBManager(self, self.path_manager.history_db)
+ await self.db_manager.startup()
+ if not isinstance(self.hash_manager, HashManager):
+ self.hash_manager = HashManager()
+
+
async def args_consolidation(self) -> None:
"""Consolidates runtime arguments with config values"""
for arg in self.args_manager.parsed_args:
diff --git a/cyberdrop_dl/ui/prompts/general_prompts.py b/cyberdrop_dl/ui/prompts/general_prompts.py
index b62ee4304..b4c9d32e8 100644
--- a/cyberdrop_dl/ui/prompts/general_prompts.py
+++ b/cyberdrop_dl/ui/prompts/general_prompts.py
@@ -29,15 +29,16 @@ def main_prompt(manager: Manager) -> int:
Choice(1, "Download"),
Choice(2, "Download (All Configs)"),
Choice(3, "Retry Failed Downloads"),
- Choice(4, "Sort All Configs"),
- Choice(5, "Edit URLs"),
+ Choice(4, "Create File Hashes"),
+ Choice(5, "Sort All Configs"),
+ Choice(6, "Edit URLs"),
Separator(),
- Choice(6, f"Select Config (Current: {manager.config_manager.loaded_config})"),
- Choice(7, "Change URLs.txt file and Download Location"),
- Choice(8, "Edit Configs"),
+ Choice(7, f"Select Config (Current: {manager.config_manager.loaded_config})"),
+ Choice(8, "Change URLs.txt file and Download Location"),
+ Choice(9, "Edit Configs"),
Separator(),
- Choice(9, "Import Cyberdrop_V4 Items"),
- Choice(10, "Exit"),
+ Choice(10, "Import Cyberdrop_V4 Items"),
+ Choice(11, "Exit"),
], long_instruction="ARROW KEYS: Navigate | ENTER: Select",
vi_mode=manager.vi_mode,
).execute()
diff --git a/cyberdrop_dl/ui/prompts/settings_hash_prompts.py b/cyberdrop_dl/ui/prompts/settings_hash_prompts.py
new file mode 100644
index 000000000..6182c0ec9
--- /dev/null
+++ b/cyberdrop_dl/ui/prompts/settings_hash_prompts.py
@@ -0,0 +1,21 @@
+from __future__ import annotations
+
+import os
+from typing import TYPE_CHECKING
+
+from InquirerPy import inquirer
+from InquirerPy.validator import PathValidator
+
+if TYPE_CHECKING:
+ from cyberdrop_dl.managers.manager import Manager
+
+
+
+def path_prompt(manager: Manager):
+ home_path = "~/" if os.name == "posix" else "C:\\"
+ hash_path = inquirer.filepath(
+ message="Select the directory to scan",
+ default=home_path,
+ validate=PathValidator(is_dir=True, message="Input is not a directory"),
+ ).execute()
+ return hash_path
\ No newline at end of file
diff --git a/cyberdrop_dl/ui/ui.py b/cyberdrop_dl/ui/ui.py
index 4531a4089..5faa58c04 100644
--- a/cyberdrop_dl/ui/ui.py
+++ b/cyberdrop_dl/ui/ui.py
@@ -15,6 +15,8 @@ from cyberdrop_dl.ui.prompts.general_prompts import (
from cyberdrop_dl.ui.prompts.settings_global_prompts import edit_global_settings_prompt
from cyberdrop_dl.ui.prompts.url_file_prompts import edit_urls_prompt
from cyberdrop_dl.ui.prompts.settings_user_prompts import create_new_config_prompt, edit_config_values_prompt
+from cyberdrop_dl.clients.hash_client import HashClient
+from cyberdrop_dl.ui.prompts.settings_hash_prompts import path_prompt
console = Console()
@@ -45,24 +47,30 @@ def program_ui(manager: Manager):
manager.args_manager.retry = True
break
- # Sort All Configs
+ # Scanning folder to create hashes
elif action == 4:
+ path=path_prompt(manager)
+ HashClient(manager).hash_directory(path)
+ break
+
+ # Sort All Configs
+ elif action == 5:
manager.args_manager.sort_all_configs = True
manager.args_manager.all_configs = True
break
# Edit URLs
- elif action == 5:
+ elif action == 6:
input_file = manager.config_manager.settings_data['Files']['input_file'] if not manager.args_manager.input_file else manager.args_manager.input_file
edit_urls_prompt(input_file, manager.vi_mode)
# Select Config
- elif action == 6:
+ elif action == 7:
configs = manager.config_manager.get_configs()
selected_config = select_config_prompt(manager, configs)
manager.config_manager.change_config(selected_config)
- elif action == 7:
+ elif action == 8:
console.clear()
console.print("Editing Input / Output File Paths")
input_file = inquirer.filepath(
@@ -83,7 +91,7 @@ def program_ui(manager: Manager):
manager.config_manager.write_updated_settings_config()
# Manage Configs
- elif action == 8:
+ elif action == 9:
while True:
console.clear()
console.print("[bold]Manage Configs[/bold]")
@@ -138,9 +146,9 @@ def program_ui(manager: Manager):
break
# Import Cyberdrop_V4 Items
- elif action == 9:
+ elif action == 10:
import_cyberdrop_v4_items_prompt(manager)
# Exit
- elif action == 10:
+ elif action == 11:
exit(0)
diff --git a/cyberdrop_dl/utils/database/table_definitions.py b/cyberdrop_dl/utils/database/table_definitions.py
index 3b021e840..cfbbdd80d 100644
--- a/cyberdrop_dl/utils/database/table_definitions.py
+++ b/cyberdrop_dl/utils/database/table_definitions.py
@@ -23,3 +23,13 @@ create_fixed_history = """CREATE TABLE IF NOT EXISTS media_copy (domain TEXT,
);"""
create_temp = """CREATE TABLE IF NOT EXISTS temp (downloaded_filename TEXT);"""
+
+create_hash = """
+CREATE TABLE IF NOT EXISTS hash (
+ folder TEXT,
+ filename TEXT,
+ size INT,
+ hash TEXT,
+ UNIQUE (folder, filename)
+);
+"""
diff --git a/cyberdrop_dl/utils/database/tables/hash_table.py b/cyberdrop_dl/utils/database/tables/hash_table.py
new file mode 100644
index 000000000..326dbea4e
--- /dev/null
+++ b/cyberdrop_dl/utils/database/tables/hash_table.py
@@ -0,0 +1,92 @@
+from __future__ import annotations
+import pathlib
+from sqlite3 import Row, IntegrityError
+
+import aiosqlite
+
+from cyberdrop_dl.utils.database.table_definitions import create_hash
+
+
+class HashTable:
+ def __init__(self, db_conn: aiosqlite.Connection):
+ self.db_conn: aiosqlite.Connection = db_conn
+
+ async def startup(self) -> None:
+ """Startup process for the HistoryTable"""
+ await self.db_conn.execute(create_hash)
+ await self.db_conn.commit()
+
+
+ async def check_file_hash_exists(self, full_path):
+ """
+ Checks if a file exists in the database based on its folder, filename, and size.
+
+ Args:
+ db_path: Path to the SQLite database file.
+ full_path: Full path to the file to check.
+
+ Returns:
+ True if the file exists and has a hash, False otherwise.
+ """
+
+ try:
+ # Extract folder, filename, and size from the full path
+ path = pathlib.Path(full_path)
+ folder = str(path.parent)
+ filename = path.name
+ size = path.stat().st_size
+
+ # Connect to the database
+ cursor = await self.db_conn.cursor()
+
+ # Check if the file exists with matching folder, filename, and size
+ await cursor.execute("SELECT hash FROM hash WHERE folder=? AND filename=? AND size=?", (folder, filename, size))
+ result = await cursor.fetchone()
+
+
+ return bool(result and result[0]) # Return True if a hash exists, False otherwise
+ except Exception as e:
+ print(f"Error checking file: {e}")
+ return False
+
+ async def insert_or_update_hash_db(self, hash_value, file_size, filename, folder):
+ """
+ Inserts or updates a record in the specified SQLite database.
+
+ Args:
+ db_file: Path to the SQLite database file.
+ hash_value: The calculated hash of the file.
+ file_size: The size of the file in bytes.
+ filename: The name of the file.
+ folder: The folder containing the file.
+
+ Returns:
+ True if the record was inserted or updated successfully, False otherwise.
+ """
+
+ cursor = await self.db_conn.cursor()
+
+ filename=str(filename)
+ folder=str(folder)
+
+ # Assuming a table named 'file_info' with columns: id (primary key), hash, size, filename, folder
+ try:
+ await cursor.execute("INSERT INTO hash (hash, size, filename, folder) VALUES (?, ?, ?, ?)",
+ (hash_value, file_size, filename, folder))
+ await self.db_conn.commit()
+ return True
+ except IntegrityError:
+ # Handle potential duplicate key (assuming a unique constraint on hash, filename, and folder)
+ await cursor.execute("UPDATE hash SET size=?,hash=? WHERE filename=? AND folder=?",
+ (file_size,hash_value, filename, folder))
+ await self.db_conn.commit()
+ return True
+ except Exception as e:
+ print(f"Error inserting/updating record: {e}")
+ return False
+
+
+
+
+
+