Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
fix: long UI messages for unknown error (#753)
NTFSvolumeb13f1d81ce4d
diff --git a/cyberdrop_dl/clients/errors.py b/cyberdrop_dl/clients/errors.pyindex a0f84fa73..20507ab5a 100644--- a/cyberdrop_dl/clients/errors.py+++ b/cyberdrop_dl/clients/errors.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom functools import singledispatchfrom http import HTTPStatusfrom pathlib import Path-from typing import TYPE_CHECKING, NamedTuple+from typing import TYPE_CHECKINGfrom yaml import YAMLErrorfrom yarl import URL@@ -35,73 +35,69 @@ class CDLBaseError(Exception):def __init__(self,- ui_message: str = "Something went wrong",+ ui_failure: str = "Something went wrong",*,message: str | None = None,status: str | int | None = None,origin: ScrapeItem | MediaItem | URL | Path | None = None,) -> None:- self.ui_message = ui_message- self.message = message or ui_message+ self.ui_failure = ui_failure+ self.message = message or ui_failureself.origin = get_origin(origin)super().__init__(self.message)if status:self.status = statussuper().__init__(self.status)- def __str__(self):- return self.format(self.ui_message, self.message)-- @classmethod- def format(cls, ui_message: str, message: str) -> str:- if ui_message == message:- return message- return f"{ui_message} - {message}"+ def __str__(self) -> str:+ if self.ui_failure == self.message:+ return self.message+ return f"{self.ui_failure} - {self.message}"class InvalidContentTypeError(CDLBaseError):def __init__(self, *, message: str | None = None, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when the content type isn't as expected."""- ui_message = "Invalid Content Type"- super().__init__(ui_message, message=message, origin=origin)+ ui_failure = "Invalid Content Type"+ super().__init__(ui_failure, message=message, origin=origin)class NoExtensionError(CDLBaseError):def __init__(self, *, message: str | None = None, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when no extension is given for a file."""- ui_message = "No File Extension"- super().__init__(ui_message, message=message, origin=origin)+ ui_failure = "No File Extension"+ super().__init__(ui_failure, message=message, origin=origin)class InvalidExtensionError(NoExtensionError):def __init__(self, *, message: str | None = None, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when no extension is given for a file."""super().__init__(message=message, origin=origin)- self.ui_message = "Invalid File Extension"+ self.ui_failure = "Invalid File Extension"class PasswordProtectedError(CDLBaseError):def __init__(self, message: str | None = None, *, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when a file is password protected."""- ui_message = "Password Protected"+ ui_failure = "Password Protected"msg = message or "File/Folder is password protected"- super().__init__(ui_message, message=msg, origin=origin)+ super().__init__(ui_failure, message=msg, origin=origin)class MaxChildrenError(CDLBaseError):def __init__(self, message: str | None = None, *, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when an scrape item reaches its max number or children."""- ui_message = "Max Children Reached"+ ui_failure = "Max Children Reached"msg = message or "Max number of children reached"- super().__init__(ui_message, message=msg, origin=origin)+ super().__init__(ui_failure, message=msg, origin=origin)class DDOSGuardError(CDLBaseError):def __init__(self, message: str | None = None, *, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when DDoS-Guard is detected."""- ui_message = "DDoS-Guard"+ ui_failure = "DDoS-Guard"msg = message or "DDoS-Guard detected"- super().__init__(ui_message, message=msg, origin=origin)+ super().__init__(ui_failure, message=msg, origin=origin)class DownloadError(CDLBaseError):@@ -113,38 +109,38 @@ class DownloadError(CDLBaseError):retry: bool = False,) -> None:"""This error will be thrown when a download fails."""- ui_message = create_error_msg(status)+ ui_failure = create_error_msg(status)msg = messageself.retry = retry- super().__init__(ui_message, message=msg, status=status, origin=origin)+ super().__init__(ui_failure, message=msg, status=status, origin=origin)class SlowDownloadError(DownloadError):def __init__(self, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when a file will be skipped do to a low download speed."""- ui_message = "Slow Download"- super().__init__(ui_message, origin=origin)+ ui_failure = "Slow Download"+ super().__init__(ui_failure, origin=origin)class InsufficientFreeSpaceError(CDLBaseError):def __init__(self, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when no enough storage is available."""- ui_message = "Insufficient Free Space"- super().__init__(ui_message, origin=origin)+ ui_failure = "Insufficient Free Space"+ super().__init__(ui_failure, origin=origin)class RestrictedFiletypeError(CDLBaseError):def __init__(self, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when has a filytpe not allowed by config."""- ui_message = "Restricted Filetype"- super().__init__(ui_message, origin=origin)+ ui_failure = "Restricted Filetype"+ super().__init__(ui_failure, origin=origin)class DurationError(CDLBaseError):def __init__(self, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""THis error will be thrown when the file duration is not allowed by the config."""- ui_message = "Duration Not Allowed"- super().__init__(ui_message, origin=origin)+ ui_failure = "Duration Not Allowed"+ super().__init__(ui_failure, origin=origin)class MediaFireError(CDLBaseError):@@ -152,8 +148,8 @@ class MediaFireError(CDLBaseError):self, status: str | int, message: str | None = None, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when a scrape fails."""- ui_message = f"{status} MediaFire Error"- super().__init__(ui_message, message=message, status=status, origin=origin)+ ui_failure = f"{status} MediaFire Error"+ super().__init__(ui_failure, message=message, status=status, origin=origin)class RealDebridError(CDLBaseError):@@ -163,8 +159,8 @@ class RealDebridError(CDLBaseError):url = URL(response.url)self.path = url.pathmsg = message.capitalize()- ui_message = f"{code} RealDebrid Error"- super().__init__(ui_message, message=msg, status=code, origin=url)+ ui_failure = f"{code} RealDebrid Error"+ super().__init__(ui_failure, message=msg, status=code, origin=url)class ScrapeError(CDLBaseError):@@ -172,8 +168,8 @@ class ScrapeError(CDLBaseError):self, status: str | int, message: str | None = None, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when a scrape fails."""- ui_message = create_error_msg(status)- super().__init__(ui_message, message=message, status=status, origin=origin)+ ui_failure = create_error_msg(status)+ super().__init__(ui_failure, message=message, status=status, origin=origin)class InvalidURLError(ScrapeError):@@ -181,16 +177,16 @@ class InvalidURLError(ScrapeError):self, message: str | None = None, origin: ScrapeItem | MediaItem | URL | None = None, url: URL | str = "") -> None:"""This error will be thrown when parsed URL is not valid."""- ui_message = "Invalid URL"+ ui_failure = "Invalid URL"self.url = url- super().__init__(ui_message, message=message, origin=origin)+ super().__init__(ui_failure, message=message, origin=origin)class LoginError(CDLBaseError):def __init__(self, message: str | None = None, *, origin: ScrapeItem | MediaItem | URL | None = None) -> None:"""This error will be thrown when the login fails for a site."""- ui_message = "Failed Login"- super().__init__(ui_message, message=message, origin=origin)+ ui_failure = "Failed Login"+ super().__init__(ui_failure, message=message, origin=origin)class JDownloaderError(CDLBaseError):@@ -201,6 +197,7 @@ class InvalidYamlError(CDLBaseError):def __init__(self, file: Path, e: Exception) -> None:"""This error will be thrown when a yaml config file has invalid values."""file_path = file.resolve()+ ui_failure = "Invalid YAML"msg = f"Unable to read file '{file_path}'"if isinstance(e, YAMLError):msg = f"File '{file_path}' is not a valid YAML file"@@ -211,7 +208,7 @@ class InvalidYamlError(CDLBaseError):problem = getattr(e, "problem", str(e))msg += f"\n\n{problem.capitalize()}"msg += f"\n\n{VALIDATION_ERROR_FOOTER}"- super().__init__("Invalid YAML", message=msg, origin=file)+ super().__init__(ui_failure, message=msg, origin=file)@singledispatch@@ -237,7 +234,22 @@ def get_origin(origin: ScrapeItem | Path | MediaItem | URL | None = None) -> Patreturn origin-class ErrorLogMessage(NamedTuple):- ui_msg: str+class ErrorLogMessage:+ ui_failure: strmain_log_msg: strcsv_log_msg: str++ def __init__(self, ui_failure: str, main_log_msg: str = "", csv_log_msg: str = "") -> None:+ self.ui_failure = ui_failure+ self.main_log_msg = main_log_msg or ui_failure+ self.csv_log_msg = csv_log_msg or ui_failure+ if self.csv_log_msg == "Unknown":+ self.csv_log_msg = "See Logs for details"++ @classmethod+ def from_unknown_exc(cls, e: Exception) -> ErrorLogMessage:+ e_status = getattr(e, "status", None)+ e_message = getattr(e, "message", None)+ ui_failure = create_error_msg(e_status) if e_status else "Unknown"+ log_msg = e_message or str(e)+ return ErrorLogMessage(ui_failure, log_msg)diff --git a/cyberdrop_dl/downloader/downloader.py b/cyberdrop_dl/downloader/downloader.pyindex 82ca65066..4e16a20a7 100644--- a/cyberdrop_dl/downloader/downloader.py+++ b/cyberdrop_dl/downloader/downloader.py@@ -8,7 +8,7 @@ from http import HTTPStatusfrom pathlib import Pathfrom typing import TYPE_CHECKING-from aiohttp import ClientError, ClientResponseError+from aiohttp import ClientConnectorError, ClientError, ClientResponseErrorfrom filedate import Filefrom cyberdrop_dl.clients.errors import (@@ -61,11 +61,9 @@ def retry(func: Callable) -> Callable:if e.status != 999:media_item.current_attempt += 1- full_message = str(e.status)- if e.message != full_message:- full_message = f"{e.status} - {e.message}"+ error_log_msg = ErrorLogMessage(e.ui_failure, str(e))- log_message = f"with error: {full_message}"+ log_message = f"with error: {error_log_msg.main_log_msg}"log(f"{self.log_prefix} failed: {media_item.url} {log_message}", 40)if media_item.current_attempt < max_attempts:retry_msg = f"Retrying {self.log_prefix.lower()}: {media_item.url} , retry attempt: {media_item.current_attempt + 1}"@@ -191,7 +189,7 @@ class Downloader:self.manager.progress_manager.download_progress.add_skipped()self.attempt_task_removal(media_item)- except (DownloadError, ClientResponseError, InvalidContentTypeError):+ except (DownloadError, ClientResponseError, InvalidContentTypeError, ClientConnectorError):raiseexcept (@@ -219,9 +217,9 @@ class Downloader:async def write_download_error(self, media_item: MediaItem, error_log_msg: ErrorLogMessage, exc_info=None) -> None:self.attempt_task_removal(media_item)full_message = f"{self.log_prefix} Failed: {media_item.url} ({error_log_msg.main_log_msg}) \n -> Referer: {media_item.referer}"- log(full_message, 40, exc_info=exc_info) # type: ignore- await self.manager.log_manager.write_download_error_log(media_item, error_log_msg.csv_log_msg) # type: ignore- self.manager.progress_manager.download_stats_progress.add_failure(error_log_msg.ui_msg)+ log(full_message, 40, exc_info=exc_info)+ await self.manager.log_manager.write_download_error_log(media_item, error_log_msg.csv_log_msg)+ self.manager.progress_manager.download_stats_progress.add_failure(error_log_msg.ui_failure)self.manager.progress_manager.download_progress.add_failed()@staticmethoddiff --git a/cyberdrop_dl/managers/log_manager.py b/cyberdrop_dl/managers/log_manager.pyindex fe3b93f82..b74aeeeef 100644--- a/cyberdrop_dl/managers/log_manager.py+++ b/cyberdrop_dl/managers/log_manager.py@@ -62,7 +62,9 @@ class LogManager:self.download_error_log, url=media_item.url, error=error_message, referer=media_item.referer, origin=origin)- async def write_scrape_error_log(self, url: URL, error_message: str, origin: URL | Path | None = None) -> None:+ async def write_scrape_error_log(+ self, url: URL | str, error_message: str, origin: URL | Path | None = None+ ) -> None:"""Writes to the scrape error log."""await self.write_to_csv(self.scrape_error_log, url=url, error=error_message, origin=origin)@@ -95,7 +97,7 @@ class LogManager:async with aiofiles.open(self.last_post_log, encoding="utf8") as f:reader = csv.DictReader(await f.readlines())for row in reader:- new_url = base_url = row.get("url").strip().removesuffix("/")+ new_url = base_url = row.get("url").strip().removesuffix("/") # type: ignoreif "https" in new_url and "/post-" in new_url:base_url = new_url.rsplit("/post", 1)[0]diff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.pyindex e32c8f698..670ef5c73 100644--- a/cyberdrop_dl/utils/utilities.py+++ b/cyberdrop_dl/utils/utilities.py@@ -19,7 +19,6 @@ from cyberdrop_dl.clients.errors import (CDLBaseError,ErrorLogMessage,InvalidExtensionError,- InvalidURLError,NoExtensionError,get_origin,)@@ -48,44 +47,35 @@ def error_handling_wrapper(func: Callable) -> Callable:item: ScrapeItem | MediaItem | URL = args[0]link: URL = item if isinstance(item, URL) else item.urlorigin = exc_info = None+ link_to_show: URL | str = ""try:return await func(self, *args, **kwargs)except CDLBaseError as e:- ui_failure = e.ui_message- main_log_msg = str(e)- origin = e.origin or get_origin(item)- if isinstance(e, InvalidURLError):- link: URL = e.url or link # type: ignore+ error_log_msg = ErrorLogMessage(e.ui_failure, str(e))+ origin = e.origin+ e_url: URL | str | None = getattr(e, "url", None)+ link_to_show = e_url or link_to_showexcept TimeoutError:- main_log_msg = ui_failure = "Timeout"+ error_log_msg = ErrorLogMessage("Timeout")except ClientConnectorError as e:- ui_failure = "ClientConnectorError"- main_log_msg = f"Can't connect to {link}. If you're using a VPN, try turning it off \n {e!s}"+ ui_failure = "Client Connector Error"+ # link_to_show = link.with_host(e.host) # For bunkr and jpg5, to make sure the log message matches the actual URL we tried to connect+ log_msg = f"Can't connect to {link}. If you're using a VPN, try turning it off \n {e!s}"+ error_log_msg = ErrorLogMessage(ui_failure, log_msg)except Exception as e:exc_info = e- e_status = getattr(e, "status", None)- e_message = getattr(e, "message", None)- if e_status and e_message:- main_log_msg = ui_failure = CDLBaseError.format(str(e_status), e_message)- else:- main_log_msg = str(e)- ui_failure = "Unknown"-- csv_log_msg = ui_failure- if csv_log_msg == "Unknown":- csv_log_msg = "See Log for Details"-- error_log_msg = ErrorLogMessage(ui_failure, main_log_msg, csv_log_msg)+ error_log_msg = ErrorLogMessage.from_unknown_exc(e)+ link_to_show = link_to_show or link+ origin = origin or get_origin(item)log_prefix = getattr(self, "log_prefix", None)- if log_prefix:+ if log_prefix: # This error came from a Downloaderawait self.write_download_error(item, error_log_msg, exc_info) # type: ignorereturn- log(f"Scrape Failed: {link} ({main_log_msg})", 40, exc_info=exc_info)- await self.manager.log_manager.write_scrape_error_log(link, error_log_msg.csv_log_msg, origin)- self.manager.progress_manager.scrape_stats_progress.add_failure(ui_failure)- return None+ log(f"Scrape Failed: {link_to_show} ({error_log_msg.main_log_msg})", 40, exc_info=exc_info)+ await self.manager.log_manager.write_scrape_error_log(link_to_show, error_log_msg.csv_log_msg, origin)+ self.manager.progress_manager.scrape_stats_progress.add_failure(error_log_msg.ui_failure)return wrapper@@ -151,7 +141,7 @@ def get_download_path(manager: Manager, scrape_item: ScrapeItem, domain: str) ->download_dir = manager.path_manager.download_folderif scrape_item.retry:- return scrape_item.retry_path+ return scrape_item.retry_path # type: ignoreif scrape_item.parent_title and scrape_item.part_of_album:return download_dir / scrape_item.parent_titleif scrape_item.parent_title:@@ -263,7 +253,7 @@ async def send_webhook_message(manager: Manager) -> None:returnrich.print("\nSending Webhook Notifications.. ")- url = webhook.url.get_secret_value()+ url: URL = webhook.url.get_secret_value() # type: ignoretext: Text = constants.LOG_OUTPUT_TEXTplain_text = parse_rich_text_by_style(text, constants.STYLE_TO_DIFF_FORMAT_MAP)main_log = manager.path_manager.main_log