Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
Update utilities.py
Jacob38f06327d69a
diff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.pyindex cd5c01c84..2018d4c3a 100644--- a/cyberdrop_dl/utils/utilities.py+++ b/cyberdrop_dl/utils/utilities.py@@ -9,16 +9,16 @@ from functools import wrapsfrom pathlib import Pathfrom typing import TYPE_CHECKING, Union+import aiofiles+import appriseimport rich+from aiohttp import ClientSession, FormDatafrom rich.text import Textfrom yarl import URL-from aiohttp import ClientSession, FormData-import aiofiles-import apprisefrom cyberdrop_dl.clients.errors import NoExtensionFailure, CDLBaseException-from cyberdrop_dl.managers.real_debrid.errors import RealDebridErrorfrom cyberdrop_dl.managers.console_manager import log as log_console+from cyberdrop_dl.managers.real_debrid.errors import RealDebridErrorDEFAULT_CONSOLE_WIDTH = 240@@ -40,7 +40,7 @@ global LOG_OUTPUT_TEXTLOG_OUTPUT_TEXT = Text('')RAR_MULTIPART_PATTERN = r'^part\d+'-_7Z_FILE_EXTENSIONS = {"7z","tar","gz","bz2","zip"}+_7Z_FILE_EXTENSIONS = {"7z", "tar", "gz", "bz2", "zip"}FILE_FORMATS = {'Images': {@@ -65,6 +65,7 @@ FILE_FORMATS = {}}+def error_handling_wrapper(func):"""Wrapper handles errors for url scraping"""@@ -79,7 +80,7 @@ def error_handling_wrapper(func):e_log_message = err.messagee_origin = err.originexcept RealDebridError as err:- e_log_detail = e_log_message = f"RealDebridError - {err.error}"+ e_log_detail = e_log_message = f"RealDebridError - {err.error}"e_ui_failure = f"RD - {err.error}"except asyncio.TimeoutError:e_log_detail = e_log_message = e_ui_failure = "Timeout"@@ -91,11 +92,11 @@ def error_handling_wrapper(func):e_log_detail = str(err)e_log_message = "See Log for Details"e_ui_failure = "Unknown"- await log(f"Scrape Failed: {link} ({e_log_detail})", 40, exc_info = True)+ await log(f"Scrape Failed: {link} ({e_log_detail})", 40, exc_info=True)if not exc_info:- await log(f"Scrape Failed: {link} ({e_log_detail})", 40)- await self.manager.log_manager.write_scrape_error_log(link, e_log_message, e_origin )+ await log(f"Scrape Failed: {link} ({e_log_detail})", 40)+ await self.manager.log_manager.write_scrape_error_log(link, e_log_message, e_origin)await self.manager.progress_manager.scrape_stats_progress.add_failure(e_ui_failure)return wrapper@@ -115,7 +116,7 @@ async def log_debug(message: Union[str, Exception], level: int, sleep: int = Nonlogger_debug.log(level, message.encode('ascii', 'ignore').decode('ascii'), *kwargs)-async def log_debug_console(message: Union [str, Exception], level: int, sleep: int = None):+async def log_debug_console(message: Union[str, Exception], level: int, sleep: int = None):if CONSOLE_DEBUG_VAR:log_console(level, message.encode('ascii', 'ignore').decode('ascii'), sleep=sleep)@@ -124,7 +125,7 @@ async def log_with_color(message: str, style: str, level: int, show_in_stats: bo"""Simple logging function with color"""global LOG_OUTPUT_TEXTlogger.log(level, message, *kwargs)- text = Text (message, style = style)+ text = Text(message, style=style)if DEBUG_VAR:logger_debug.log(level, message, *kwargs)rich.print(text)@@ -136,20 +137,23 @@ async def get_log_output_text() -> str:global LOG_OUTPUT_TEXTreturn LOG_OUTPUT_TEXT-async def set_log_output_text( text = Text | str) -> str:++async def set_log_output_text(text=Text | str) -> str:global LOG_OUTPUT_TEXTif isinstance(text, str):text = Text(text)LOG_OUTPUT_TEXT = text+async def log_spacer(level: int, char: str = "-") -> None:global LOG_OUTPUT_TEXTspacer = char * min(DEFAULT_CONSOLE_WIDTH / 2, 50)rich.print(f"")- LOG_OUTPUT_TEXT.append("\n", style = 'black')- logger.log(level,spacer)+ LOG_OUTPUT_TEXT.append("\n", style='black')+ logger.log(level, spacer)if DEBUG_VAR:- logger_debug.log(level,spacer)+ logger_debug.log(level, spacer)+"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""@@ -219,6 +223,7 @@ async def get_download_path(manager: Manager, scrape_item: ScrapeItem, domain: selse:return download_dir / f"Loose Files ({domain})"+async def _is_number(ext: str):try:int(ext.rsplit(".", 1)[-1])@@ -226,6 +231,7 @@ async def _is_number(ext: str):except ValueError:return False+async def remove_id(manager: Manager, filename: str, ext: str) -> Tuple[str, str]:"""Removes the additional string some websites adds to the end of every filename"""original_filename = filename@@ -235,10 +241,10 @@ async def remove_id(manager: Manager, filename: str, ext: str) -> Tuple[str, strfilename = filename.rsplit("-", 1)[0]tail = filename.rsplit("-", 1)[-1]if re.match(RAR_MULTIPART_PATTERN, tail) and ext == ".rar" and "-" in filename:- filename , part = filename.rsplit("-", 1)+ filename, part = filename.rsplit("-", 1)filename = f"{filename}.{part}"elif await _is_number(ext) and tail in _7Z_FILE_EXTENSIONS and "-" in filename:- filename , _7z_ext = filename.rsplit("-", 1)+ filename, _7z_ext = filename.rsplit("-", 1)filename = f"{filename}.{_7z_ext}"if not filename.endswith(ext):filename = filename + ext@@ -260,7 +266,7 @@ async def purge_dir_tree(dirname: Path) -> None:try:(Path(parent) / child_dir).rmdir()except OSError:- pass #skip if folder is not empty+ pass # skip if folder is not emptyasync def check_partials_and_empty_folders(manager: Manager):@@ -278,7 +284,7 @@ async def check_partials_and_empty_folders(manager: Manager):temp_downloads = any(Path(f).is_file() for f in await manager.db_manager.temp_table.get_temp_names())if temp_downloads:await log_with_color("There are partial downloads from the previous run, please re-run the program.",- "yellow", 20)+ "yellow", 20)if not manager.config_manager.settings_data['Runtime_Options']['skip_check_for_empty_folders']:await log_with_color("Checking for empty folders...", "yellow", 20)@@ -298,7 +304,6 @@ async def check_latest_pypi(log_to_console: bool = True, call_from_ui: bool = Falatest_version = data['info']['version']releases = data['releases'].keys()-if current_version not in releases:message = "You are on an unreleased version, skipping version check"if call_from_ui:@@ -307,12 +312,11 @@ async def check_latest_pypi(log_to_console: bool = True, call_from_ui: bool = Faawait log_with_color(message, "bold_yellow", 30)return current_version, latest_version-- tags = {'dev': 'Development', 'pre': 'Pre-Release', 'post': 'Post-Release',+ tags = {'dev': 'Development', 'pre': 'Pre-Release', 'post': 'Post-Release','rc': 'Release Candidate', 'a': 'Alpha', 'b': 'Beta'}latest_version_rich = f"[b cyan]{latest_version}[/b cyan]"-+for tag in tags:if tag in current_version:match = re.match(r'(\d+)\.(\d+)\.(\d+)(?:\.([a-z]+)\d+|([a-z]+)\d+)', current_version)@@ -320,8 +324,9 @@ async def check_latest_pypi(log_to_console: bool = True, call_from_ui: bool = Famajor_version, minor_version, patch_version, dot_tag, no_dot_tag = match.groups()test_tag = dot_tag if dot_tag else no_dot_tag- rough_matches = [release for release in releases- if re.match(rf'{major_version}\.{minor_version}\.{patch_version}(\.{test_tag}\d+|{test_tag}\d+)', release)]+ rough_matches = [release for release in releases+ if re.match(+ rf'{major_version}\.{minor_version}\.{patch_version}(\.{test_tag}\d+|{test_tag}\d+)', release)]latest_testing_version = max(rough_matches, key=lambda x: int(re.search(r'(\d+)$', x).group()))latest_testing_version_rich = f"[b cyan]{latest_testing_version}[/b cyan]"@@ -333,7 +338,8 @@ async def check_latest_pypi(log_to_console: bool = True, call_from_ui: bool = Faawait log_with_color(f"{message}{latest_testing_version}", "bold_red", 30)else:if call_from_ui:- rich.print(f"You are currently on the latest {tags.get(test_tag, 'Testing').lower()} version of [b cyan]{major_version}.{minor_version}.{patch_version}[/b cyan]")+ rich.print(+ f"You are currently on the latest {tags.get(test_tag, 'Testing').lower()} version of [b cyan]{major_version}.{minor_version}.{patch_version}[/b cyan]")return current_version, latest_testing_version@@ -349,7 +355,8 @@ async def check_latest_pypi(log_to_console: bool = True, call_from_ui: bool = Fareturn current_version, latest_version-async def sent_appraise_notifications(manager: Manager) -> None:++async def sent_apprise_notifications(manager: Manager) -> None:apprise_file = manager.path_manager.config_dir / manager.config_manager.loaded_config / 'apprise.txt'text: Text = await get_log_output_text()@@ -357,67 +364,69 @@ async def sent_appraise_notifications(manager: Manager) -> None:if not apprise_file.is_file():return-+async with aiofiles.open(apprise_file, mode='r', encoding='utf8') as file:- lines = await file.readlines()+ lines = await file.readlines()lines = [line.strip() for line in lines]if not lines:return-- rich.print ('\nSending notifications.. ')++ rich.print('\nSending notifications.. ')apprise_obj = apprise.Apprise()for line in lines:- parts = line.split("://",1)[0].split('=', 1)+ parts = line.split("://", 1)[0].split('=', 1)url = linetags = 'no_logs'if len(parts) == 2:- tags, url = line.split("=",1)+ tags, url = line.split("=", 1)tags = tags.split(',')- apprise_obj.add(url, tag = tags)-+ apprise_obj.add(url, tag=tags)+results = []result = apprise_obj.notify(- body = text.plain,- title = 'Cyberdrop-DL',+ body=text.plain,+ title='Cyberdrop-DL',body_format=apprise.NotifyFormat.TEXT,- tag = 'no_logs'+ tag='no_logs')if result is not None:results += [result]result = apprise_obj.notify(- body = text.plain,- title = 'Cyberdrop-DL',+ body=text.plain,+ title='Cyberdrop-DL',body_format=apprise.NotifyFormat.TEXT,- attach = str(manager.path_manager.main_log.resolve()),- tag = 'attach_logs'+ attach=str(manager.path_manager.main_log.resolve()),+ tag='attach_logs')if result is not None:results += [result]if not results:- result = Text('No notifications sent', 'yellow')- if all (results):+ result = Text('No notifications sent', 'yellow')+ if all(results):result = Text('Success', 'green')- elif any (results):+ elif any(results):result = Text('Partial Success', 'yellow')else:- result= Text('Failed','bold red')-+ result = Text('Failed', 'bold red')+rich.print('Apprise notifications results:', result)+def parse_bytes(size: int) -> Tuple[int, str]:for unit in ["B", "KB", "MB", "GB", "TB", "PB", "EB"]:if size < 1024:- return size , unit+ return size, unitsize /= 1024- return size , "YB"+ return size, "YB"-def parse_rich_text_by_style(text: Text, style_map : dict, default_style_map_key: str = 'default'):++def parse_rich_text_by_style(text: Text, style_map: dict, default_style_map_key: str = 'default'):plain_text = ""for span in text.spans:span_text = text.plain[span.start:span.end].rstrip('\n')@@ -427,14 +436,16 @@ def parse_rich_text_by_style(text: Text, style_map : dict, default_style_map_keyreturn plain_text+STYLE_TO_DIFF_FORMAT_MAP = {- 'default': "{}",- 'green': "+ {}",- 'red': "- {}",- 'yellow': "*** {}",- }+ 'default': "{}",+ 'green': "+ {}",+ 'red': "- {}",+ 'yellow': "*** {}",+}-async def send_webhook_message( manager: Manager) -> None:++async def send_webhook_message(manager: Manager) -> None:"""Outputs the stats to a code block for webhook messages"""webhook_url: str = manager.config_manager.settings_data['Logs']['webhook_url']@@ -443,10 +454,10 @@ async def send_webhook_message( manager: Manager) -> None:returnurl = webhook_url.strip()- parts = url.split("://",1)[0].split('=', 1)+ parts = url.split("://", 1)[0].split('=', 1)tags = ['no_logs']if len(parts) == 2:- tags, url = url.split('=',1)+ tags, url = url.split('=', 1)tags = tags.split(',')url = URL(url)@@ -455,11 +466,11 @@ async def send_webhook_message( manager: Manager) -> None:main_log = manager.path_manager.main_logform = FormData()-+if 'attach_logs' in tags and main_log.is_file():if main_log.stat().st_size <= 25 * 1024 * 1024:async with aiofiles.open(main_log, "rb") as f:- form.add_field("file", await f.read() , filename=main_log.name)+ form.add_field("file", await f.read(), filename=main_log.name)else:plain_text += '\n\nWARNING: log file too large to send as attachment\n'@@ -468,7 +479,7 @@ async def send_webhook_message( manager: Manager) -> None:("content", f"```diff\n{plain_text}```"),("username", "CyberDrop-DL"),)-+# Make an asynchronous POST request to the webhookasync with ClientSession() as session:async with session.post(url, data=form) as response: