Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
add progress bar
datawhores675c90050c15
diff --git a/cyberdrop_dl/clients/hash_client.py b/cyberdrop_dl/clients/hash_client.pyindex 5d1226334..401c01585 100644--- a/cyberdrop_dl/clients/hash_client.py+++ b/cyberdrop_dl/clients/hash_client.py@@ -1,7 +1,11 @@import pathlib+from contextlib import asynccontextmanagerfrom collections import defaultdictimport asyncio+from rich.live import Live++class HashClient:@@ -20,10 +24,11 @@ class HashClient: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("**/*"):- await self.hash_item(file)+ with self.manager.live_manager.get_hash_live() as live:+ if not pathlib.Path(path).is_dir():+ raise Exception("Path is not a directory")+ for file in pathlib.Path(path).glob("**/*"):+ await self.hash_item(file)async def hash_item(self,file):if not file.is_file():@@ -32,44 +37,49 @@ class HashClient:if not hash: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)+ await self.manager.progress_manager.hash_progress.add_completed_hash()++ else:+ await self.manager.progress_manager.hash_progress.add_prev_hash()return hashasync def cleanup_dupes(self):- if not self.manager.config_manager.global_settings_data['Dupe_Cleanup_Options']['delete_after_download']:- return- hashes_dict=defaultdict(list)- # first compare downloads to each other- for item in self.manager.path_manager.completed_downloads:- hash=await self.hash_item(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:- continue- elif self.manager.config_manager.global_settings_data['Dupe_Cleanup_Options']['keep_current_download']:- for ele in matches:- ele.unlink(missing_ok=True)- else:- path.unlink(missing_ok=True)- for ele in matches:- ele.unlink(missing_ok=True)+ with self.manager.live_manager.get_hash_live() :+ if not self.manager.config_manager.global_settings_data['Dupe_Cleanup_Options']['delete_after_download']:+ return+ hashes_dict=defaultdict(list)+ # first compare downloads to each other+ for item in self.manager.path_manager.completed_downloads:+ hash=await self.hash_item(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:+ continue+ elif self.manager.config_manager.global_settings_data['Dupe_Cleanup_Options']['keep_current_download']:+ for ele in matches:+ ele.unlink(missing_ok=True)+ else:+ path.unlink(missing_ok=True)+ for ele in matches:+ ele.unlink(missing_ok=True)diff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.pyindex 43121ce22..7165a16ef 100644--- a/cyberdrop_dl/main.py+++ b/cyberdrop_dl/main.py@@ -111,11 +111,7 @@ async def director(manager: Manager) -> None:await log("Starting UI...", 20)if not manager.args_manager.sort_all_configs:try:- if not manager.args_manager.no_ui:- with Live(manager.progress_manager.layout, refresh_per_second=manager.config_manager.global_settings_data['UI_Options']['refresh_rate']):- await runtime(manager)- await post_runtime(manager)- else:+ with manager.live_manager.get_main_live():await runtime(manager)await post_runtime(manager)except Exception as e:diff --git a/cyberdrop_dl/managers/live_manager.py b/cyberdrop_dl/managers/live_manager.pynew file mode 100644index 000000000..bc7f769ab--- /dev/null+++ b/cyberdrop_dl/managers/live_manager.py@@ -0,0 +1,32 @@+from rich.live import Live+from contextlib import contextmanager++++class LiveManager:+ def __init__(self,manager):+ self.manager = manager+ self.live=None+ @contextmanager+ def get_main_live(self):+ if self.manager.args_manager.no_ui:+ yield+ elif self.live:+ self.live.update(Live(self.manager.progress_manager.layout, refresh_per_second=self.manager.config_manager.global_settings_data['UI_Options']['refresh_rate']))+ yield self.live+ else:+ self.live=Live(self.manager.progress_manager.layout, refresh_per_second=self.manager.config_manager.global_settings_data['UI_Options']['refresh_rate'])+ with self.live as live:+ yield live+ @contextmanager+ def get_hash_live(self):+ if self.manager.args_manager.no_ui:+ yield+ elif self.live:+ self.live.update(Live(self.manager.progress_manager.hash_layout, refresh_per_second=self.manager.config_manager.global_settings_data['UI_Options']['refresh_rate']))+ yield self.live+ else:+ self.live=Live(self.manager.progress_manager.hash_layout, refresh_per_second=self.manager.config_manager.global_settings_data['UI_Options']['refresh_rate'])+ with self.live as live:+ yield live+diff --git a/cyberdrop_dl/managers/manager.py b/cyberdrop_dl/managers/manager.pyindex 2214280b0..095150182 100644--- a/cyberdrop_dl/managers/manager.py+++ b/cyberdrop_dl/managers/manager.py@@ -14,6 +14,7 @@ from cyberdrop_dl.managers.log_manager import LogManagerfrom cyberdrop_dl.managers.path_manager import PathManagerfrom cyberdrop_dl.managers.progress_manager import ProgressManagerfrom cyberdrop_dl.managers.hash_manager import HashManager+from cyberdrop_dl.managers.live_manager import LiveManagerfrom cyberdrop_dl.utils.args import config_definitionsfrom cyberdrop_dl.utils.dataclasses.supported_domains import SupportedDomains@@ -34,6 +35,7 @@ class Manager:self.client_manager: ClientManager = field(init=False)self.download_manager: DownloadManager = field(init=False)self.progress_manager: ProgressManager = field(init=False)+ self.live_manager: LiveManager = field(init=False)self.first_time_setup: TransitionManager = TransitionManager(self)@@ -87,6 +89,8 @@ class Manager:self.download_manager = DownloadManager(self)if not isinstance(self.hash_manager, HashManager):self.hash_manager = HashManager()+ if not isinstance(self.live_manager, LiveManager):+ self.live_manager = LiveManager(self)self.progress_manager = ProgressManager(self)await self.progress_manager.startup()@@ -96,12 +100,17 @@ class Manager: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+ #start up the db manager and hash manager only for scanningif 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()+ if not isinstance(self.live_manager, LiveManager):+ self.live_manager = LiveManager(self)+ self.progress_manager = ProgressManager(self)+ await self.progress_manager.startup()+async def args_consolidation(self) -> None:diff --git a/cyberdrop_dl/managers/progress_manager.py b/cyberdrop_dl/managers/progress_manager.pyindex 02610976e..f6a5eed56 100644--- a/cyberdrop_dl/managers/progress_manager.py+++ b/cyberdrop_dl/managers/progress_manager.py@@ -4,6 +4,8 @@ from typing import TYPE_CHECKINGfrom rich.layout import Layoutfrom cyberdrop_dl.ui.progress.downloads_progress import DownloadsProgress+from cyberdrop_dl.ui.progress.hash_progress import HashProgress+from cyberdrop_dl.ui.progress.file_progress import FileProgressfrom cyberdrop_dl.ui.progress.scraping_progress import ScrapingProgressfrom cyberdrop_dl.ui.progress.statistic_progress import DownloadStatsProgress, ScrapeStatsProgress@@ -26,10 +28,12 @@ class ProgressManager:self.download_progress: DownloadsProgress = DownloadsProgress(manager)self.download_stats_progress: DownloadStatsProgress = DownloadStatsProgress()self.scrape_stats_progress: ScrapeStatsProgress = ScrapeStatsProgress()+ self.hash_progress: HashProgress = HashProgress(manager)self.ui_refresh_rate = manager.config_manager.global_settings_data['UI_Options']['refresh_rate']self.layout: Layout = field(init=False)+ self.hash_layout: Layout = field(init=False)async def startup(self) -> None:"""Startup process for the progress manager"""@@ -45,7 +49,14 @@ class ProgressManager:Layout(renderable=await self.download_stats_progress.get_progress(), name="Download Failures", ratio=1),)+ hash_layout =Layout()+ hash_layout.split_column(+ await self.hash_progress.get_hash_progress(),+ await self.hash_progress.get_removed_progress()+ )+self.layout = progress_layout+ self.hash_layout = hash_layoutasync def print_stats(self) -> None:"""Prints the stats of the program"""diff --git a/cyberdrop_dl/ui/progress/hash_progress.py b/cyberdrop_dl/ui/progress/hash_progress.pynew file mode 100644index 000000000..dea5e0c5e--- /dev/null+++ b/cyberdrop_dl/ui/progress/hash_progress.py@@ -0,0 +1,70 @@+from typing import Tuple, TYPE_CHECKING++from rich.console import Group+from rich.panel import Panel+from rich.progress import Progress, BarColumn++if TYPE_CHECKING:+ from cyberdrop_dl.managers.manager import Manager++class HashProgress:+ """Class that keeps track of hashed files"""++ def __init__(self, manager: 'Manager'):+ self.manager = manager+ self.hash_progress = Progress("[progress.description]{task.description}",+ BarColumn(bar_width=None),+ "{task.completed} Files")+ self.remove_progress=Progress("[progress.description]{task.description}",+ BarColumn(bar_width=None),+ "{task.completed} Files")+ self.match_progress=Progress("[progress.description]{task.description}",+ BarColumn(bar_width=None),+ "{task.completed} of {task.total} Files")++++ self.hashed_files = 0+ self.prev_hash_files = 0+ self.hash_progress_group = Group(self.hash_progress)+ self.hashed_files_task_id = self.hash_progress.add_task("[green]Hashed", total=None)+ self.prev_hashed_files_task_id = self.hash_progress.add_task("[green]Previously Hashed", total=None)+++ self.removed_files=0+ self.removed_progress_group = Group(self.match_progress,self.remove_progress)+ self.removed_files_task_id = self.remove_progress.add_task("[green]Removed Files", total=None)++++ async def get_hash_progress(self) -> Panel:+ """Returns the progress bar"""+ return Panel(self.hash_progress_group, title=f"Config: {self.manager.config_manager.loaded_config}", border_style="green", padding=(1, 1))+++ async def get_removed_progress(self) -> Panel:+ """Returns the progress bar"""+ return Panel(self.removed_progress_group, border_style="green", padding=(1, 1))++ # async def update_hash(self) -> None:+ # """Updates the total number of files to be downloaded"""+ # self.hashed_file_total = self.hashed_file_total + 1+ # self.progress.update(self.completed_files_task_id, total=self.hashed_file_total)+++ async def add_completed_hash(self) -> None:+ """Adds a completed file to the progress bar"""+ self.hash_progress.advance(self.hashed_files_task_id , 1)+ self.hashed_files += 1++ async def add_prev_hash(self) -> None:+ """Adds a completed file to the progress bar"""+ self.hash_progress.advance(self.prev_hashed_files_task_id , 1)+ self.prev_hash_files += 1+++ async def add_removed_file(self) -> None:+ """Adds a completed file to the progress bar"""+ self.remove_progress.advance(self.removed_files_task_id , 1)+ self.removed_files += 1+diff --git a/cyberdrop_dl/ui/ui.py b/cyberdrop_dl/ui/ui.pyindex c3d687856..baca9ac64 100644--- a/cyberdrop_dl/ui/ui.py+++ b/cyberdrop_dl/ui/ui.py@@ -17,6 +17,8 @@ from cyberdrop_dl.ui.prompts.url_file_prompts import edit_urls_promptfrom cyberdrop_dl.ui.prompts.settings_user_prompts import create_new_config_prompt, edit_config_values_promptfrom cyberdrop_dl.clients.hash_client import HashClientfrom cyberdrop_dl.ui.prompts.settings_hash_prompts import path_prompt+from rich.live import Live+console = Console()