Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: decouple exceptions from URL objects

NTFSvolumeed34172142b6
diff --git a/cyberdrop_dl/exceptions.py b/cyberdrop_dl/exceptions.py
index 1a45f608a..c99b9bce2 100644
--- a/cyberdrop_dl/exceptions.py
+++ b/cyberdrop_dl/exceptions.py
@@ -3,16 +3,29 @@ from __future__ import annotations
import dataclasses
from http import HTTPStatus
from pathlib import Path
-from typing import TYPE_CHECKING, final
+from typing import TYPE_CHECKING, Protocol, final
import yarl
if TYPE_CHECKING:
+ import datetime
from collections.abc import Sequence
from yaml import YAMLError
- from cyberdrop_dl.url_objects import MediaItem, ScrapeItem
+
+class HasParents(Protocol):
+ @property
+ def parents(self) -> Sequence[yarl.URL]: ...
+
+
+class MediaItemLike(HasParents, Protocol):
+ @property
+ def uploaded_at_date(self) -> datetime.datetime | None: ...
+ @property
+ def ext(self) -> str: ...
+ @property
+ def duration(self) -> float | None: ...
def _format_error(ui_failure: str, message: str, notes: Sequence[str] | None = None) -> str:
@@ -65,14 +78,14 @@ class CDLBaseError(Exception):
*,
message: str | None = None,
status: str | int | None = None,
- origin: ScrapeItem | MediaItem | yarl.URL | Path | None = None,
+ origin: HasParents | yarl.URL | Path | None = None,
) -> None:
- self.ui_failure = ui_failure
- self.message = message or ui_failure
- self.origin = get_origin(origin)
+ self.ui_failure: str = ui_failure
+ self.message: str = message or ui_failure
+ self.origin: Path | yarl.URL | None = get_origin(origin)
super().__init__(self.message)
if status:
- self.status = status
+ self.status: str | int | None = status
super().__init__(self.status)
def __str__(self) -> str:
@@ -86,7 +99,7 @@ class FlaresolverrError(CDLBaseError):
class InvalidContentTypeError(CDLBaseError):
- def __init__(self, *, message: str | None = None, origin: ScrapeItem | MediaItem | yarl.URL | None = None) -> None:
+ def __init__(self, *, message: str | None = None, origin: HasParents | yarl.URL | None = None) -> None:
"""This error will be thrown when the content type isn't as expected."""
ui_failure = "Invalid Content Type"
super().__init__(ui_failure, message=message, origin=origin)
@@ -96,7 +109,7 @@ class FileNameError(CDLBaseError): ...
class NoExtensionError(FileNameError):
- def __init__(self, filename: str | None = None, *, origin: ScrapeItem | MediaItem | yarl.URL | None = None) -> None:
+ def __init__(self, filename: str | None = None, *, origin: HasParents | yarl.URL | None = None) -> None:
"""This error will be thrown when no extension is given for a file."""
ui_failure = "No File Extension"
super().__init__(ui_failure, message=filename, origin=origin)
@@ -106,7 +119,7 @@ class NoExtensionError(FileNameError):
class InvalidExtensionError(NoExtensionError):
- def __init__(self, filename: str | None = None, *, origin: ScrapeItem | MediaItem | yarl.URL | None = None) -> None:
+ def __init__(self, filename: str | None = None, *, origin: HasParents | yarl.URL | None = None) -> None:
"""This error will be thrown when no extension is given for a file."""
super().__init__(filename=filename, origin=origin)
self.ui_failure = "Invalid File Extension"
@@ -120,7 +133,7 @@ class PathTraversalError(CDLBaseError):
class PasswordProtectedError(CDLBaseError):
- def __init__(self, message: str | None = None, *, origin: ScrapeItem | MediaItem | yarl.URL | None = None) -> None:
+ def __init__(self, message: str | None = None, *, origin: HasParents | yarl.URL | None = None) -> None:
"""This error will be thrown when a file is password protected."""
ui_failure = "Password Protected"
msg = message or "File/Folder is password protected"
@@ -128,7 +141,7 @@ class PasswordProtectedError(CDLBaseError):
class MaxChildrenError(CDLBaseError):
- def __init__(self, message: str | None = None, *, origin: ScrapeItem | MediaItem | yarl.URL | None = None) -> None:
+ def __init__(self, message: str | None = None, *, origin: HasParents | yarl.URL | None = None) -> None:
"""This error will be thrown when an scrape item reaches its max number or children."""
ui_failure = "Max Children Reached"
msg = message or "Max number of children reached"
@@ -136,7 +149,7 @@ class MaxChildrenError(CDLBaseError):
class DDOSGuardError(CDLBaseError):
- def __init__(self, message: str | None = None, *, origin: ScrapeItem | MediaItem | yarl.URL | None = None) -> None:
+ def __init__(self, message: str | None = None, *, origin: HasParents | yarl.URL | None = None) -> None:
"""This error will be thrown when DDoS-Guard is detected."""
ui_failure = "DDoS-Guard"
msg = message or "DDoS-Guard detected"
@@ -148,7 +161,7 @@ class DownloadError(CDLBaseError):
self,
status: str | int,
message: str | None = None,
- origin: ScrapeItem | MediaItem | yarl.URL | None = None,
+ origin: HasParents | yarl.URL | None = None,
*,
retry: bool = False,
) -> None:
@@ -160,14 +173,14 @@ class DownloadError(CDLBaseError):
class SlowDownloadError(DownloadError):
- def __init__(self, origin: ScrapeItem | MediaItem | yarl.URL | None = None) -> None:
+ def __init__(self, origin: HasParents | yarl.URL | None = None) -> None:
"""This error will be thrown when a file will be skipped do to a low download speed."""
ui_failure = "Slow Download"
super().__init__(ui_failure, origin=origin)
class InsufficientFreeSpaceError(CDLBaseError):
- def __init__(self, origin: ScrapeItem | MediaItem | yarl.URL | None = None) -> None:
+ def __init__(self, origin: HasParents | yarl.URL | None = None) -> None:
"""This error will be thrown when no enough storage is available."""
ui_failure = "Insufficient Free Space"
super().__init__(ui_failure, origin=origin)
@@ -178,7 +191,7 @@ class SkipDownloadError(CDLBaseError):
class RestrictedFiletypeError(SkipDownloadError):
- def __init__(self, origin: MediaItem) -> None:
+ def __init__(self, origin: MediaItemLike) -> None:
"""This error will be thrown when has a filetype not allowed by config."""
ui_failure = "Restricted File Ext"
message = f"File extension ({origin.ext}) ignored config options"
@@ -186,7 +199,7 @@ class RestrictedFiletypeError(SkipDownloadError):
class DurationError(SkipDownloadError):
- def __init__(self, origin: MediaItem) -> None:
+ def __init__(self, origin: MediaItemLike) -> None:
"""This error will be thrown when the file duration is not allowed by the config."""
ui_failure = "Duration Not Allowed"
message = f"File duration ({origin.duration}s) out of config range"
@@ -194,7 +207,7 @@ class DurationError(SkipDownloadError):
class RestrictedDateRangeError(SkipDownloadError):
- def __init__(self, origin: MediaItem) -> None:
+ def __init__(self, origin: MediaItemLike) -> None:
"""This error will be thrown when the publication date of the media item is not allowed by config."""
ui_failure = "Restricted DateRange"
message = f"File upload date ({origin.uploaded_at_date}s) out of config range"
@@ -203,7 +216,7 @@ class RestrictedDateRangeError(SkipDownloadError):
class ScrapeError(CDLBaseError):
def __init__(
- self, status: str | int, message: str | None = None, origin: ScrapeItem | MediaItem | yarl.URL | None = None
+ self, status: str | int, message: str | None = None, origin: HasParents | yarl.URL | None = None
) -> None:
"""This error will be thrown when a scrape fails."""
ui_failure = create_error_msg(status)
@@ -218,17 +231,17 @@ class InvalidURLError(ScrapeError):
def __init__(
self,
message: str | None = None,
- origin: ScrapeItem | MediaItem | yarl.URL | None = None,
+ origin: HasParents | yarl.URL | None = None,
url: yarl.URL | str = "",
) -> None:
"""This error will be thrown when parsed yarl.URL is not valid."""
ui_failure = "Invalid yarl.URL"
- self.url = url
+ self.url: yarl.URL | str = url
super().__init__(ui_failure, message=message, origin=origin)
class LoginError(CDLBaseError):
- def __init__(self, message: str | None = None, *, origin: ScrapeItem | MediaItem | yarl.URL | None = None) -> None:
+ def __init__(self, message: str | None = None, *, origin: HasParents | yarl.URL | None = None) -> None:
"""This error will be thrown when the login fails for a site."""
ui_failure = "Failed Login"
super().__init__(ui_failure, message=message, origin=origin)
@@ -274,24 +287,26 @@ def create_error_msg(error: int | str) -> str:
return f"Unknown ({error})"
-def get_origin(origin: ScrapeItem | Path | MediaItem | yarl.URL | None = None) -> Path | yarl.URL | None:
- if origin and not isinstance(origin, yarl.URL | Path):
- return origin.parents[0] if origin.parents else None
- return origin
+def get_origin(origin: HasParents | Path | yarl.URL | None = None) -> Path | yarl.URL | None:
+ if origin is None:
+ return None
+ if isinstance(origin, yarl.URL | Path):
+ return origin
+ return origin.parents[0] if origin.parents else None
@final
@dataclasses.dataclass(slots=True)
class CDLAppError(RuntimeError):
- ui_failure: str
- main_log_msg: str = ""
- csv_log_msg: str = ""
+ ui_error: str
+ msg: str = ""
+ csv_msg: str = ""
def __post_init__(self) -> None:
- self.main_log_msg = self.main_log_msg or self.ui_failure
- self.csv_log_msg = self.csv_log_msg or self.ui_failure
- if self.csv_log_msg == "Unknown":
- self.csv_log_msg = "See logs for details"
+ self.msg = self.msg or self.ui_error
+ self.csv_msg = self.csv_msg or self.ui_error
+ if self.csv_msg == "Unknown":
+ self.csv_msg = "See logs for details"
@staticmethod
def from_unknown_exc(e: Exception) -> CDLAppError:
diff --git a/cyberdrop_dl/url_objects.py b/cyberdrop_dl/url_objects.py
index ab3f70bd3..42a3fc00a 100644
--- a/cyberdrop_dl/url_objects.py
+++ b/cyberdrop_dl/url_objects.py
@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Any, Literal, NamedTuple, Self, final, overloa
import yarl
+from cyberdrop_dl.exceptions import MaxChildrenError
from cyberdrop_dl.utils.filepath import sanitize_folder
if TYPE_CHECKING:
@@ -261,8 +262,6 @@ class ScrapeItem:
def add_children(self, number: int = 1) -> None:
self._children_count += number
if self._children_limit and self._children_count >= self._children_limit:
- from cyberdrop_dl.exceptions import MaxChildrenError
-
raise MaxChildrenError(origin=self)
def reset(self, *, reset_parents: bool = False, reset_parent_title: bool = False) -> None:
diff --git a/cyberdrop_dl/utils/_errors.py b/cyberdrop_dl/utils/_errors.py
index 03d844357..fe9646cdc 100644
--- a/cyberdrop_dl/utils/_errors.py
+++ b/cyberdrop_dl/utils/_errors.py
@@ -187,17 +187,17 @@ def _log_error( # noqa: PLR0913
if is_downloader:
self, item = cast("Downloader", self), cast("MediaItem", item)
logger.error(
- f"{self.log_prefix} Failed: {item.url} ({app_error.main_log_msg}) \n -> Referer: {item.referer}",
+ f"{self.log_prefix} Failed: {item.url} ({app_error.msg}) \n -> Referer: {item.referer}",
exc_info=exc,
)
- self.manager.logs.write_download_error(item, app_error.csv_log_msg)
+ self.manager.logs.write_download_error(item, app_error.csv_msg)
self.manager.scrape_mapper.tui.files.stats.failed += 1
- self.manager.scrape_mapper.tui.download_errors.add(app_error.ui_failure)
+ self.manager.scrape_mapper.tui.download_errors.add(app_error.ui_error)
return
- logger.error(f"Scrape Failed: {url} ({app_error.main_log_msg})", exc_info=exc)
- self.manager.logs.write_scrape_error(url, app_error.csv_log_msg, origin) # pyright: ignore[reportArgumentType]
- self.manager.scrape_mapper.tui.scrape_errors.add(app_error.ui_failure)
+ logger.error(f"Scrape Failed: {url} ({app_error.msg})", exc_info=exc)
+ self.manager.logs.write_scrape_error(url, app_error.csv_msg, origin) # pyright: ignore[reportArgumentType]
+ self.manager.scrape_mapper.tui.scrape_errors.add(app_error.ui_error)
@overload