Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
fix: parsing of json responses from flaresolverr (#1794)
NTFSvolume1d6180d838aa
diff --git a/cyberdrop_dl/clients/flaresolverr.py b/cyberdrop_dl/clients/flaresolverr.pyindex 744c84473..fe252f2e8 100644--- a/cyberdrop_dl/clients/flaresolverr.py+++ b/cyberdrop_dl/clients/flaresolverr.py@@ -36,7 +36,7 @@ class Command(StrEnum):@dataclasses.dataclass(slots=True)class Solution:- content: str+ content: Anycookies: SimpleCookieheaders: CIMultiDictProxy[str]url: AbsoluteHttpURL@@ -224,11 +224,12 @@ async def check_solution(cdl_user_agent: str, solution: Solution) -> None:f"\n Flaresolverr: '{solution.user_agent}'")- try:- ddos_guard.check_html(solution.content)- except DDOSGuardError:- if solution.user_agent != cdl_user_agent:- raise DDOSGuardError(mismatch_ua_msg) from None+ if type(solution.content) is str:+ try:+ ddos_guard.check_html(solution.content)+ except DDOSGuardError:+ if solution.user_agent != cdl_user_agent:+ raise DDOSGuardError(mismatch_ua_msg) from Noneif solution.user_agent != cdl_user_agent:logger.warning(f"{mismatch_ua_msg}\n Response was successful but cookies will not be valid")diff --git a/cyberdrop_dl/clients/response.py b/cyberdrop_dl/clients/response.pyindex 721e52c49..159f9d472 100644--- a/cyberdrop_dl/clients/response.py+++ b/cyberdrop_dl/clients/response.py@@ -82,23 +82,26 @@ class AbstractResponse(ABC, Generic[_ResponseT]):def __repr__(self) -> str:return f"<{type(self).__name__} [{self.status}] ({self.url})>"- def __json__(self) -> dict[str, Any]:- if content := self._text:+ def _get_content(self) -> Any:+ if self._text:if "json" in self.content_type:- content = json.loads(content)+ return json.loads(self._text)- elif "html" in self.content_type:- content = BeautifulSoup(content, "html.parser").prettify(formatter="html")+ if "html" in self.content_type:+ return BeautifulSoup(self._text, "html.parser").prettify(formatter="html")- elif not ("json" in self.content_type or "html" in self.content_type):- content = f"<{self.content_type} payload>"+ if not ("json" in self.content_type or "html" in self.content_type):+ return f"<{self.content_type} payload>"+ return self._text++ def __json__(self) -> dict[str, Any]:return {"url": str(self.url),"status_code": self.status,"created_at": str(self.created_at),"response_headers": dict(self.headers),- "content": content,+ "content": self._get_content(),}@abstractmethod@@ -190,6 +193,9 @@ class AbstractResponse(ABC, Generic[_ResponseT]):self.__check_content_type(*content_type, expecting="JSON")+ return await self._json(encoding)++ async def _json(self, encoding: str | None = None) -> Any:return json.loads(await self.text(encoding))@final@@ -229,12 +235,27 @@ class _FlareSolverrResponse(AbstractResponse[FlaresolverrSolution]):async def aclose(self) -> None: ...+ async def _json(self, encoding: str | None = None) -> Any:+ if self._text:+ return json.loads(self._text)++ assert "json" in self.content_type+ return self._resp.content++ def _get_content(self) -> Any:+ return super()._get_content() or self._resp.content+@override@classmethoddef create(cls, solution: FlaresolverrSolution, /) -> Self:content_type, location = _parse_headers(solution.url, solution.headers)- if not content_type:- content_type = _infer_content_type_from_body(solution.content)+ if type(solution.content) is str:+ text = solution.content+ if not content_type and text:+ content_type = _infer_content_type_from_body(text)+ else:+ text = ""+ content_type = content_type or "application/json"return cls(content_type=content_type,@@ -242,7 +263,7 @@ class _FlareSolverrResponse(AbstractResponse[FlaresolverrSolution]):headers=solution.headers,url=solution.url,location=location,- _text=solution.content,+ _text=text,_resp=solution,)diff --git a/tests/test_flaresolverr_response.py b/tests/test_flaresolverr_response.pyindex a0f2eaa51..0ef14b581 100644--- a/tests/test_flaresolverr_response.py+++ b/tests/test_flaresolverr_response.py@@ -36,10 +36,73 @@ FLARESOLVERR_RESPONSE_EMPTY_HEADERS = {"version": "3.4.6",}--# ----------------------------------------------------------------------------# _infer_content_type_from_body-# ---------------------------------------------------------------------------+FLARESOLVER_RESP_JSON = {+ "status": "ok",+ "message": "Challenge not detected!",+ "solution": {+ "url": "https://www.tikwm.com/api/user/posts?unique_id=kittyasmr2&count=50&cursor=0",+ "status": 200,+ "response": {+ "code": 0,+ "msg": "success",+ "processed_time": 0.9642,+ "data": {+ "videos": [+ {+ "video_id": "7637253304178740500",+ "region": "CL",+ "title": "Esa amiga que solo hace videollamada para admirarse 🐥 créditos: jimenita #humor #comedia #Viral #kdramas #paratii ",+ "content_desc": [+ "Esa amiga que solo hace videollamada para admirarse 🐥 créditos: jimenita #humor #comedia #Viral #kdramas",+ "#paratii ",+ ],+ "duration": 16,+ }+ ],+ "cursor": "1745723767416",+ "hasMore": False,+ },+ },+ "headers": {+ "access-control-allow-credentials": "true",+ "access-control-allow-headers": "Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin",+ "access-control-allow-methods": "POST,GET,OPTIONS,DELETE",+ "access-control-allow-origin": "*",+ "cf-cache-status": "DYNAMIC",+ "cf-ray": "9f8a6e819968f0-MIA",+ "content-encoding": "br",+ "content-type": "application/json",+ "date": "Fri, 08 May 2026 18:12:17 GMT",+ "nel": '{"report_to":"cf-nel","success_fraction":0.0,"max_age":604800}',+ "server": "cloudflare",+ "x-limit-request-remaining": "9995",+ "x-limit-request-reset": "20864",+ },+ "cookies": [+ {+ "name": "cf_clearance",+ "value": "m5B4ZLfY9b1yGWFI0mQHveDo7Jnb4e",+ "domain": ".tikwm.com",+ "path": "/",+ "expires": 1809798658.438918,+ "size": 417,+ "httpOnly": True,+ "secure": True,+ "session": False,+ "sameSite": "None",+ "priority": "Medium",+ "sameParty": False,+ "sourceScheme": "Secure",+ "sourcePort": 443,+ "partitionKey": "https://tikwm.com",+ }+ ],+ "userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",+ },+ "startTimestamp": 1778263936203,+ "endTimestamp": 1778263939479,+ "version": "3.3.21",+}def test_infer_content_type_html() -> None:@@ -66,11 +129,6 @@ def test_infer_content_type_only_whitespace() -> None:assert _infer_content_type_from_body(" \n\t ") == ""-# ----------------------------------------------------------------------------# _parse_cookies-# -----------------------------------------------------------------------------def test_parse_cookies_complete_cookie() -> None:cookies = [{@@ -167,9 +225,9 @@ def test_solution_from_dict_cookies_parsed_correctly() -> None:assert morsel["secure"] == "TRUE"-# ----------------------------------------------------------------------------# _FlareSolverrResponse.create (async)-# ---------------------------------------------------------------------------+def test_solution_from_dict_json_resp() -> None:+ solution = Solution.from_dict(FLARESOLVER_RESP_JSON["solution"])+ assert type(solution.content) is dictasync def test_flaresolverr_response_infers_html_from_empty_headers() -> None:@@ -188,12 +246,22 @@ async def test_flaresolverr_response_reads_text() -> None:assert "<html>" in text+async def test_flaresolverr_response_from_json_resp() -> None:+ solution = Solution.from_dict(FLARESOLVER_RESP_JSON["solution"])+ response = _FlareSolverrResponse.create(solution)+ assert not response._text+ assert response.content_type == "application/json"+ assert response._get_content() == solution.content+ assert await response.json() == solution.content+ assert await response.text() == ""++async def test_flaresolverr_response_with_explicit_content_type() -> None:"""When headers contain Content-Type, it should be used instead of inference."""solution_data = {**FLARESOLVERR_RESPONSE_EMPTY_HEADERS["solution"],"headers": {"Content-Type": "application/json"},- "response": '{"data": true}',+ "response": '{"data": True}',}solution = Solution.from_dict(solution_data)response = _FlareSolverrResponse.create(solution)