Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: use cache_control_manager
NTFSvolume892cb8041dbc
diff --git a/cyberdrop_dl/clients/scraper_client.py b/cyberdrop_dl/clients/scraper_client.pyindex 4f547751d..fdba924ff 100644--- a/cyberdrop_dl/clients/scraper_client.py+++ b/cyberdrop_dl/clients/scraper_client.py@@ -1,11 +1,12 @@from __future__ import annotationsimport json+from contextlib import asynccontextmanagerfrom functools import wrapsfrom typing import TYPE_CHECKING, Anyimport aiohttp-import aiohttp_client_cache+from aiohttp_client_cache import CachedSessionfrom aiohttp_client_cache.response import CachedStreamReaderfrom bs4 import BeautifulSoupfrom yarl import URL@@ -33,7 +34,7 @@ def limiter(func: Callable) -> Any:await self._global_limiter.acquire()await domain_limiter.acquire()- async with aiohttp_client_cache.CachedSession(+ async with CachedSession(headers=self._headers,raise_for_status=False,cookie_jar=self.client_manager.cookies,@@ -47,6 +48,13 @@ def limiter(func: Callable) -> Any:return wrapper+@asynccontextmanager+async def cache_control_manager(client_session: CachedSession, disabled: bool = False):+ client_session.cache.disabled = disabled+ yield+ client_session.cache.disabled = False++class ScraperClient:"""AIOHTTP operations for scraping."""@@ -82,7 +90,7 @@ class ScraperClient:self,domain: str,url: URL,- client_session: aiohttp_client_cache.CachedSession,+ client_session: CachedSession,origin: ScrapeItem | URL | None = None,with_response_url: bool = False,) -> tuple[str, URL | None]:@@ -117,82 +125,46 @@ class ScraperClient:self,domain: str,url: URL,- client_session: aiohttp_client_cache.CachedSession,+ client_session: CachedSession,origin: ScrapeItem | URL | None = None,with_response_url: bool = False,cache_disabled: bool = False,) -> BeautifulSoup:"""Returns a BeautifulSoup object from the given URL."""- if cache_disabled:- async with client_session.disabled():- async with client_session.get(+ async with (+ cache_control_manager(client_session, disabled=cache_disabled),+ 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, origin=origin)+ except DDOSGuardError:+ await self.client_manager.manager.cache_manager.request_cache.delete_url(url)+ response, response_URL = await self.flaresolverr(+ domain,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, origin=origin)- except DDOSGuardError:- await self.client_manager.manager.cache_manager.request_cache.delete_url(url)- response, response_URL = await self.flaresolverr(- domain,- url,- origin=origin,- with_response_url=with_response_url,- )- if with_response_url:- return BeautifulSoup(response, "html.parser"), response_URL- return BeautifulSoup(response, "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 InvalidContentTypeError(- message=f"Received {content_type}, was expecting text", origin=origin- )- text = await CachedStreamReader(await response.read()).read()- if with_response_url:- return BeautifulSoup(text, "html.parser"), URL(response.url)- return BeautifulSoup(text, "html.parser")- else:- 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, origin=origin)- except DDOSGuardError:- await self.client_manager.manager.cache_manager.request_cache.delete_url(url)- response, response_URL = await self.flaresolverr(- domain,- url,- origin=origin,- with_response_url=with_response_url,- )- if with_response_url:- return BeautifulSoup(response, "html.parser"), response_URL- return BeautifulSoup(response, "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 InvalidContentTypeError(message=f"Received {content_type}, was expecting text", origin=origin)- text = await CachedStreamReader(await response.read()).read()+ origin=origin,+ with_response_url=with_response_url,+ )if with_response_url:- return BeautifulSoup(text, "html.parser"), URL(response.url)- return BeautifulSoup(text, "html.parser")+ return BeautifulSoup(response, "html.parser"), response_URL+ return BeautifulSoup(response, "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 InvalidContentTypeError(message=f"Received {content_type}, was expecting text", origin=origin)+ text = await CachedStreamReader(await response.read()).read()+ if with_response_url:+ return BeautifulSoup(text, "html.parser"), URL(response.url)+ return BeautifulSoup(text, "html.parser")async def get_soup_and_return_url(- self,- domain: str,- url: URL,- origin: ScrapeItem | URL | None = None,+ self, domain: str, url: URL, origin: ScrapeItem | URL | None = None, **kwargs) -> tuple[BeautifulSoup, URL]:"""Returns a BeautifulSoup object and response URL from the given URL."""- return await self.get_soup(domain, url, origin=origin, with_response_url=True)+ return await self.get_soup(domain, url, origin=origin, with_response_url=True, **kwargs)@limiterasync def get_json(@@ -201,90 +173,62 @@ class ScraperClient:url: URL,params: dict | None = None,headers_inc: dict | None = None,- client_session: aiohttp_client_cache.CachedSession = None,+ client_session: CachedSession = None,origin: ScrapeItem | URL | None = None,cache_disabled: bool = False,) -> dict:"""Returns a JSON object from the given URL."""- headers = {**self._headers, **headers_inc} if headers_inc else self._headers- if cache_disabled:- async with client_session.disabled():- 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, origin=origin)- content_type = response.headers.get("Content-Type")- assert content_type is not None- if "json" not in content_type.lower():- raise InvalidContentTypeError(- message=f"Received {content_type}, was expecting JSON", origin=origin- )- return await response.json(), response- else:- async with client_session.get(+ headers = self._headers | headers_inc if headers_inc else self._headers+ async with (+ cache_control_manager(client_session, disabled=cache_disabled),+ 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, origin=origin)- content_type = response.headers.get("Content-Type")- assert content_type is not None- if "json" not in content_type.lower():- raise InvalidContentTypeError(message=f"Received {content_type}, was expecting JSON", origin=origin)- return await response.json()+ ) as 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 InvalidContentTypeError(message=f"Received {content_type}, was expecting JSON", origin=origin)+ json_resp = await response.json()+ if cache_disabled:+ return json_resp, response+ return json_resp@limiterasync def get_text(self,domain: str,url: URL,- client_session: aiohttp_client_cache.CachedSession,+ client_session: CachedSession,origin: ScrapeItem | URL | None = None,cache_disabled: bool = False,) -> str:"""Returns a text object from the given URL."""- if cache_disabled:- async with client_session.disabled():- 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, origin=origin)- except DDOSGuardError:- await self.client_manager.manager.cache_manager.request_cache.delete_url(url)- response_text, _ = await self.flaresolverr(domain, url)- return response_text- return await response.text()- else:- 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, origin=origin)- except DDOSGuardError:- await self.client_manager.manager.cache_manager.request_cache.delete_url(url)- response_text, _ = await self.flaresolverr(domain, url)- return response_text- return await response.text()+ async with (+ cache_control_manager(client_session, disabled=cache_disabled),+ 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, origin=origin)+ except DDOSGuardError:+ await self.client_manager.manager.cache_manager.request_cache.delete_url(url)+ response_text, _ = await self.flaresolverr(domain, url)+ return response_text+ return await response.text()@limiterasync def post_data(self,domain: str,url: URL,- client_session: aiohttp_client_cache.CachedSession,+ client_session: CachedSession,data: dict,req_resp: bool = True,raw: bool = False,@@ -307,9 +251,7 @@ class ScraperClient:return {}@limiter- async def get_head(- self, domain: str, url: URL, client_session: aiohttp_client_cache.CachedSession- ) -> CIMultiDictProxy[str]:+ async def get_head(self, domain: str, url: URL, client_session: CachedSession) -> CIMultiDictProxy[str]:"""Returns the headers from the given URL."""async with client_session.head(url,