Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: cleanup utils (#1279)

NTFSvolume7eaa0fa3c24f
diff --git a/cyberdrop_dl/crawlers/bunkrr.py b/cyberdrop_dl/crawlers/bunkrr.py
index 20d7c3257..83e96e1c2 100644
--- a/cyberdrop_dl/crawlers/bunkrr.py
+++ b/cyberdrop_dl/crawlers/bunkrr.py
@@ -18,13 +18,7 @@ from cyberdrop_dl.crawlers.crawler import Crawler, SupportedDomains, SupportedPa
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.exceptions import DDOSGuardError, NoExtensionError, ScrapeError
from cyberdrop_dl.utils import css, open_graph
-from cyberdrop_dl.utils.utilities import (
- error_handling_wrapper,
- get_text_between,
- parse_url,
- with_suffix_encoded,
- xor_decrypt,
-)
+from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_text_between, parse_url, xor_decrypt
if TYPE_CHECKING:
from collections.abc import AsyncGenerator
@@ -113,8 +107,7 @@ class AlbumItem:
@property
def src(self) -> AbsoluteHttpURL:
src_str = self.thumbnail.replace("/thumbs/", "/")
- src = parse_url(src_str, relative_to=PRIMARY_URL)
- src = with_suffix_encoded(src, self.suffix).with_query(None)
+ src = parse_url(src_str, relative_to=PRIMARY_URL).with_suffix(self.suffix).with_query(None)
if src.suffix.lower() not in FILE_FORMATS["Images"]:
src = src.with_host(src.host.replace("i-", ""))
return override_cdn(src)
diff --git a/cyberdrop_dl/crawlers/hotpic.py b/cyberdrop_dl/crawlers/hotpic.py
index ad1bf3c6e..5591139c4 100644
--- a/cyberdrop_dl/crawlers/hotpic.py
+++ b/cyberdrop_dl/crawlers/hotpic.py
@@ -5,7 +5,7 @@ from typing import TYPE_CHECKING, ClassVar
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedDomains, SupportedPaths
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.utils import css
-from cyberdrop_dl.utils.utilities import error_handling_wrapper, with_suffix_encoded
+from cyberdrop_dl.utils.utilities import error_handling_wrapper
if TYPE_CHECKING:
from bs4 import BeautifulSoup
@@ -81,7 +81,7 @@ def thumbnail_to_img(url: AbsoluteHttpURL) -> AbsoluteHttpURL:
return url
if (new_ext := ".mp4") != url.suffix:
new_ext = ".jpg"
- url = with_suffix_encoded(url, new_ext)
+ url = url.with_suffix(new_ext)
new_parts = [p for p in url.parts if p not in ("/", "thumb")]
new_path = "/".join(new_parts)
return url.with_path(new_path)
diff --git a/cyberdrop_dl/director.py b/cyberdrop_dl/director.py
index 6986e6470..f62ad17bd 100644
--- a/cyberdrop_dl/director.py
+++ b/cyberdrop_dl/director.py
@@ -26,7 +26,8 @@ from cyberdrop_dl.utils.apprise import send_apprise_notifications
from cyberdrop_dl.utils.logger import LogHandler, QueuedLogger, log, log_spacer, log_with_color
from cyberdrop_dl.utils.sorting import Sorter
from cyberdrop_dl.utils.updates import check_latest_pypi
-from cyberdrop_dl.utils.utilities import check_partials_and_empty_folders, send_webhook_message
+from cyberdrop_dl.utils.utilities import check_partials_and_empty_folders
+from cyberdrop_dl.utils.webhook import send_webhook_message
from cyberdrop_dl.utils.yaml import handle_validation_error
if TYPE_CHECKING:
diff --git a/cyberdrop_dl/downloader/downloader.py b/cyberdrop_dl/downloader/downloader.py
index 31919e605..c2d86fee0 100644
--- a/cyberdrop_dl/downloader/downloader.py
+++ b/cyberdrop_dl/downloader/downloader.py
@@ -426,7 +426,12 @@ class Downloader:
message = str(e)
raise DownloadError(ui_message, message, retry=True) from e
- async def write_download_error(self, media_item: MediaItem, error_log_msg: ErrorLogMessage, exc_info=None) -> None:
+ def write_download_error(
+ self,
+ media_item: MediaItem,
+ error_log_msg: ErrorLogMessage,
+ exc_info: Exception | None = 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)
diff --git a/cyberdrop_dl/ui/program_ui.py b/cyberdrop_dl/ui/program_ui.py
index 2813c997f..6051efe32 100644
--- a/cyberdrop_dl/ui/program_ui.py
+++ b/cyberdrop_dl/ui/program_ui.py
@@ -19,8 +19,9 @@ from cyberdrop_dl.ui.prompts.basic_prompts import ask_dir_path, enter_to_continu
from cyberdrop_dl.ui.prompts.defaults import DONE_CHOICE, EXIT_CHOICE
from cyberdrop_dl.utils.cookie_management import clear_cookies
from cyberdrop_dl.utils.sorting import Sorter
+from cyberdrop_dl.utils.text_editor import open_in_text_editor
from cyberdrop_dl.utils.updates import check_latest_pypi
-from cyberdrop_dl.utils.utilities import clear_term, open_in_text_editor
+from cyberdrop_dl.utils.utilities import clear_term
if TYPE_CHECKING:
from collections.abc import Callable
diff --git a/cyberdrop_dl/utils/text_editor.py b/cyberdrop_dl/utils/text_editor.py
new file mode 100644
index 000000000..7f140bb90
--- /dev/null
+++ b/cyberdrop_dl/utils/text_editor.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+import os
+import platform
+import shutil
+import subprocess
+from functools import lru_cache
+from pathlib import Path
+
+import rich
+
+_TEXT_EDITORS = "micro", "nano", "vim" # Ordered by preference
+_USING_SSH = "SSH_CONNECTION" in os.environ
+_USING_DESKTOP_ENVIROMENT = any(var in os.environ for var in ("DISPLAY", "WAYLAND_DISPLAY"))
+_CUSTOM_EDITOR = os.environ.get("EDITOR")
+
+
+def open_in_text_editor(file_path: Path) -> bool | None:
+ """Opens file in OS text editor."""
+
+ if _CUSTOM_EDITOR:
+ path = shutil.which(_CUSTOM_EDITOR)
+ if not path:
+ msg = f"Editor '{_CUSTOM_EDITOR}' from env bar $EDITOR is not available"
+ raise ValueError(msg)
+ cmd = path, file_path
+
+ elif platform.system() == "Darwin":
+ cmd = "open", "-a", "TextEdit", file_path
+
+ elif platform.system() == "Windows":
+ cmd = "notepad.exe", file_path
+
+ elif _USING_DESKTOP_ENVIROMENT and not _USING_SSH and _xdg_set_default_if_none(file_path):
+ cmd = "xdg-open", file_path
+
+ elif fallback_editor := _find_text_editor():
+ cmd = fallback_editor, file_path
+ else:
+ msg = "No default text editor found"
+ raise ValueError(msg)
+
+ bin_path, *rest = cmd
+ if Path(bin_path).stem == "micro":
+ cmd = bin_path, "-keymenu", "true", *rest
+
+ rich.print(f"Opening '{file_path}' with '{bin_path}'...")
+ subprocess.call(cmd, stderr=subprocess.DEVNULL)
+
+
+@lru_cache
+def _find_text_editor() -> str | None:
+ for editor in _TEXT_EDITORS:
+ if bin_path := shutil.which(editor):
+ return bin_path
+
+
+@lru_cache
+def _xdg_set_default_if_none(file: Path) -> bool:
+ """
+ Ensures a file's MIME type has a default XDG app, falling back to whatever app is currently set for 'text/plain'
+
+ Required to open YAML files as most of the time they have no default
+
+ Returns `True` if a default app is now associated, `False` if setting the default failed
+ """
+
+ def xdg_mime_query(arg: str, *args: str) -> str:
+ cmd = "xdg-mime", "query", arg, *args
+ process = subprocess.run(cmd, capture_output=True, text=True, check=False)
+ return process.stdout.strip()
+
+ mimetype = xdg_mime_query("filetype", str(file))
+ if not mimetype:
+ return False
+
+ has_default = xdg_mime_query("default", mimetype)
+ if has_default:
+ return True
+
+ default_text_app = xdg_mime_query("default", "text/plain")
+ if not default_text_app:
+ return False
+
+ return subprocess.call(["xdg-mime", "default", default_text_app, mimetype]) == 0
diff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.py
index f4a83b995..372b36267 100644
--- a/cyberdrop_dl/utils/utilities.py
+++ b/cyberdrop_dl/utils/utilities.py
@@ -1,31 +1,25 @@
from __future__ import annotations
-import asyncio
import contextlib
+import dataclasses
import inspect
import itertools
import json
import os
import platform
import re
-import shutil
-import subprocess
import sys
import unicodedata
-from dataclasses import Field, fields
from functools import lru_cache, partial, wraps
from pathlib import Path
from stat import S_ISREG
-from typing import TYPE_CHECKING, Any, ClassVar, Concatenate, ParamSpec, Protocol, TypeGuard, TypeVar
+from typing import TYPE_CHECKING, Any, ClassVar, Concatenate, ParamSpec, Protocol, TypeGuard, TypeVar, cast, overload
-import aiofiles
-import rich
-from aiohttp import ClientConnectorError, FormData
+from aiohttp import ClientConnectorError
from pydantic import ValidationError
from yarl import URL
from cyberdrop_dl import constants
-from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.exceptions import (
CDLBaseError,
ErrorLogMessage,
@@ -36,12 +30,10 @@ from cyberdrop_dl.exceptions import (
create_error_msg,
get_origin,
)
-from cyberdrop_dl.utils.logger import log, log_debug, log_spacer, log_with_color
+from cyberdrop_dl.utils.logger import log, log_with_color
if TYPE_CHECKING:
- from collections.abc import Callable, Coroutine, Iterable, Mapping
-
- from rich.text import Text
+ from collections.abc import Callable, Coroutine, Generator, Iterable, Mapping
from cyberdrop_dl.crawlers import Crawler
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL, AnyURL, MediaItem, ScrapeItem
@@ -51,75 +43,99 @@ if TYPE_CHECKING:
CrawerOrDownloader = TypeVar("CrawerOrDownloader", bound=Crawler | Downloader)
Origin = TypeVar("Origin", bound=ScrapeItem | MediaItem | URL)
+ _P = ParamSpec("_P")
+ _T = TypeVar("_T")
+ _R = TypeVar("_R")
-P = ParamSpec("P")
-T = TypeVar("T")
-R = TypeVar("R")
+ class Dataclass(Protocol):
+ __dataclass_fields__: ClassVar[dict]
-TEXT_EDITORS = "micro", "nano", "vim" # Ordered by preference
-ALLOWED_FILEPATH_PUNCTUATION = " .-_!#$%'()+,;=@[]^{}~"
+_ALLOWED_FILEPATH_PUNCTUATION = " .-_!#$%'()+,;=@[]^{}~"
_BLOB_OR_SVG = ("data:", "blob:", "javascript:")
-subprocess_get_text = partial(subprocess.run, capture_output=True, text=True, check=False)
-class Dataclass(Protocol):
- __dataclass_fields__: ClassVar[dict]
+def error_handling_context(self: Crawler | Downloader, item: ScrapeItem | MediaItem | URL) -> Generator[None]:
+ link: URL = item if isinstance(item, URL) else item.url
+ error_log_msg = origin = exc_info = None
+ link_to_show: URL | str = ""
+ is_segment: bool = getattr(item, "is_segment", False)
+ is_downloader: bool = bool(getattr(self, "log_prefix", False))
+ try:
+ yield
+ except TooManyCrawlerErrors:
+ return
+ except CDLBaseError as e:
+ error_log_msg = ErrorLogMessage(e.ui_failure, str(e))
+ origin = e.origin
+ link_to_show: URL | str = getattr(e, "url", None) or link_to_show
+ except NotImplementedError as e:
+ error_log_msg = ErrorLogMessage("NotImplemented")
+ exc_info = e
+ except TimeoutError as e:
+ error_log_msg = ErrorLogMessage("Timeout", repr(e))
+ except ClientConnectorError as e:
+ ui_failure = "Client Connector Error"
+ suffix = "" if (link.host or "").startswith(e.host) else f" from {link}"
+ log_msg = f"{e}{suffix}. If you're using a VPN, try turning it off"
+ error_log_msg = ErrorLogMessage(ui_failure, log_msg)
+ except ValidationError as e:
+ exc_info = e
+ ui_failure = create_error_msg(422)
+ log_msg = str(e).partition("For further information")[0].strip()
+ error_log_msg = ErrorLogMessage(ui_failure, log_msg)
+ except Exception as e:
+ exc_info = e
+ error_log_msg = ErrorLogMessage.from_unknown_exc(e)
+
+ if error_log_msg is None or is_segment:
+ return
+ link_to_show = link_to_show or link
+ origin = origin or get_origin(item)
+ if is_downloader:
+ self, item = cast("Downloader", self), cast("MediaItem", item)
+ self.write_download_error(item, error_log_msg, exc_info)
+ return
+ log(f"Scrape Failed: {link_to_show} ({error_log_msg.main_log_msg})", 40, exc_info=exc_info)
+ 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)
+
+
+@overload
def error_handling_wrapper(
- func: Callable[Concatenate[CrawerOrDownloader, Origin, P], R | Coroutine[Any, Any, R]],
-) -> Callable[Concatenate[CrawerOrDownloader, Origin, P], Coroutine[Any, Any, R | None]]:
+ func: Callable[Concatenate[CrawerOrDownloader, Origin, _P], _R],
+) -> Callable[Concatenate[CrawerOrDownloader, Origin, _P], _R]: ...
+
+
+@overload
+def error_handling_wrapper(
+ func: Callable[Concatenate[CrawerOrDownloader, Origin, _P], Coroutine[None, None, _R]],
+) -> Callable[Concatenate[CrawerOrDownloader, Origin, _P], Coroutine[None, None, _R]]: ...
+
+
+def error_handling_wrapper(
+ func: Callable[Concatenate[CrawerOrDownloader, Origin, _P], _R | Coroutine[None, None, _R]],
+) -> Callable[Concatenate[CrawerOrDownloader, Origin, _P], _R | Coroutine[None, None, _R]]:
"""Wrapper handles errors for url scraping."""
+ if inspect.iscoroutinefunction(func):
+
+ @wraps(func)
+ async def async_wrapper(self: CrawerOrDownloader, item: Origin, *args: _P.args, **kwargs: _P.kwargs) -> _R:
+ with error_handling_context(self, item):
+ return await func(self, item, *args, **kwargs)
+
+ return async_wrapper
+
@wraps(func)
- async def wrapper(self: CrawerOrDownloader, item: Origin, *args: P.args, **kwargs: P.kwargs) -> R | None:
- link: URL = item if isinstance(item, URL) else item.url
- origin = exc_info = None
- link_to_show: URL | str = ""
- try:
+ def wrapper(self: CrawerOrDownloader, item: Origin, *args: _P.args, **kwargs: _P.kwargs) -> _R:
+ with error_handling_context(self, item):
result = func(self, item, *args, **kwargs)
- if inspect.isawaitable(result):
- return await result
+ assert not inspect.isawaitable(result)
return result
- except TooManyCrawlerErrors:
- return
- except CDLBaseError as e:
- error_log_msg = ErrorLogMessage(e.ui_failure, str(e))
- origin = e.origin
- link_to_show: URL | str = getattr(e, "url", None) or link_to_show
- except NotImplementedError as e:
- error_log_msg = ErrorLogMessage("NotImplemented")
- exc_info = e
- except TimeoutError as e:
- error_log_msg = ErrorLogMessage("Timeout", repr(e))
- except ClientConnectorError as e:
- ui_failure = "Client Connector Error"
- suffix = "" if (link.host or "").startswith(e.host) else f" from {link}"
- log_msg = f"{e}{suffix}. If you're using a VPN, try turning it off"
- error_log_msg = ErrorLogMessage(ui_failure, log_msg)
- except ValidationError as e:
- exc_info = e
- ui_failure = create_error_msg(422)
- log_msg = str(e).partition("For further information")[0].strip()
- error_log_msg = ErrorLogMessage(ui_failure, log_msg)
- except Exception as e:
- exc_info = e
- error_log_msg = ErrorLogMessage.from_unknown_exc(e)
-
- if (skip := getattr(item, "is_segment", None)) and skip is not None:
- return
-
- link_to_show = link_to_show or link
- origin = origin or get_origin(item)
- is_downloader = getattr(self, "log_prefix", False)
- if is_downloader:
- self.manager.task_group.create_task(self.write_download_error(item, error_log_msg, exc_info)) # type: ignore
- return
-
- log(f"Scrape Failed: {link_to_show} ({error_log_msg.main_log_msg})", 40, exc_info=exc_info)
- 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
@@ -130,7 +146,7 @@ def error_handling_wrapper(
def sanitize_unicode_emojis_and_symbols(title: str) -> str:
"""Allow all Unicode letters/numbers/marks, plus safe filename punctuation, but not symbols or emoji."""
return "".join(
- c for c in title if (c in ALLOWED_FILEPATH_PUNCTUATION or unicodedata.category(c)[0] in {"L", "N", "M"})
+ c for c in title if (c in _ALLOWED_FILEPATH_PUNCTUATION or unicodedata.category(c)[0] in {"L", "N", "M"})
).strip()
@@ -235,46 +251,36 @@ def clear_term():
os.system("cls" if os.name == "nt" else "clear")
-def convert_text_by_diff(text: Text) -> str:
- """Returns `rich.text` as a plain str with diff syntax."""
-
- STYLE_TO_DIFF = {
- "green": "+ {}",
- "red": "- {}",
- "yellow": "*** {}",
- }
-
- diff_text = ""
- default_format: str = "{}"
- for line in text.split(allow_blank=True):
- line_str = line.plain.rstrip("\n")
- first_span = line.spans[0] if line.spans else None
- style: str = str(first_span.style) if first_span else ""
- color = style.split(" ")[0] or "black" # remove console hyperlink markup (if any)
- line_format: str = STYLE_TO_DIFF.get(color) or default_format
- diff_text += line_format.format(line_str) + "\n"
-
- return diff_text
-
-
def purge_dir_tree(dirname: Path) -> None:
"""Purges empty files and directories efficiently."""
if not dirname.is_dir():
return
+ def get_size(path: Path):
+ try:
+ return path.stat().st_size
+ except (OSError, ValueError):
+ return
+
# Use os.walk() to remove empty files and directories in a single pass
for dirpath, _dirnames, filenames in os.walk(dirname, topdown=False):
dir_path = Path(dirpath)
# Remove empty files
+ has_non_empty_files = False
for file_name in filenames:
file_path = dir_path / file_name
- if file_path.exists() and file_path.stat().st_size == 0:
+ if get_size(file_path) == 0:
file_path.unlink()
+ else:
+ has_non_empty_files = True
# Remove empty directories
- with contextlib.suppress(OSError):
- dir_path.rmdir()
+ if not has_non_empty_files:
+ try:
+ dir_path.rmdir()
+ except OSError:
+ continue
def check_partials_and_empty_folders(manager: Manager):
@@ -312,119 +318,10 @@ def delete_empty_folders(manager: Manager):
purge_dir_tree(sorted_folder)
-async def send_webhook_message(manager: Manager) -> None:
- """Outputs the stats to a code block for webhook messages."""
- webhook = manager.config_manager.settings_data.logs.webhook
-
- if not webhook:
- return
-
- rich.print("\nSending Webhook Notifications.. ")
- url: AbsoluteHttpURL = webhook.url.get_secret_value() # type: ignore
- text: Text = constants.LOG_OUTPUT_TEXT
- diff_text = convert_text_by_diff(text)
- main_log = manager.path_manager.main_log
-
- form = FormData()
-
- if "attach_logs" in webhook.tags and (size := await asyncio.to_thread(get_size_or_none, main_log)):
- if size <= 25 * 1024 * 1024: # 25MB
- async with aiofiles.open(main_log, "rb") as f:
- form.add_field("file", await f.read(), filename=main_log.name)
-
- else:
- diff_text += "\n\nWARNING: log file too large to send as attachment\n"
-
- form.add_fields(
- ("content", f"```diff\n{diff_text}```"),
- ("username", "CyberDrop-DL"),
- )
-
- async with manager.client_manager._new_session() as session, session.post(url, data=form) as response:
- successful = 200 <= response.status <= 300
- result = [constants.NotificationResult.SUCCESS.value]
- result_to_log = result
- if not successful:
- json_resp: dict = await response.json()
- if "content" in json_resp:
- json_resp.pop("content")
- json_resp_str = json.dumps(json_resp, indent=4)
- result_to_log = constants.NotificationResult.FAILED.value, json_resp_str
-
- log_spacer(10, log_to_console=False)
- rich.print("Webhook Notifications Results:", *result)
- logger = log_debug if successful else log
- result_to_log = "\n".join(map(str, result_to_log))
- logger(f"Webhook Notifications Results: {result_to_log}")
-
-
-def open_in_text_editor(file_path: Path) -> bool | None:
- """Opens file in OS text editor."""
- using_ssh = "SSH_CONNECTION" in os.environ
- using_desktop_enviroment = any(var in os.environ for var in ("DISPLAY", "WAYLAND_DISPLAY"))
- custom_editor = os.environ.get("EDITOR")
-
- if custom_editor:
- path = shutil.which(custom_editor)
- if not path:
- msg = f"Editor '{custom_editor}' from env bar $EDITOR is not available"
- raise ValueError(msg)
- cmd = path, file_path
-
- elif platform.system() == "Darwin":
- cmd = "open", "-a", "TextEdit", file_path
-
- elif platform.system() == "Windows":
- cmd = "notepad.exe", file_path
-
- elif using_desktop_enviroment and not using_ssh and set_default_app_if_none(file_path):
- cmd = "xdg-open", file_path
-
- elif fallback_editor := get_first_available_editor():
- cmd = fallback_editor, file_path
- if fallback_editor.stem == "micro":
- cmd = fallback_editor, "-keymenu", "true", file_path
- else:
- msg = "No default text editor found"
- raise ValueError(msg)
-
- rich.print(f"Opening '{file_path}' with '{cmd[0]}'...")
- subprocess.call([*cmd], stderr=subprocess.DEVNULL)
-
-
-@lru_cache
-def get_first_available_editor() -> Path | None:
- for editor in TEXT_EDITORS:
- path = shutil.which(editor)
- if path:
- return Path(path)
-
-
-@lru_cache
-def set_default_app_if_none(file_path: Path) -> bool:
- mimetype = xdg_mime_query("filetype", str(file_path))
- if not mimetype:
- return False
-
- default_app = xdg_mime_query("default", mimetype)
- if default_app:
- return True
-
- text_default = xdg_mime_query("default", "text/plain")
- if text_default:
- return subprocess.call(["xdg-mime", "default", text_default, mimetype]) == 0
-
- return False
-
-
def get_valid_dict(dataclass: Dataclass | type[Dataclass], info: Mapping[str, Any]) -> dict[str, Any]:
"""Remove all keys that are not fields in the dataclass"""
- return {k: v for k, v in info.items() if k in get_field_names(dataclass)}
-
-
-@lru_cache
-def get_field_names(dataclass: Dataclass | type[Dataclass]) -> list[str]:
- return [f.name for f in fields(dataclass)]
+ fields_names = [f.name for f in dataclasses.fields(dataclass)]
+ return {name: info[name] for name in fields_names if name in info}
def get_text_between(original_text: str, start: str, end: str) -> str:
@@ -434,12 +331,6 @@ def get_text_between(original_text: str, start: str, end: str) -> str:
return original_text[start_index:end_index].strip()
-def xdg_mime_query(*args) -> str:
- assert args
- arg_list = ["xdg-mime", "query", *args]
- return subprocess_get_text(arg_list).stdout.strip()
-
-
def parse_url(link_str: str, relative_to: AbsoluteHttpURL | None = None, *, trim: bool = True) -> AbsoluteHttpURL:
"""Parse a string into an absolute URL, handling relative URLs, encoding and optionally removes trailing slash (trimming).
Raises:
@@ -449,10 +340,10 @@ def parse_url(link_str: str, relative_to: AbsoluteHttpURL | None = None, *, trim
base: AbsoluteHttpURL = relative_to # type: ignore
- def fix_query_params_encoding() -> str:
- if "?" not in link_str:
- return link_str
- parts, query_and_frag = link_str.split("?", 1)
+ def fix_query_params_encoding(link: str) -> str:
+ if "?" not in link:
+ return link
+ parts, query_and_frag = link.split("?", 1)
query_and_frag = query_and_frag.replace("+", "%20")
return f"{parts}?{query_and_frag}"
@@ -462,12 +353,13 @@ def parse_url(link_str: str, relative_to: AbsoluteHttpURL | None = None, *, trim
try:
assert link_str, "link_str is empty"
assert isinstance(link_str, str), f"link_str must be a string object, got: {link_str!r}"
- clean_link_str = fix_query_params_encoding()
- clean_link_str = fix_multiple_slashes(clean_link_str)
+ clean_link_str = fix_multiple_slashes(fix_query_params_encoding(link_str))
is_encoded = "%" in clean_link_str
new_url = URL(clean_link_str, encoded=is_encoded)
+
except (AssertionError, AttributeError, ValueError, TypeError) as e:
raise InvalidURLError(str(e), url=link_str) from e
+
if not new_url.absolute:
new_url = base.join(new_url)
if not new_url.scheme:
@@ -478,12 +370,6 @@ def parse_url(link_str: str, relative_to: AbsoluteHttpURL | None = None, *, trim
return remove_trailing_slash(new_url)
-def make_http_url(val: str, *, encoded: bool = False, strict: bool | None = None) -> AbsoluteHttpURL:
- url = URL(val, encoded=encoded, strict=strict)
- assert is_absolute_http_url(url)
- return url
-
-
def is_absolute_http_url(url: URL) -> TypeGuard[AbsoluteHttpURL]:
return url.absolute and url.scheme.startswith("http")
@@ -528,60 +414,53 @@ C = TypeVar("C", bound=HasAsyncClose | HasClose)
async def close_if_defined(obj: C) -> C:
- if not isinstance(obj, Field):
+ if not isinstance(obj, dataclasses.Field):
await obj.close() if inspect.iscoroutinefunction(obj.close) else obj.close()
return constants.NOT_DEFINED
-def with_suffix_encoded(url: AnyURL, suffix: str) -> AnyURL:
- name = Path(url.raw_name).with_suffix(suffix)
- return url.parent.joinpath(str(name), encoded=True).with_query(url.query).with_fragment(url.fragment)
-
-
@lru_cache
def get_system_information() -> str:
+ def get_common_name() -> str:
+ system = platform.system()
+
+ if system in ("Linux",):
+ try:
+ return platform.freedesktop_os_release()["PRETTY_NAME"]
+ except OSError:
+ pass
+
+ if system == "Android" and sys.version_info >= (3, 13):
+ ver = platform.android_ver()
+ os_name = f"{system} {ver.release}"
+ for component in (ver.manufacturer, ver.model, ver.device):
+ if component:
+ os_name += f" ({component})"
+ return os_name
+
+ default = platform.platform(aliased=True, terse=True).replace("-", " ")
+ if system == "Windows" and (edition := platform.win32_edition()):
+ return f"{default} {edition}"
+ return default
+
system_info = platform.uname()._asdict() | {
"architecture": str(platform.architecture()),
"python": f"{platform.python_version()} {platform.python_implementation()}",
- "common_name": get_os_common_name(),
+ "common_name": get_common_name(),
}
_ = system_info.pop("node", None)
return json.dumps(system_info, indent=4)
-@lru_cache
-def get_os_common_name() -> str:
- system = platform.system()
-
- if system in ("Linux",):
- try:
- return platform.freedesktop_os_release()["PRETTY_NAME"]
- except OSError:
- pass
-
- if system == "Android" and sys.version_info >= (3, 13):
- ver = platform.android_ver()
- os_name = f"{system} {ver.release}"
- for component in (ver.manufacturer, ver.model, ver.device):
- if component:
- os_name += f" ({component})"
- return os_name
-
- default = platform.platform(aliased=True, terse=True).replace("-", " ")
- if system == "Windows" and (edition := platform.win32_edition()):
- return f"{default} {edition}"
- return default
-
-
def is_blob_or_svg(link: str) -> bool:
return any(link.startswith(x) for x in _BLOB_OR_SVG)
-def unique(iterable: Iterable[T], *, hashable: bool = True) -> Iterable[T]:
+def unique(iterable: Iterable[_T], *, hashable: bool = True) -> Iterable[_T]:
"""Yields unique values from iterable, keeping original order"""
if hashable:
- seen: set[T] | list[T] = set()
- add: Callable[[T], None] = seen.add
+ seen: set[_T] | list[_T] = set()
+ add: Callable[[_T], None] = seen.add
else:
seen = []
add = seen.append
@@ -592,7 +471,9 @@ def unique(iterable: Iterable[T], *, hashable: bool = True) -> Iterable[T]:
yield value
-def get_valid_kwargs(func: Callable[..., Any], kwargs: Mapping[str, T], accept_kwargs: bool = True) -> Mapping[str, T]:
+def get_valid_kwargs(
+ func: Callable[..., Any], kwargs: Mapping[str, _T], accept_kwargs: bool = True
+) -> Mapping[str, _T]:
"""Get the subset of ``kwargs`` that are valid params for ``func`` and their values are not `None`
If func takes **kwargs, returns everything"""
@@ -603,11 +484,11 @@ def get_valid_kwargs(func: Callable[..., Any], kwargs: Mapping[str, T], accept_k
return {k: v for k, v in kwargs.items() if k in params.keys() and v is not None}
-def call_w_valid_kwargs(cls: Callable[..., R], kwargs: Mapping[str, Any]) -> R:
+def call_w_valid_kwargs(cls: Callable[..., _R], kwargs: Mapping[str, Any]) -> _R:
return cls(**get_valid_kwargs(cls, kwargs))
-def type_adapter(func: Callable[..., R], aliases: dict[str, str] | None = None) -> Callable[[dict[str, Any]], R]:
+def type_adapter(func: Callable[..., _R], aliases: dict[str, str] | None = None) -> Callable[[dict[str, Any]], _R]:
"""Like `pydantic.TypeAdapter`, but without type validation of attributes (faster)
Ignores attributes with `None` as value"""
diff --git a/cyberdrop_dl/utils/webhook.py b/cyberdrop_dl/utils/webhook.py
new file mode 100644
index 000000000..cb52304fa
--- /dev/null
+++ b/cyberdrop_dl/utils/webhook.py
@@ -0,0 +1,90 @@
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING, Any, cast
+
+import aiofiles
+import rich
+from aiohttp import FormData
+
+from cyberdrop_dl import constants
+from cyberdrop_dl.utils import aio
+from cyberdrop_dl.utils.logger import log, log_debug, log_spacer
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
+ from cyberdrop_dl.managers.manager import Manager
+ from cyberdrop_dl.models.base_models import HttpAppriseURL
+
+
+_DEFAULT_DIFF_LINE_FORMAT: str = "{}"
+_STYLE_TO_DIFF_MAP = {
+ "green": "+ {}",
+ "red": "- {}",
+ "yellow": "*** {}",
+}
+
+
+def _prepare_diff_text() -> str:
+ """Returns the `rich.text` in the current log buffer as a plain str with diff syntax."""
+
+ def prepare_lines():
+ for text_line in constants.LOG_OUTPUT_TEXT.split(allow_blank=True):
+ line_str = text_line.plain.rstrip("\n")
+ first_span = text_line.spans[0] if text_line.spans else None
+ style: str = str(first_span.style) if first_span else ""
+
+ color = style.split(" ")[0] or "black" # remove console hyperlink markup (if any)
+ line_format: str = _STYLE_TO_DIFF_MAP.get(color) or _DEFAULT_DIFF_LINE_FORMAT
+ yield line_format.format(line_str)
+
+ return "\n".join(prepare_lines())
+
+
+async def _prepare_form(webhook: HttpAppriseURL, main_log: Path) -> FormData:
+ diff_text = _prepare_diff_text()
+ form = FormData()
+
+ if "attach_logs" in webhook.tags and (size := await aio.get_size(main_log)):
+ if size <= 25 * 1024 * 1024: # 25MB
+ async with aiofiles.open(main_log, "rb") as f:
+ form.add_field("file", await f.read(), filename=main_log.name)
+
+ else:
+ diff_text += "\n\nWARNING: log file too large to send as attachment\n"
+
+ form.add_fields(
+ ("content", f"```diff\n{diff_text}```"),
+ ("username", "CyberDrop-DL"),
+ )
+ return form
+
+
+async def send_webhook_message(manager: Manager) -> None:
+ """Outputs the stats to a code block for webhook messages."""
+ webhook = manager.config_manager.settings_data.logs.webhook
+
+ if not webhook:
+ return
+
+ rich.print("\nSending Webhook Notifications.. ")
+ url = cast("AbsoluteHttpURL", webhook.url.get_secret_value())
+ form = await _prepare_form(webhook, manager.path_manager.main_log)
+
+ async with manager.client_manager._new_session() as session, session.post(url, data=form) as response:
+ result = [constants.NotificationResult.SUCCESS.value]
+ result_to_log = result
+ if not response.ok:
+ json_resp: dict[str, Any] = await response.json()
+ if "content" in json_resp:
+ json_resp.pop("content")
+ resp_text = json.dumps(json_resp, indent=4, ensure_ascii=False)
+ result_to_log = constants.NotificationResult.FAILED.value, resp_text
+
+ log_spacer(10, log_to_console=False)
+ rich.print("Webhook Notifications Results:", *result)
+ logger = log_debug if response.ok else log
+ result_to_log = "\n".join(map(str, result_to_log))
+ logger(f"Webhook Notifications Results: {result_to_log}")