Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: redefine cdl errors

NTFSvolumeecf6a80245a9
diff --git a/cyberdrop_dl/clients/errors.py b/cyberdrop_dl/clients/errors.py
index 57e76e512..96d2518aa 100644
--- a/cyberdrop_dl/clients/errors.py
+++ b/cyberdrop_dl/clients/errors.py
@@ -1,88 +1,80 @@
-from typing import TYPE_CHECKING
-from pathlib import Path
-from yaml.constructor import ConstructorError
+from typing import TYPE_CHECKING, Optional
+from http import HTTPStatus
if TYPE_CHECKING:
from cyberdrop_dl.scraper.crawler import ScrapeItem
-
-class InvalidContentTypeFailure(Exception):
- """This error will be thrown when the content type isn't as expected"""
-
- def __init__(self, *, message: str = "Invalid content type"):
- self.message = message
- super().__init__(self.message)
-
-class InvalidYamlConfig(Exception):
- """This error will be thrown when a yaml config file has invalid values"""
-
- def __init__(self, file: Path, e: ConstructorError):
- self.file = file
- mark = e.problem_mark if hasattr(e, 'problem_mark') else e
- self.message = f"ERROR: File '{file}' has an invalid config. Please verify and edit it manually\n {mark}"
- self.message_rich = self.message.replace("ERROR:", "[bold red]ERROR:[/bold red]")
- super().__init__(self.message)
-
-
-class NoExtensionFailure(Exception):
- """This error will be thrown when no extension is given for a file"""
-
- def __init__(self, *, message: str = "Extension missing for file"):
- self.message = message
- super().__init__(self.message)
-
-
-class PasswordProtected(Exception):
- """This error will be thrown when a file is password protected"""
-
- def __init__(self,/, scrape_item: 'ScrapeItem'):
- self.message = "File/Folder is password protected"
- self.scrape_item = scrape_item
+ from yaml.constructor import ConstructorError
+ from yarl import URL
+ from pathlib import Path
+
+class CDLBaseException(Exception):
+ """Base exception for cyberdrop-dl errors"""
+
+ def __init__(self, ui_message: str = "Something went wrong", *, message: Optional[str] = None , status: Optional[int]=None, origin: Optional[ScrapeItem | URL | Path] = None):
+ self.ui_message = ui_message
+ self.message = message if message else ui_message
+ self.origin = origin
+ if isinstance(origin, ScrapeItem):
+ self.origin = origin.parents[0] if origin.parents else None
super().__init__(self.message)
+ if status:
+ self.status = status
+ super().__init__(self.status)
+class InvalidContentTypeFailure(CDLBaseException):
+ def __init__(self, *, message: str = "Invalid Content Type", origin: Optional[ScrapeItem | URL] = 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)
-class DDOSGuardFailure(Exception):
- """This error will be thrown when DDoS-Guard is detected"""
-
- def __init__(self, status: int, message: str = "DDoS-Guard detected"):
- self.status = status
- self.message = message
- super().__init__(self.message)
- super().__init__(self.status)
-
+class NoExtensionFailure(CDLBaseException):
+ def __init__(self, *, message: str = "No File Extension", origin: Optional[ScrapeItem | URL] = 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)
-class DownloadFailure(Exception):
- """This error will be thrown when a request fails"""
- def __init__(self, status: int, message: str = "Something went wrong"):
- self.status = status
- self.message = message
- super().__init__(self.message)
- super().__init__(self.status)
+class PasswordProtected(CDLBaseException):
+ def __init__(self, *, message: str = "File/Folder is password protected", origin: Optional[ScrapeItem | URL] = None ):
+ """This error will be thrown when a file is password protected"""
+ ui_message = "Password Protected"
+ super().__init__(ui_message, message = message, origin=origin)
-class ScrapeFailure(Exception):
- """This error will be thrown when a request fails"""
+class DDOSGuardFailure(CDLBaseException):
+ def __init__(self, *, message: str = "DDoS-Guard detected", origin: Optional[ScrapeItem | URL] = None):
+ """This error will be thrown when DDoS-Guard is detected"""
+ ui_message = "DDoS-Guard"
+ super().__init__(ui_message, message = message, origin=origin)
- def __init__(self, status: int, message: str = "Something went wrong"):
- self.status = status
- self.message = message
- super().__init__(self.message)
- super().__init__(self.status)
+class DownloadFailure(CDLBaseException):
+ def __init__(self, status: int, message: Optional[str] = "Download Failure" , origin: Optional[ScrapeItem | URL] = None):
+ """This error will be thrown when a request fails"""
+ ui_message = f"{status} {HTTPStatus(status).phrase}"
+ super().__init__(ui_message, message = message, status = status, origin=origin)
-class FailedLoginFailure(Exception):
- """This error will be thrown when the login fails for a site"""
+class ScrapeFailure(CDLBaseException):
+ def __init__(self, status: int, message: Optional[str] = "Scrape Failure" , origin: Optional[ScrapeItem | URL] = None):
+ """This error will be thrown when a scrape fails"""
+ ui_message = f"{status} {HTTPStatus(status).phrase}"
+ super().__init__(ui_message, message = message, status = status, origin=origin)
- def __init__(self, *, status: int, message: str = "Failed login."):
- self.status = status
- self.message = message
- super().__init__(self.message)
- super().__init__(self.status)
+class FailedLoginFailure(CDLBaseException):
+ def __init__(self, *, message: str = "Failed Login", origin: Optional[ScrapeItem | URL] = 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)
-class JDownloaderFailure(Exception):
- """Basic failure template for JDownloader"""
+class JDownloaderFailure(CDLBaseException):
+ """This error will be thrown for any Jdownloader error"""
+ pass
- def __init__(self, message: str = "Something went wrong"):
- self.message = message
- super().__init__(self.message)
+class InvalidYamlConfig(CDLBaseException):
+ def __init__(self, file: Path, e: ConstructorError):
+ """This error will be thrown when a yaml config file has invalid values"""
+ mark = e.problem_mark if hasattr(e, 'problem_mark') else e
+ message = f"ERROR: File '{file}' has an invalid config. Please verify and edit it manually\n {mark}"
+ self.message_rich = message.replace("ERROR:", "[bold red]ERROR:[/bold red]")
+ super().__init__('Invalid YAML', message = message, origin = file)
diff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.py
index 2aaecb106..7ae19f5f8 100644
--- a/cyberdrop_dl/utils/utilities.py
+++ b/cyberdrop_dl/utils/utilities.py
@@ -12,16 +12,15 @@ from typing import TYPE_CHECKING, Union
import rich
from yarl import URL
-from cyberdrop_dl.clients.errors import NoExtensionFailure, FailedLoginFailure, InvalidContentTypeFailure, \
- PasswordProtected
+from cyberdrop_dl.clients.errors import NoExtensionFailure, CDLBaseException
from cyberdrop_dl.managers.real_debrid.errors import RealDebridError
from cyberdrop_dl.managers.console_manager import log as log_console
if TYPE_CHECKING:
from typing import Tuple
-
from cyberdrop_dl.managers.manager import Manager
from cyberdrop_dl.utils.dataclasses.url_objects import ScrapeItem
+ from cyberdrop_dl.scraper.crawler import Crawler
logger = logging.getLogger("cyberdrop_dl")
logger_debug = logging.getLogger("cyberdrop_dl_debug")
@@ -60,54 +59,36 @@ FILE_FORMATS = {
}
}
-
def error_handling_wrapper(func):
"""Wrapper handles errors for url scraping"""
@wraps(func)
- async def wrapper(self, *args, **kwargs):
+ async def wrapper(self: Crawler, *args, **kwargs):
link = args[0] if isinstance(args[0], URL) else args[0].url
-
+ e_origin = exc_info = None
try:
return await func(self, *args, **kwargs)
- except NoExtensionFailure:
- await log(f"Scrape Failed: {link} (No File Extension)", 40)
- await self.manager.log_manager.write_scrape_error_log(link, " No File Extension")
- await self.manager.progress_manager.scrape_stats_progress.add_failure("No File Extension")
- except PasswordProtected as e:
- await log(f"Scrape Failed: {link} (Password Protected)", 40)
- parent_url = e.scrape_item.parents[0] if e.scrape_item.parents else None
- await self.manager.log_manager.write_unsupported_urls_log(link,parent_url)
- await self.manager.progress_manager.scrape_stats_progress.add_failure("Password Protected")
- except RealDebridError as e:
- await log(f"Scrape Failed: {link} (RealDebridError): {e.error}", 40)
- await self.manager.log_manager.write_scrape_error_log(link, f" {e.error}")
- await self.manager.progress_manager.scrape_stats_progress.add_failure(f"RD - {e.error}")
- except FailedLoginFailure:
- await log(f"Scrape Failed: {link} (Failed Login)", 40)
- await self.manager.log_manager.write_scrape_error_log(link, " Failed Login")
- await self.manager.progress_manager.scrape_stats_progress.add_failure("Failed Login")
- except InvalidContentTypeFailure:
- await log(f"Scrape Failed: {link} (Invalid Content Type Received)", 40)
- await self.manager.log_manager.write_scrape_error_log(link, " Invalid Content Type Received")
- await self.manager.progress_manager.scrape_stats_progress.add_failure("Invalid Content Type")
+ except CDLBaseException as err:
+ e_log_detail = e_ui_failure = err.ui_message
+ e_log_message = err.message
+ e_origin = err.origin
+ except RealDebridError as err:
+ e_log_detail = e_log_message = f"RealDebridError - {err.error}"
+ e_ui_failure = f"RD - {err.error}"
except asyncio.TimeoutError:
- await log(f"Scrape Failed: {link} (Timeout)", 40)
- await self.manager.log_manager.write_scrape_error_log(link, " Timeout")
- await self.manager.progress_manager.scrape_stats_progress.add_failure("Timeout")
- except Exception as e:
- if hasattr(e, 'status'):
- if hasattr(e, 'message'):
- await log(f"Scrape Failed: {link} ({e.status} - {e.message})", 40)
- await self.manager.log_manager.write_scrape_error_log(link, f" {e.status} - {e.message}")
- else:
- await log(f"Scrape Failed: {link} ({e.status})", 40)
- await self.manager.log_manager.write_scrape_error_log(link, f" {e.status}")
- await self.manager.progress_manager.scrape_stats_progress.add_failure(e.status)
+ e_log_detail = e_log_message = e_ui_failure = "Timeout"
+ except Exception as err:
+ exc_info = True
+ if hasattr(err, 'status') and hasattr(err, 'message'):
+ e_log_detail = e_log_message = e_ui_failure = f"{err.status} - {err.message}"
else:
- await log(f"Scrape Failed: {link} ({e})", 40, exc_info=True)
- await self.manager.log_manager.write_scrape_error_log(link, " See Log for Details")
- await self.manager.progress_manager.scrape_stats_progress.add_failure("Unknown")
+ 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 = exc_info)
+ 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