Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: send plain notifications + tests (#118)
NTFSvolume2d4cd5a2293e
diff --git a/cyberdrop_dl/__main__.py b/cyberdrop_dl/__main__.pyindex 4038f4f57..143457d27 100644--- a/cyberdrop_dl/__main__.py+++ b/cyberdrop_dl/__main__.py@@ -7,7 +7,7 @@ from typing import TYPE_CHECKINGfrom rich.traceback import install as install_rich_tracebacks-from cyberdrop_dl import aio, storage+from cyberdrop_dl import aio, storage, webhookfrom cyberdrop_dl.managers.manager import Managerfrom cyberdrop_dl.scraper.scrape_mapper import ScrapeMapperfrom cyberdrop_dl.ui import program_ui@@ -16,7 +16,6 @@ from cyberdrop_dl.utils.apprise import send_apprise_notificationsfrom cyberdrop_dl.utils.logger import log_spacer, setup_loggingfrom cyberdrop_dl.utils.sorting import Sorterfrom cyberdrop_dl.utils.utilities import check_partials_and_empty_folders-from cyberdrop_dl.utils.webhook import send_webhook_messageif TYPE_CHECKING:from collections.abc import Sequence@@ -41,7 +40,7 @@ async def _scrape(manager: Manager) -> None:await _runtime(manager)await _post_runtime(manager)- manager.progress_manager.print_stats(start_time)+ stats = manager.progress_manager.print_stats(start_time)log_spacer()check_latest_pypi()@@ -49,7 +48,9 @@ async def _scrape(manager: Manager) -> None:logger.info("Closing program...")logger.info("Finished downloading. Enjoy :)", extra={"color": "green"})- await send_webhook_message(manager)+ if manager.config.logs.webhook:+ await webhook.send_notification(manager.config.logs.webhook, stats)+await send_apprise_notifications(manager)@@ -61,7 +62,7 @@ async def _runtime(manager: Manager) -> None:async def _post_runtime(manager: Manager) -> None:- """Actions to complete after main runtime, and before ui shutdown."""+ """Actions to complete after main runtime, and before UI shutdown."""log_spacer()logger.info("Running Post-Download Processes", extra={"color": "green"})@@ -92,7 +93,11 @@ def main(args: Sequence[str] | None = None) -> str | int | None:exit_code = 1with contextlib.suppress(Exception):- aio.run(_run(manager))+ try:+ aio.run(_run(manager))+ except KeyboardInterrupt:+ logger.info("Exiting (Ctrl + C) ...")+exit_code = 0return exit_codediff --git a/cyberdrop_dl/managers/progress_manager.py b/cyberdrop_dl/managers/progress_manager.pyindex 3d2f7c798..bb20ff831 100644--- a/cyberdrop_dl/managers/progress_manager.py+++ b/cyberdrop_dl/managers/progress_manager.py@@ -21,7 +21,7 @@ from cyberdrop_dl.ui.progress.hash_progress import HashProgressfrom cyberdrop_dl.ui.progress.scraping_progress import ScrapingProgressfrom cyberdrop_dl.ui.progress.sort_progress import SortProgressfrom cyberdrop_dl.ui.progress.statistic_progress import DownloadStatsProgress, ScrapeStatsProgress-from cyberdrop_dl.utils.logger import log_spacer+from cyberdrop_dl.utils.logger import capture_logs, log_spacerif TYPE_CHECKING:from collections.abc import AsyncGenerator, Sequence@@ -113,16 +113,24 @@ class ProgressManager:return self.vertical_layoutreturn self.horizontal_layout- def print_stats(self, start_time: float) -> None:- """Prints the stats of the program."""+ def print_stats(self, start_time: float) -> str:if not self.manager.parsed_args.cli_only_args.print_stats:- return+ return ""++ log_spacer()+ logger.info("Printing Stats...\n")++ with capture_logs() as stream:+ self._print_stats(start_time)++ return stream.getvalue()++ def _print_stats(self, start_time: float) -> None:+end_time = time.perf_counter()runtime = timedelta(seconds=int(end_time - start_time))total_data_written = ByteSize(self.file_progress.total_data_written).human_readable(decimal=True)- log_spacer()- logger.info("Printing Stats...\n")config_path = self.manager.appdata.configs / self.manager.config_manager.loaded_configconfig_path_text = get_console_hyperlink(config_path, text=self.manager.config_manager.loaded_config)input_file_text = get_input(self.manager)diff --git a/cyberdrop_dl/utils/logger.py b/cyberdrop_dl/utils/logger.pyindex cba1632e0..a4f0d30de 100644--- a/cyberdrop_dl/utils/logger.py+++ b/cyberdrop_dl/utils/logger.py@@ -29,7 +29,7 @@ _DEFAULT_CONSOLE = Console()_USER_NAME = Path.home().name_DEFAULT_CONSOLE_WIDTH = 240_MAIN_LOG_LISTENER: ContextVar[QueueListener] = ContextVar("_MAIN_LOGGER_LISTENER")-_MAIN_LOG_FILE: ContextVar[Path] = ContextVar("_MAIN_LOGGER_FILE")+MAIN_LOG_FILE: ContextVar[Path] = ContextVar("_MAIN_LOGGER_FILE")if TYPE_CHECKING:@@ -267,11 +267,11 @@ def setup_logging(file: Path, /, level: int = logging.DEBUG) -> Generator[None]:),):logger.info(f"Debug log file: '{debug_log_file}'")- token = _MAIN_LOG_FILE.set(file)+ token = MAIN_LOG_FILE.set(file)try:yieldfinally:- _MAIN_LOG_FILE.reset(token)+ MAIN_LOG_FILE.reset(token)@contextlib.contextmanager@@ -285,10 +285,14 @@ def _setup_debug_logger() -> Generator[Path | None]:if env.DEBUG_LOG_FOLDER:debug_log_folder = Path(env.DEBUG_LOG_FOLDER)- if not debug_log_folder.is_dir():+ if not debug_log_folder.exists():msg = f"Value of env var 'CDL_DEBUG_LOG_FOLDER' is invalid. Folder '{debug_log_folder}' does not exists"raise FileNotFoundError(None, msg, env.DEBUG_LOG_FOLDER)+ if not debug_log_folder.is_dir():+ msg = f"Value of env var 'CDL_DEBUG_LOG_FOLDER' is invalid. Folder '{debug_log_folder}' should a directory"+ raise NotADirectoryError(None, msg, env.DEBUG_LOG_FOLDER)+now = datetime.now().strftime("%Y%m%d_%H%M%S")debug_log_file = debug_log_folder / f"cyberdrop_dl_debug_{now}.log"@@ -317,11 +321,11 @@ def capture_logs() -> Generator[StringIO]:logger.removeHandler(in_memory_handler)-def export_logs(*, size_limit: int | None = None) -> bytes:+def export_logs(*, size_limit: float | None = None) -> bytes:flush_logs()- log_file = _MAIN_LOG_FILE.get()+ log_file = MAIN_LOG_FILE.get()if size_limit and log_file.stat().st_size > size_limit:- raise RuntimeError(f"Logs file '{log_file}' it's too big. Max size expected: {size_limit}")+ raise RuntimeError(f"Logs file '{log_file}' is too big. Max size expected: {size_limit}")return log_file.read_bytes()diff --git a/cyberdrop_dl/utils/webhook.py b/cyberdrop_dl/utils/webhook.pydeleted file mode 100644index 3d81f3e05..000000000--- a/cyberdrop_dl/utils/webhook.py+++ /dev/null@@ -1,96 +0,0 @@-from __future__ import annotations--import json-import logging-from typing import TYPE_CHECKING, Any--import aiofiles-import rich-from aiohttp import FormData--from cyberdrop_dl import aio, constants-from cyberdrop_dl.utils.logger import log_spacer--if TYPE_CHECKING:- from pathlib import Path-- from cyberdrop_dl.managers.manager import Manager- from cyberdrop_dl.models import AppriseURL--logger = logging.getLogger(__name__)-_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: AppriseURL, 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.logs.webhook-- if not webhook:- return-- rich.print("\nSending Webhook Notifications.. ")- url = str(webhook.url.get_secret_value())- form = await _prepare_form(webhook, manager.config.logs.main_log)-- result = constants.NotificationResult.FAILED.value-- try:- async with manager.client_manager.create_aiohttp_session() as session, session.post(url, data=form) as response:- if response.ok:- result = constants.NotificationResult.SUCCESS.value- result_to_log = [result]-- else:- json_resp: dict[str, Any] = await response.json()- json_resp.pop("content", None)- resp_text = json.dumps(json_resp, indent=4, ensure_ascii=False)- result_to_log = constants.NotificationResult.FAILED.value, resp_text-- except Exception as e:- logger.exception("Unable to send webhook notification")- result_to_log = result, str(e)-- log_spacer()- rich.print("Webhook Notifications Results:", result)- result_to_log = "\n".join(map(str, result_to_log))- logger.info(f"Webhook Notifications Results: {result_to_log}")diff --git a/cyberdrop_dl/webhook.py b/cyberdrop_dl/webhook.pynew file mode 100644index 000000000..b50c7066e--- /dev/null+++ b/cyberdrop_dl/webhook.py@@ -0,0 +1,59 @@+from __future__ import annotations++import asyncio+import logging+from typing import TYPE_CHECKING, Any++import aiohttp++from cyberdrop_dl.utils.logger import MAIN_LOG_FILE, export_logs, log_spacer++if TYPE_CHECKING:+ import yarl++ from cyberdrop_dl.models import AppriseURL+++logger = logging.getLogger(__name__)+++async def send_notification(webhook: AppriseURL, body: str) -> None:+ log_spacer()+ url, form = await _prepare(webhook)+ form.add_field("content", body)+ await _send_notification(url, form)+++async def _prepare(webhook: AppriseURL) -> tuple[str, aiohttp.FormData]:+ url = str(webhook.url.get_secret_value())+ form = aiohttp.FormData()+ if webhook.attach_logs:+ try:+ logs = await asyncio.to_thread(export_logs, size_limit=25 * 1e6)+ except Exception:+ logger.exception("Unable to attach log for webhook notification")+ else:+ form.add_field("file", logs, filename=MAIN_LOG_FILE.get().name)++ form.add_field("username", "cyberdrop-dl")+ return url, form+++async def _send_notification(url: yarl.URL | str, form: aiohttp.FormData) -> None:+ logger.info("Sending webhook notifications.. ")+ try:+ async with aiohttp.request("POST", url, data=form) as response:+ if response.ok:+ logger.info("Webhook notifications: Success", extra={"color": "green"})+ else:+ try:+ error: dict[str, Any] = await response.json()+ except Exception:+ response.raise_for_status()+ raise+ else:+ _ = error.pop("content", None)+ logger.error(f"Webhook notification failed: {error}", extra={"color": "red"})++ except Exception:+ logger.exception("Unable to send webhook notification")diff --git a/tests/test_webhook.py b/tests/test_webhook.pynew file mode 100644index 000000000..326f91a53--- /dev/null+++ b/tests/test_webhook.py@@ -0,0 +1,71 @@+from __future__ import annotations++import contextlib+from typing import TYPE_CHECKING+from unittest.mock import AsyncMock, MagicMock, patch++import aiohttp++from cyberdrop_dl.models import AppriseURL+from cyberdrop_dl.webhook import send_notification++if TYPE_CHECKING:+ from collections.abc import Generator++ import pytest++webhook = AppriseURL.model_validate({"url": "https://example.com/webhook", "tags": {"no_logs"}})+++def _mock_aiohttp_request(mock_response: AsyncMock) -> Generator[None]:+ with patch("aiohttp.request") as mock_request:+ mock_request.return_value.__aenter__.return_value = mock_response+ yield+++async def test_send_webhook_success(caplog: pytest.LogCaptureFixture) -> None:+ mock_response = AsyncMock()+ mock_response.ok = True+ mock_response.status = 200++ with _mock_aiohttp_request(mock_response):+ with caplog.at_level(10):+ await send_notification(webhook, "test")++ assert "Webhook notifications: Success" in caplog.text+++async def test_send_webhook_failure_with_json_error(caplog: pytest.LogCaptureFixture) -> None:+ mock_response = AsyncMock()+ mock_response.ok = False+ mock_response.status = 400+ mock_response.json = AsyncMock(return_value={"error": "Bad Request", "content": "details"})++ with _mock_aiohttp_request(mock_response):+ with caplog.at_level(10):+ await send_notification(webhook, "test")++ assert "Webhook notification failed:" in caplog.text+ assert "Bad Request" in caplog.text+++async def test_send_webhook_failure_with_non_json_error(caplog: pytest.LogCaptureFixture) -> None:+ mock_response = AsyncMock()+ mock_response.ok = False+ mock_response.status = 500+ mock_response.json = AsyncMock(side_effect=aiohttp.ClientError("JSON error"))++ mock_response.raise_for_status = MagicMock(+ side_effect=aiohttp.ClientResponseError(+ AsyncMock(spec=aiohttp.RequestInfo),+ (),+ status=500,+ )+ )++ with _mock_aiohttp_request(mock_response):+ with caplog.at_level(10):+ await send_notification(webhook, "test")++ assert "ClientResponseError: 500" in caplog.text