Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
fix: get soup from non curl responses (#861)
NTFSvolume03407c3623c2
diff --git a/cyberdrop_dl/managers/client_manager.py b/cyberdrop_dl/managers/client_manager.pyindex d0564e9fd..d4041703a 100644--- a/cyberdrop_dl/managers/client_manager.py+++ b/cyberdrop_dl/managers/client_manager.py@@ -25,6 +25,7 @@ from cyberdrop_dl.utils.logger import log, log_spacerfrom cyberdrop_dl.utils.utilities import get_soup_from_responseif TYPE_CHECKING:+ from aiohttp_client_cache import CachedResponsefrom curl_cffi.requests.models import Response as CurlResponsefrom cyberdrop_dl.managers.manager import Manager@@ -159,38 +160,52 @@ class ClientManager:@classmethodasync def check_http_status(cls,- response: ClientResponse | CurlResponse,+ response: ClientResponse | CurlResponse | CachedResponse,download: bool = False,origin: ScrapeItem | URL | None = None,- ) -> None:- """Checks the HTTP status code and raises an exception if it's not acceptable."""+ ) -> BeautifulSoup | None:+ """Checks the HTTP status code and raises an exception if it's not acceptable.++ If the response is successful and has valid html, returns soup+ """status: int = response.status_code if hasattr(response, "status_code") else response.status # type: ignoreheaders = response.headers+ url_host: str = URL(response.url).host # type: ignoremessage = None- e_tag = headers.get("ETag")- if download and e_tag in DOWNLOAD_ERROR_ETAGS:- message = DOWNLOAD_ERROR_ETAGS.get(e_tag)- raise DownloadError(HTTPStatus.NOT_FOUND, message=message, origin=origin)+ def check_etag():+ if download and (e_tag := headers.get("ETag")) in DOWNLOAD_ERROR_ETAGS:+ message = DOWNLOAD_ERROR_ETAGS.get(e_tag)+ raise DownloadError(HTTPStatus.NOT_FOUND, message=message, origin=origin)- if HTTPStatus.OK <= status < HTTPStatus.BAD_REQUEST:- return+ async def check_ddos_guard():+ if soup := await get_soup_from_response(response):+ if cls.check_ddos_guard(soup) or cls.check_cloudflare(soup):+ raise DDOSGuardError(origin=origin)+ return soup++ async def check_json_status():+ if not any(domain in url_host for domain in ("gofile", "imgur")):+ return- if any(domain in response.url.host for domain in ("gofile", "imgur")): # type: ignorewith contextlib.suppress(ContentTypeError):- JSON_Resp: dict = await response.json()- status: str | int = JSON_Resp.get("status") # type: ignore- if status and isinstance(status, str) and "notFound" in status:+ json_resp: dict[str, Any] | None = await response.json()+ if not json_resp:+ return+ json_status: str | int | None = json_resp.get("status")+ if json_status and isinstance(status, str) and "notFound" in status:raise ScrapeError(404, origin=origin)- data = JSON_Resp.get("data")- if data and isinstance(data, dict) and "error" in data:- raise ScrapeError(status, data["error"], origin=origin)- soup = await get_soup_from_response(response)- if soup:- if cls.check_ddos_guard(soup) or cls.check_cloudflare(soup):- raise DDOSGuardError(origin=origin)+ if (data := json_resp.get("data")) and isinstance(data, dict) and "error" in data:+ raise ScrapeError(json_status or status, data["error"], origin=origin)++ check_etag()+ if HTTPStatus.OK <= status < HTTPStatus.BAD_REQUEST:+ # check DDosGuard even on successful pages+ return await check_ddos_guard()+ await check_json_status()+ await check_ddos_guard()raise DownloadError(status=status, message=message, origin=origin)@staticmethoddiff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.pyindex eb0a712a4..eafcba161 100644--- a/cyberdrop_dl/utils/utilities.py+++ b/cyberdrop_dl/utils/utilities.py@@ -15,6 +15,7 @@ from typing import TYPE_CHECKING, Any, ClassVar, Protocolimport aiofilesimport richfrom aiohttp import ClientConnectorError, ClientResponse, ClientSession, FormData+from aiohttp_client_cache import CachedResponsefrom bs4 import BeautifulSoupfrom yarl import URL@@ -436,15 +437,12 @@ def remove_trailing_slash(url: URL) -> URL:return url.parent.with_fragment(url.fragment).with_query(url.query)-async def get_soup_from_response(response: CurlResponse | ClientResponse) -> BeautifulSoup | None:- response_text = None+async def get_soup_from_response(response: CurlResponse | ClientResponse | CachedResponse) -> BeautifulSoup | None:+ # We can't use `CurlResponse` at runtime so we check the reverse+ is_curl = not isinstance(response, ClientResponse | CachedResponse)with contextlib.suppress(UnicodeDecodeError):- response_text = await response.text() if isinstance(response, ClientResponse) else response.text-- if not response_text:- return-- return BeautifulSoup(response_text, "html.parser")+ response_text = response.text if is_curl else await response.text()+ return BeautifulSoup(response_text, "html.parser")log_cyan = partial(log_with_color, style="cyan", level=20)