Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: add origin to ScraperClient functions

NTFSvolume3d2faaf49a08
diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.py
index 054b4a2ae..36d2aa94c 100644
--- a/cyberdrop_dl/clients/download_client.py
+++ b/cyberdrop_dl/clients/download_client.py
@@ -110,7 +110,7 @@ class DownloadClient:
if resp.status == HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE:
media_item.partial_file.unlink()
- await self.client_manager.check_http_status(resp, download=True)
+ await self.client_manager.check_http_status(resp, download=True, origin = media_item.url)
content_type = resp.headers.get('Content-Type')
media_item.filesize = int(resp.headers.get('Content-Length', '0'))
diff --git a/cyberdrop_dl/clients/scraper_client.py b/cyberdrop_dl/clients/scraper_client.py
index 4f349b8a5..4b2df5f3e 100644
--- a/cyberdrop_dl/clients/scraper_client.py
+++ b/cyberdrop_dl/clients/scraper_client.py
@@ -16,13 +16,14 @@ from cyberdrop_dl.utils.utilities import log
if TYPE_CHECKING:
from cyberdrop_dl.managers.client_manager import ClientManager
+ from cyberdrop_dl.utils.dataclasses.url_objects import ScrapeItem
def limiter(func):
"""Wrapper handles limits for scrape session"""
@wraps(func)
- async def wrapper(self, *args, **kwargs):
+ async def wrapper(self: ScraperClient, *args, **kwargs):
domain_limiter = await self.client_manager.get_rate_limiter(args[0])
async with self.client_manager.session_limit:
await self._global_limiter.acquire()
@@ -63,10 +64,10 @@ class ScraperClient:
self.trace_configs.append(trace_config)
@limiter
- async def flaresolverr(self, domain: str, url: URL, client_session: ClientSession) -> str:
+ async def flaresolverr(self, domain: str, url: URL, client_session: ClientSession, origin: Optional[ ScrapeItem | URL] = None) -> str:
"""Returns the resolved URL from the given URL"""
if not self.client_manager.flaresolverr:
- raise DDOSGuardFailure(message="FlareSolverr is not configured")
+ raise DDOSGuardFailure(message="FlareSolverr is not configured", origin=origin)
headers = {**self._headers, **{"Content-Type": "application/json"}}
data = {"cmd": "request.get", "url": str(url), "maxTimeout": 60000}
@@ -74,66 +75,66 @@ class ScraperClient:
async with client_session.post(f"http://{self.client_manager.flaresolverr}/v1", headers=headers,
ssl=self.client_manager.ssl_context,
proxy=self.client_manager.proxy, json=data) as response:
- json_obj = await response.json()
+ json_obj: dict = await response.json()
status = json_obj.get("status")
if status != "ok":
- raise DDOSGuardFailure(message="Failed to resolve URL with flaresolverr")
+ raise DDOSGuardFailure(message="Failed to resolve URL with flaresolverr", origin=origin)
return json_obj.get("solution").get("response")
@limiter
- async def get_BS4(self, domain: str, url: URL, client_session: ClientSession) -> BeautifulSoup:
+ async def get_BS4(self, domain: str, url: URL, client_session: ClientSession, origin: Optional[ ScrapeItem | URL] = None) -> BeautifulSoup:
"""Returns a BeautifulSoup object from the given URL"""
async with client_session.get(url, headers=self._headers, ssl=self.client_manager.ssl_context,
proxy=self.client_manager.proxy) as response:
try:
- await self.client_manager.check_http_status(response)
+ await self.client_manager.check_http_status(response, origin=origin)
except DDOSGuardFailure:
- response_text = await self.flaresolverr(domain, url)
+ response_text = await self.flaresolverr(domain, url, origin=origin)
return BeautifulSoup(response_text, 'html.parser')
content_type = response.headers.get('Content-Type')
assert content_type is not None
if not any(s in content_type.lower() for s in ("html", "text")):
- raise InvalidContentTypeFailure(message=f"Received {content_type}, was expecting text")
+ raise InvalidContentTypeFailure(message=f"Received {content_type}, was expecting text", origin=origin )
text = await response.text()
return BeautifulSoup(text, 'html.parser')
@limiter
- async def get_BS4_and_return_URL(self, domain: str, url: URL, client_session: ClientSession) -> tuple[
+ async def get_BS4_and_return_URL(self, domain: str, url: URL, client_session: ClientSession, origin: Optional[ ScrapeItem | URL] = None) -> tuple[
BeautifulSoup, URL]:
"""Returns a BeautifulSoup object and response URL from the given URL"""
async with client_session.get(url, headers=self._headers, ssl=self.client_manager.ssl_context,
proxy=self.client_manager.proxy) as response:
- await self.client_manager.check_http_status(response)
+ await self.client_manager.check_http_status(response, origin=origin)
content_type = response.headers.get('Content-Type')
assert content_type is not None
if not any(s in content_type.lower() for s in ("html", "text")):
- raise InvalidContentTypeFailure(message=f"Received {content_type}, was expecting text")
+ raise InvalidContentTypeFailure(message=f"Received {content_type}, was expecting text", origin=origin)
text = await response.text()
return BeautifulSoup(text, 'html.parser'), URL(response.url)
@limiter
async def get_json(self, domain: str, url: URL, params: Optional[Dict] = None, headers_inc: Optional[Dict] = None,
- client_session: ClientSession = None) -> Dict:
+ client_session: ClientSession = None, origin: Optional[ ScrapeItem | URL] = None) -> Dict:
"""Returns a JSON object from the given URL"""
headers = {**self._headers, **headers_inc} if headers_inc else self._headers
async with client_session.get(url, headers=headers, ssl=self.client_manager.ssl_context,
proxy=self.client_manager.proxy, params=params) as response:
- await self.client_manager.check_http_status(response)
+ await self.client_manager.check_http_status(response, origin=origin)
content_type = response.headers.get('Content-Type')
assert content_type is not None
if 'json' not in content_type.lower():
- raise InvalidContentTypeFailure(message=f"Received {content_type}, was expecting JSON")
+ raise InvalidContentTypeFailure(message=f"Received {content_type}, was expecting JSON", origin=origin)
return await response.json()
@limiter
- async def get_text(self, domain: str, url: URL, client_session: ClientSession) -> str:
+ async def get_text(self, domain: str, url: URL, client_session: ClientSession, origin: Optional[ ScrapeItem | URL] = None) -> str:
"""Returns a text object from the given URL"""
async with client_session.get(url, headers=self._headers, ssl=self.client_manager.ssl_context,
proxy=self.client_manager.proxy) as response:
try:
- await self.client_manager.check_http_status(response)
+ await self.client_manager.check_http_status(response, origin=origin)
except DDOSGuardFailure:
response_text = await self.flaresolverr(domain, url)
return response_text
@@ -142,11 +143,11 @@ class ScraperClient:
@limiter
async def post_data(self, domain: str, url: URL, client_session: ClientSession, data: Dict,
- req_resp: bool = True, raw: Optional[bool] = False) -> Dict:
+ req_resp: bool = True, raw: Optional[bool] = False, origin: Optional[ ScrapeItem | URL] = None) -> Dict:
"""Returns a JSON object from the given URL when posting data. If raw == True, returns raw binary data of response"""
async with client_session.post(url, headers=self._headers, ssl=self.client_manager.ssl_context,
proxy=self.client_manager.proxy, data=data) as response:
- await self.client_manager.check_http_status(response)
+ await self.client_manager.check_http_status(response, origin=origin)
if req_resp:
content = await response.content.read()
if raw:
diff --git a/cyberdrop_dl/managers/client_manager.py b/cyberdrop_dl/managers/client_manager.py
index 3de5cbbe5..3a7bd56c6 100644
--- a/cyberdrop_dl/managers/client_manager.py
+++ b/cyberdrop_dl/managers/client_manager.py
@@ -87,14 +87,14 @@ class ClientManager:
"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
- async def check_http_status(self, response: ClientResponse, download: bool = False, scrape_item: Optional[ScrapeItem | URL]= None) -> None:
+ async def check_http_status(self, response: ClientResponse, download: bool = False, origin: Optional[ScrapeItem | URL]= None) -> None:
"""Checks the HTTP status code and raises an exception if it's not acceptable"""
status = response.status
headers = response.headers
if download and headers.get('ETag') in DOWNLOAD_ERROR_ETAGS:
message = DOWNLOAD_ERROR_ETAGS.get(headers.get('ETag'))
- raise DownloadFailure(HTTPStatus.NOT_FOUND, message=message, origin = scrape_item)
+ raise DownloadFailure(HTTPStatus.NOT_FOUND, message=message, origin = origin)
if HTTPStatus.OK <= status < HTTPStatus.BAD_REQUEST:
return
@@ -104,20 +104,20 @@ class ClientManager:
JSON_Resp: dict = await response.json()
if "status" in JSON_Resp:
if "notFound" in JSON_Resp["status"]:
- raise ScrapeFailure(HTTPStatus.NOT_FOUND, origin = scrape_item)
+ raise ScrapeFailure(HTTPStatus.NOT_FOUND, origin = origin)
if JSON_Resp.get('data') and 'error' in JSON_Resp['data']:
- raise ScrapeFailure(JSON_Resp['status'], JSON_Resp['data']['error'], origin = scrape_item)
+ raise ScrapeFailure(JSON_Resp['status'], JSON_Resp['data']['error'], origin = origin)
except ContentTypeError:
pass
response_text = await response.text()
if "<title>DDoS-Guard</title>" in response_text:
- raise DDOSGuardFailure(origin = scrape_item)
+ raise DDOSGuardFailure(origin = origin)
if not headers.get('Content-Type'):
- raise DownloadFailure(status=CustomHTTPStatus.IM_A_TEAPOT, message="No content-type in response header", origin = scrape_item)
+ raise DownloadFailure(status=CustomHTTPStatus.IM_A_TEAPOT, message="No content-type in response header", origin = origin)
- raise DownloadFailure(status=status, origin = scrape_item )
+ raise DownloadFailure(status=status, origin = origin )
async def check_bunkr_maint(self, headers):
if headers.get('Content-Length') == "322509" and headers.get('Content-Type') == "video/mp4":