Skip to content

Bulk asynchronous downloader for multiple file hosts

add code for deleting hash

datawhores5a4b1f86c375
diff --git a/cyberdrop_dl/clients/hash_client.py b/cyberdrop_dl/clients/hash_client.py
index 10ad6927b..289725465 100644
--- a/cyberdrop_dl/clients/hash_client.py
+++ b/cyberdrop_dl/clients/hash_client.py
@@ -1,6 +1,6 @@
import pathlib
from contextlib import asynccontextmanager
-from cyberdrop_dl.managers.db_manager import DBManager
+from collections import defaultdict
import asyncio
@@ -16,16 +16,54 @@ class HashClient:
await self.manager.close()
def hash_directory(self,path):
- asyncio.run(self.hash_directory_helper(path))
+ asyncio.run(self._hash_directory_helper(path))
- async def hash_directory_helper(self,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)
+ await self._hash_item_helper(file)
+
+ async def _hash_item_helper(self,file):
+ hash=await self.manager.db_manager.hash_table.get_file_hash_exists(file)
+ if not hash and file.exists():
+ 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)
+ return hash
+
+ async def cleanup_dupes(self):
+ hashes_dict=defaultdict(list)
+ # first compare downloads to each other
+ for item in self.manager.path_manager.completed_downloads:
+ hash=await self._hash_item_helper(item)
+ if hash:
+ hashes_dict[hash].append(item)
+ #remove downloaded files, so each group only has the first downloaded file
+ final_list=[]
+ for key,group in hashes_dict.items():
+ #double check files exits
+ match=False
+ for ele in group:
+ if match:
+ ele.unlink(missing_ok=True)
+ elif ele.exists():
+ match=ele
+ final_list.append((key,ele))
+ # compare hashes against all hashes in db
+ for ele in final_list:
+ hash=ele[0]
+ path=ele[1]
+ # get all files with same hash
+ all_matches=list(map(lambda x:pathlib.Path(x[0],x[1]),await self.manager.db_manager.hash_table.get_files_with_hash_matches(hash)))
+ # delete files if more then one match exists
+ matches=list(filter(lambda x:x!=path and x.exists(),all_matches))
+ if len(matches)>0:
+ path.unlink(missing_ok=True)
+
+
+
+
+ #compare other files in folder, and remove downloaded if already exists
+
diff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.py
index bd5378da3..43121ce22 100644
--- a/cyberdrop_dl/main.py
+++ b/cyberdrop_dl/main.py
@@ -12,7 +12,7 @@ from cyberdrop_dl.scraper.scraper import ScrapeMapper
from cyberdrop_dl.ui.ui import program_ui
from cyberdrop_dl.utils.sorting import Sorter
from cyberdrop_dl.utils.utilities import check_latest_pypi, log_with_color, check_partials_and_empty_folders, log
-
+from cyberdrop_dl.clients.hash_client import HashClient
def startup() -> Manager:
"""
@@ -47,9 +47,8 @@ async def runtime(manager: Manager) -> None:
async def post_runtime(manager: Manager) -> None:
"""Actions to complete after main runtime, and before ui shutdown"""
#checking and removing dupes
- downloads=manager.path_manager.completed_downloads
- for download in downloads:
- print(download)
+ await HashClient(manager).cleanup_dupes()
+
async def director(manager: Manager) -> None:
"""Runs the program and handles the UI"""
diff --git a/cyberdrop_dl/managers/manager.py b/cyberdrop_dl/managers/manager.py
index 377e81cdc..2214280b0 100644
--- a/cyberdrop_dl/managers/manager.py
+++ b/cyberdrop_dl/managers/manager.py
@@ -85,6 +85,8 @@ class Manager:
self.client_manager = ClientManager(self)
if not isinstance(self.download_manager, DownloadManager):
self.download_manager = DownloadManager(self)
+ if not isinstance(self.hash_manager, HashManager):
+ self.hash_manager = HashManager()
self.progress_manager = ProgressManager(self)
await self.progress_manager.startup()
diff --git a/cyberdrop_dl/utils/database/tables/hash_table.py b/cyberdrop_dl/utils/database/tables/hash_table.py
index 326dbea4e..4059ecd9b 100644
--- a/cyberdrop_dl/utils/database/tables/hash_table.py
+++ b/cyberdrop_dl/utils/database/tables/hash_table.py
@@ -1,6 +1,6 @@
from __future__ import annotations
import pathlib
-from sqlite3 import Row, IntegrityError
+from sqlite3 import IntegrityError
import aiosqlite
@@ -17,16 +17,15 @@ class HashTable:
await self.db_conn.commit()
- async def check_file_hash_exists(self, full_path):
+ async def get_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.
+ hash if exists
"""
try:
@@ -42,19 +41,40 @@ class HashTable:
# 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
+ if result and result[0]:
+ return result[0]
+ return None
except Exception as e:
print(f"Error checking file: {e}")
return False
+ async def get_files_with_hash_matches(self,hash_value):
+ """
+ Retrieves a list of (folder, filename) tuples based on a given hash.
+
+ Args:
+ hash_value: The hash value to search for.
+
+ Returns:
+ A list of (folder, filename) tuples, or an empty list if no matches found.
+ """
+
+ cursor = await self.db_conn.cursor()
+
+ try:
+ await cursor.execute("SELECT folder, filename FROM hash WHERE hash = ?", (hash_value,))
+ results = await cursor.fetchall()
+ return results
+ except Exception as e:
+ print(f"Error retrieving folder and filename: {e}")
+ return []
+
+
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.