Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
perf: async delete files (dedupe) (#823)
NTFSvolume8689619dc8c5
diff --git a/cyberdrop_dl/clients/hash_client.py b/cyberdrop_dl/clients/hash_client.pyindex 240f1452c..a5cf75189 100644--- a/cyberdrop_dl/clients/hash_client.py+++ b/cyberdrop_dl/clients/hash_client.py@@ -6,6 +6,7 @@ from collections import defaultdictfrom pathlib import Pathfrom typing import TYPE_CHECKING+import aiofiles.osfrom send2trash import send2trashfrom cyberdrop_dl.ui.prompts.basic_prompts import enter_to_continue@@ -144,43 +145,70 @@ class HashClient:async def final_dupe_cleanup(self, final_dict: dict[str, dict]) -> None:"""cleanup files based on dedupe setting"""+ to_trash = self.manager.config_manager.settings_data.dupe_cleanup_options.send_deleted_to_trash+ suffix = "Sent to trash " if to_trash else "Permanently deleted"++ async def delete_and_log(file: Path):+ try:+ deleted = await delete_file(file, to_trash)+ if deleted:+ log(f"Removed new download '{file}' with hash {hash} [{suffix}]", 10)+ self.manager.progress_manager.hash_progress.add_removed_file()++ except OSError as e:+ log(f"Unable to remove '{file}' with hash {hash}: {e}", 40)++ tasks = []+ get_matches = self.manager.db_manager.hash_table.get_files_with_hash_matchesfor hash, size_dict in final_dict.items():for size in size_dict:- # Get all matches from the database- db_matches = await self.manager.db_manager.hash_table.get_files_with_hash_matches(- hash, size, self.xxhash- )- all_matches = [Path(*match[:2]) for match in db_matches]- for file in all_matches[1:]:- if not file.is_file():- continue- try:- self.delete_file(file)- log(f"Removed new download: {file} with hash {hash}", 10)- self.manager.progress_manager.hash_progress.add_removed_file()- except OSError as e:- log(f"Unable to remove {file = } with hash {hash} : {e}", 40)+ db_matches = await get_matches(hash, size, self.xxhash)+ for match in db_matches[1:]:+ file = Path(*match[:2])+ tasks.append(delete_and_log(file))++ await asyncio.gather(*tasks)async def get_file_hashes_dict(self) -> dict:- """- get a dictionary of files based on matching file hashes and file size- """+ """Get a dictionary of files based on matching file hashes and file size."""downloads = self.manager.path_manager.completed_downloads - self.hashed_media_items- for media_item in downloads:- if not media_item.complete_file.is_file():++ async def exists(item: MediaItem) -> MediaItem | None:+ if await asyncio.to_thread(item.complete_file.is_file):+ return item++ results = await asyncio.gather(*(exists(item) for item in downloads))+ for media_item in results:+ if media_item is None:continuetry:await self.hash_item(media_item)except Exception as e:- msg = f"Unable to hash file = {media_item.complete_file.resolve()}: {e}"+ msg = f"Unable to hash file = {media_item.complete_file}: {e}"log(msg, 40)return self.hashes_dict- def delete_file(self, path: Path) -> None:- if self.manager.config_manager.settings_data.dupe_cleanup_options.send_deleted_to_trash:- send2trash(path)- log(f"sent file at{path} to trash", 10)- return- Path(path).unlink(missing_ok=True)- log(f"permanently deleted file at {path}", 10)+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 = aiofiles.os.unlink(Path(path))++ try:+ await coro+ 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+ else:+ return True++ return False