Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
fix: gallery downloads (nhentai) (#1238)
NTFSvolume1a1238e3eb0c
diff --git a/cyberdrop_dl/clients/scraper_client.py b/cyberdrop_dl/clients/scraper_client.pyindex a1c20340c..a17b06c17 100644--- a/cyberdrop_dl/clients/scraper_client.py+++ b/cyberdrop_dl/clients/scraper_client.py@@ -10,7 +10,7 @@ from functools import wrapsfrom json import dumps as json_dumpsfrom json import loads as json_loadsfrom pathlib import Path-from typing import TYPE_CHECKING, Any, ParamSpec, Self, TypeVar+from typing import TYPE_CHECKING, Any, Literal, ParamSpec, Self, TypeVar, Unpackimport aiohttpfrom aiohttp_client_cache.response import AnyResponse@@ -29,11 +29,14 @@ if TYPE_CHECKING:from aiohttp_client_cache.session import CachedSessionfrom curl_cffi.requests.impersonate import BrowserTypeLiteral as BrowserTargetfrom curl_cffi.requests.models import Response as CurlResponse+ from curl_cffi.requests.session import RequestParams as CurlRequestParamsfrom multidict import CIMultiDictProxyfrom cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURLfrom cyberdrop_dl.managers.client_manager import ClientManager+ HttpMethod = Literal["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "TRACE", "PATCH", "QUERY"]+_curl_import_error = Nonetry:from curl_cffi.requests import AsyncSession # noqa: TC002@@ -101,7 +104,7 @@ class ScraperClient:min_html_file_path_len = len(str(self._pages_folder)) + len(constants.STARTUP_TIME_STR) + 10self._max_html_stem_len = 245 - min_html_file_path_lenself._session: CachedSession- self._curl_session: AsyncSession+ self._curl_session: AsyncSession[CurlResponse]def _startup(self) -> None:self._session = self.client_manager.new_scrape_session()@@ -143,6 +146,26 @@ class ScraperClient:raise@limiter+ async def _request_cffi(+ self,+ domain: str,+ url: AbsoluteHttpURL,+ method: HttpMethod = "GET",+ **request_params: Unpack[CurlRequestParams],+ ) -> CurlResponse:+ headers: dict[str, Any] = request_params.get("headers") or {} # type: ignore[reportAssignmentType]+ request_params["headers"] = self.client_manager._headers | headers+ response = await self._curl_session.request(method, str(url), **request_params)+ async with self.write_soup_on_error(url, response):+ await self.client_manager.check_http_status(response)+ self.client_manager.cookies.update_cookies(self._curl_session.cookies, url)+ return response++ @copy_signature(_request_cffi)+ async def request_json_cffi(self, *args, **kwargs) -> Any:+ response = await self._request_cffi(*args, **kwargs)+ return await response_to_json(response)+async def _get_response_and_soup_cffi(self,domain: str,@@ -160,18 +183,10 @@ class ScraperClient::param request_params: Additional keyword arguments to pass to `curl_session.get` (e.g., `timeout`)."""request_params = request_params or {}- headers = self.client_manager._headers | (headers or {})- response: CurlResponse = await self._curl_session.get(- str(url), impersonate=impersonate, headers=headers, **request_params- )-- async with self.write_soup_on_error(url, response):- await self.client_manager.check_http_status(response)-+ response = await self._request_cffi(domain, url, headers=headers, impersonate=impersonate, **request_params)soup = await response_to_soup(response)if self._save_pages_html:await self.write_soup_to_disk(url, response, soup)- self.client_manager.cookies.update_cookies(self._curl_session.cookies, url)return response, soup@copy_signature(_get_response_and_soup_cffi)@@ -201,11 +216,16 @@ class ScraperClient::param request_params: Additional keyword arguments to pass to `curl_session.post` (e.g., `timeout`)."""request_params = request_params or {}- headers = self.client_manager._headers | (headers or {})- response: CurlResponse = await self._curl_session.post(- str(url), data=data, json=json, impersonate=impersonate, headers=headers, **request_params+ response = await self._request_cffi(+ domain,+ url,+ method="POST",+ data=data,+ json=json,+ impersonate=impersonate,+ headers=headers,+ **request_params,)- await self.client_manager.check_http_status(response)return response# ~~~~~~~~~~~~~ AIOHTTP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -418,25 +438,28 @@ class ScraperClient:async def response_to_soup(response: AnyResponse | CurlResponse) -> BeautifulSoup:- content_type: str = response.headers.get("Content-Type") or ""- if not any(s in content_type.lower() for s in ("html", "text")):- raise InvalidContentTypeError(message=f"Received {content_type}, was expecting text")-- if isinstance(response, AnyResponse):- content = await response.read() # aiohttp- else:- content = response.content # curl response- return BeautifulSoup(content, "html.parser")---async def response_to_json(response: AnyResponse) -> Any:- content_type: str = response.headers["Content-Type"].lower()- if "text/plain" in content_type:- return json_loads(await response.text())- elif "json" in content_type:- return await response.json()- else:- raise InvalidContentTypeError(message=f"Received {content_type}, was expecting JSON")+ content_type = (response.headers.get("Content-Type") or "").lower()+ if "text" in content_type or "html" in content_type:+ if isinstance(response, AnyResponse):+ content = await response.text()+ else:+ content = response.text++ return BeautifulSoup(content, "html.parser")++ raise InvalidContentTypeError(message=f"Received {content_type}, was expecting text")+++async def response_to_json(response: AnyResponse | CurlResponse) -> Any:+ content_type = (response.headers.get("Content-Type") or "").lower()+ if "text/plain" in content_type or "json" in content_type:+ if isinstance(response, AnyResponse):+ content = await response.text()+ else:+ content = response.text+ return json_loads(content)++ raise InvalidContentTypeError(message=f"Received {content_type}, was expecting JSON")def add_request_log_hooks(trace_configs: list[aiohttp.TraceConfig]) -> None:diff --git a/cyberdrop_dl/crawlers/nhentai.py b/cyberdrop_dl/crawlers/nhentai.pyindex e3d9c1e33..f5466e785 100644--- a/cyberdrop_dl/crawlers/nhentai.py+++ b/cyberdrop_dl/crawlers/nhentai.py@@ -1,7 +1,7 @@from __future__ import annotationsimport random-from typing import TYPE_CHECKING, ClassVar+from typing import TYPE_CHECKING, Any, ClassVarfrom aiolimiter import AsyncLimiter@@ -9,7 +9,6 @@ from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPathsfrom cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURLfrom cyberdrop_dl.exceptions import LoginErrorfrom cyberdrop_dl.utils import css-from cyberdrop_dl.utils.logger import log_debugfrom cyberdrop_dl.utils.utilities import error_handling_wrapperif TYPE_CHECKING:@@ -18,85 +17,95 @@ if TYPE_CHECKING:from cyberdrop_dl.data_structures.url_objects import ScrapeItem-PRIMARY_URL = AbsoluteHttpURL("https://nhentai.net/")-API_ENTRYPOINT = PRIMARY_URL / "api/gallery/"-EXT_MAP = {"a": ".avif", "g": ".gif", "j": ".jpg", "p": ".png", "w": ".webp"}-COLLECTION_PARTS = "favorites", "tag", "search", "parody", "group", "character", "artist"-ITEM_SELECTOR = "div.gallery > a"-COLLECTION_TITLE_SELECTOR = "div#content > h1"-LOGIN_PAGE_SELECTOR = "input.id_username_or_email"+class Selector:+ ITEM = "div.gallery > a"+ COLLECTION_TITLE = "span.name"+ FAVORITES_TITLE = "div#content > h1"+ LOGIN_PAGE = "input.id_username_or_email"class NHentaiCrawler(Crawler):SUPPORTED_PATHS: ClassVar[SupportedPaths] = {- "Collections": ("favorites", "tag", "search", "parody", "group", "character", "artist"),+ "Collections": (+ "favorites",+ "tag",+ "search",+ "parody",+ "group",+ "character",+ "artist",+ ),"Gallery": "/g/<gallery_id>",}- PRIMARY_URL: ClassVar[AbsoluteHttpURL] = PRIMARY_URL- NEXT_PAGE_SELECTOR: ClassVar[str] = "a.next"- DOMAIN: ClassVar[str] = "nhentai.net"- FOLDER_DOMAIN: ClassVar[str] = "nHentai"+ PRIMARY_URL = AbsoluteHttpURL("https://nhentai.net/")+ NEXT_PAGE_SELECTOR = "a.next"+ DOMAIN = "nhentai.net"+ FOLDER_DOMAIN = "nHentai"def __post_init__(self) -> None:self.request_limiter = AsyncLimiter(4, 1)async def fetch(self, scrape_item: ScrapeItem) -> None:- if any(p in scrape_item.url.parts for p in COLLECTION_PARTS):- return await self.collection(scrape_item)- if "g" in scrape_item.url.parts:- return await self.gallery(scrape_item)- raise ValueError+ match scrape_item.url.parts[1:]:+ case ["favorites" | "tag" | "search" | "parody" | "group" | "character" | "artist" as type_, _]:+ return await self.collection(scrape_item, type_)+ case ["g", _]:+ return await self.gallery(scrape_item)+ case _:+ raise ValueError@error_handling_wrapper- async def collection(self, scrape_item: ScrapeItem) -> None:- title = ""- async for soup in self.web_pager(scrape_item.url):+ async def collection(self, scrape_item: ScrapeItem, collection_type: str) -> None:+ title: str = ""+ async for soup in self.web_pager(scrape_item.url, cffi=True):if not title:- collection_type = next(part for part in COLLECTION_PARTS if part in scrape_item.url.parts)if collection_type == "favorites":- title_tag = css.select_one(soup, COLLECTION_TITLE_SELECTOR)- if soup.select_one(LOGIN_PAGE_SELECTOR):+ title_tag = css.select_one(soup, Selector.FAVORITES_TITLE)+ if soup.select_one(Selector.LOGIN_PAGE):raise LoginError("No cookies provided to download favorites")- for span in soup.select("span"):- span.decompose()+ css.decompose(title_tag, "span")else:- title_tag = css.select_one(soup, "span.name")+ title_tag = css.select_one(soup, Selector.COLLECTION_TITLE)title = f" [{collection_type}]"- title: str = title_tag.get_text(strip=True) + title- title = self.create_title(title)+ title = self.create_title(title_tag.get_text(strip=True) + title)scrape_item.setup_as_album(title)- for _, new_scrape_item in self.iter_children(scrape_item, soup, ITEM_SELECTOR):- self.manager.task_group.create_task(self.run(new_scrape_item))+ for _, new_scrape_item in self.iter_children(scrape_item, soup, Selector.ITEM):+ self.create_task(self.run(new_scrape_item))@error_handling_wrapperasync def gallery(self, scrape_item: ScrapeItem) -> None:gallery_id = scrape_item.url.name- api_url = API_ENTRYPOINT / gallery_id+ api_url = self.PRIMARY_URL / "api/gallery" / gallery_id+async with self.request_limiter:- json_resp: dict = await self.client.get_json(self.DOMAIN, api_url)+ json_resp: dict[str, Any] = await self.client.request_json_cffi(self.DOMAIN, api_url)- log_debug(json_resp)titles: dict[str, str] = json_resp["title"]title: str = titles.get("english") or titles.get("japanese") or titles["pretty"]title = self.create_title(title, gallery_id)scrape_item.setup_as_album(title, album_id=gallery_id)scrape_item.possible_datetime = json_resp["upload_date"]- n_images: int = json_resp["num_pages"]- padding = max(3, len(str(n_images)))- for index, link in get_image_urls(json_resp):- filename, ext = self.get_filename_and_ext(link.name)- custom_filename = self.create_custom_filename(str(index).zfill(padding), ext)- await self.handle_file(link, scrape_item, filename, ext, custom_filename=custom_filename)+ padding = max(3, len(str(json_resp["num_pages"])))+ for index, link in _gen_image_urls(json_resp):+ filename = self.create_custom_filename(str(index).zfill(padding), link.suffix)+ self.create_task(self.handle_file(link, scrape_item, link.name, custom_filename=filename))+ scrape_item.add_children()-def get_image_urls(json_resp: dict) -> Generator[tuple[int, AbsoluteHttpURL]]:+def _gen_image_urls(json_resp: dict[str, Any]) -> Generator[tuple[int, AbsoluteHttpURL]]:media_id: str = json_resp["media_id"]- for index, info in enumerate(json_resp["images"]["pages"], 1):- ext = EXT_MAP.get(info["t"]) or ".jpg"+ for index, page in enumerate(json_resp["images"]["pages"], 1):+ ext = {+ "a": ".avif",+ "g": ".gif",+ "j": ".jpg",+ "p": ".png",+ "w": ".webp",+ }.get(page["t"], ".jpg")cdn = random.randint(1, 4)yield index, AbsoluteHttpURL(f"https://i{cdn}.nhentai.net/galleries/{media_id}/{index}{ext}")diff --git a/tests/crawlers/test_cases/nhentai.py b/tests/crawlers/test_cases/nhentai.pynew file mode 100644index 000000000..ffebe2523--- /dev/null+++ b/tests/crawlers/test_cases/nhentai.py@@ -0,0 +1,25 @@+DOMAIN = "nhentai.net"+TEST_CASES = [+ (+ "https://nhentai.net/g/363796/",+ [+ {+ "url": r"re:nhentai.net/galleries/1941242/",+ "referer": "https://nhentai.net/g/363796",+ "album_id": "363796",+ "datetime": 1624512830,+ }+ ],+ 25,+ ),+ (+ "https://nhentai.net/artist/tamabi/",+ [+ {+ "url": r"re:nhentai.net/galleries/",+ "download_folder": r"re:tamabi \[artist\] \(nHentai\)/",+ }+ ],+ 8658,+ ),+]