Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
feat: add xhamster support
NTFSvolume0f53554391a7
diff --git a/cyberdrop_dl/crawlers/__init__.py b/cyberdrop_dl/crawlers/__init__.pyindex e747d5df5..616a85182 100644--- a/cyberdrop_dl/crawlers/__init__.py+++ b/cyberdrop_dl/crawlers/__init__.py@@ -79,6 +79,7 @@ from .xenforo import (TitsInTopsCrawler,XBunkerCrawler,)+from .xhamster import XhamsterCrawlerfrom .xxxbunker import XXXBunkerCrawlerfrom .yandex_disk import YandexDiskCrawlerfrom .youjizz import YouJizzCrawlerdiff --git a/cyberdrop_dl/crawlers/crawler.py b/cyberdrop_dl/crawlers/crawler.pyindex fe87dff2c..26510ca16 100644--- a/cyberdrop_dl/crawlers/crawler.py+++ b/cyberdrop_dl/crawlers/crawler.py@@ -286,7 +286,7 @@ class Crawler(ABC):response_url = url or self.primary_base_domainself.client.client_manager.cookies.update_cookies(cookies, response_url)- async def web_pager(self, url: URL, next_page_selector: str = "") -> AsyncGenerator[BeautifulSoup]:+ async def web_pager(self, url: URL, next_page_selector: str | None = None) -> AsyncGenerator[BeautifulSoup]:"""Generator of website pages."""page_url = urlnext_page_selector = next_page_selector or self.next_page_selectordiff --git a/cyberdrop_dl/crawlers/xhamster.py b/cyberdrop_dl/crawlers/xhamster.pynew file mode 100644index 000000000..e939a69a8--- /dev/null+++ b/cyberdrop_dl/crawlers/xhamster.py@@ -0,0 +1,179 @@+from __future__ import annotations++from functools import partial+from typing import TYPE_CHECKING, Annotated, NamedTuple++from pydantic import Field, PlainValidator+from yarl import URL++from cyberdrop_dl.config_definitions.custom.types import AliasModel+from cyberdrop_dl.crawlers.crawler import Crawler, create_task_id+from cyberdrop_dl.utils import javascript+from cyberdrop_dl.utils.logger import log_debug+from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_text_between, parse_url++if TYPE_CHECKING:+ from collections.abc import Generator++ from bs4 import BeautifulSoup++ from cyberdrop_dl.managers.manager import Manager+ from cyberdrop_dl.utils.data_enums_classes.url_objects import ScrapeItem++PRIMARY_BASE_DOMAIN = URL("https://xhamster.com/")+JS_VIDEO_INFO_SELECTOR = "script#initials-script"+VIDEO_SELECTOR = "a.video-thumb__image-container"+GALLERY_SELECTOR = "a.gallery-thumb__link"+++HttpURL = Annotated[URL, PlainValidator(partial(parse_url, relative_to=PRIMARY_BASE_DOMAIN))]+++class XhamsterCrawler(Crawler):+ primary_base_domain = PRIMARY_BASE_DOMAIN+ next_page_selector = "a[data-page='next']"++ def __init__(self, manager: Manager) -> None:+ super().__init__(manager, "xhamster", "xHamster")++ """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""++ @create_task_id+ async def fetch(self, scrape_item: ScrapeItem) -> None:+ """Determines where to send the scrape item based on the url."""+ if "gallery" in scrape_item.url.parts:+ return await self.gallery(scrape_item)+ if any(p in scrape_item.url.parts for p in ("creators", "user")):+ return await self.profile(scrape_item)+ if any(p in scrape_item.url.parts for p in ("movies", "videos")):+ return await self.video(scrape_item)+ raise ValueError++ @error_handling_wrapper+ async def profile(self, scrape_item: ScrapeItem, paths_to_scrape) -> None:+ profile_type, username = scrape_item.url.parts[1:3]+ title = self.create_title(f"{username} [{profile_type.removesuffix('s')}]")+ scrape_item.setup_as_profile(title)+ is_user = "users" in scrape_item.url.parts+ last_part = "videos" if is_user else "exclusive"+ base_url = PRIMARY_BASE_DOMAIN / profile_type / username++ all_paths = ("videos", "photos")+ paths_to_scrape = next(((p,) for p in all_paths if p in scrape_item.url.parts), all_paths)++ async def process_children(url: URL, selector: str, name: str):+ async for soup in self.web_pager(url):+ for item in soup.select(selector):+ link_str: str = item["href"] # type: ignore+ link = self.parse_url(link_str)+ new_scrape_item = scrape_item.create_child(link, add_to_parent_title=name)+ self.manager.task_group.create_task(self.run(new_scrape_item))+ scrape_item.add_children()++ if "videos" in paths_to_scrape:+ videos_url = base_url / last_part+ await process_children(videos_url, VIDEO_SELECTOR, last_part)++ if is_user and "photos" in paths_to_scrape:+ gallerys_url = base_url / "photos"+ await process_children(gallerys_url, GALLERY_SELECTOR, "galleries")++ @error_handling_wrapper+ async def gallery(self, scrape_item: ScrapeItem) -> None:+ json_info = await self.get_model_details(scrape_item.url, "photosGalleryModel", "galleryModel")+ gallery = Gallery(**json_info)+ title = f"{gallery.title} [gallery]"+ scrape_item.setup_as_album(title, album_id=gallery.id)+ scrape_item.possible_datetime = gallery.created++ padding = max(3, len(str(gallery.quantity)))+ for index, image in enumerate(gallery.photos, 1):+ filename, ext = self.get_filename_and_ext(image.url.name)+ custom_filename = f"{index:0{padding}d} - {filename.removesuffix(ext)} [{image.id}]{ext}"+ new_scrape_item = scrape_item.create_child(image.page_url)+ await self.handle_file(image.url, new_scrape_item, filename, ext, custom_filename=custom_filename)+ scrape_item.add_children()++ @error_handling_wrapper+ async def video(self, scrape_item: ScrapeItem) -> None:+ if await self.check_complete_from_referer(scrape_item):+ return++ json_info = await self.get_model_details(scrape_item.url, "videoModel")+ video = Video(**json_info)++ scrape_item.url = video.page_url+ scrape_item.possible_datetime = video.created+ _, resolution, download_url = max(video.get_formats())+ link = PRIMARY_BASE_DOMAIN / "movies" / video.id / "download" / resolution++ filename, ext = self.get_filename_and_ext(f"{video.id}.mp4")+ custom_filename, _ = self.get_filename_and_ext(f"{video.title} [{video.id}][{resolution}]{ext}")+ await self.handle_file(+ link, scrape_item, filename, ext, custom_filename=custom_filename, debrid_link=download_url+ )++ async def get_model_details(self, url: URL, *model_name_choices: str) -> dict:+ model_names = model_name_choices or []++ async with self.request_limiter:+ soup: BeautifulSoup = await self.client.get_soup(self.domain, url)++ json_info = get_window_initials_json(soup)+ del soup++ def get_model_value():+ for model_name in model_names:+ if (value := json_info.get(model_name)) is not None:+ return value++ json_info = get_model_value() or json_info+ log_debug(json_info)+ return json_info+++# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+++def get_window_initials_json(soup: BeautifulSoup) -> dict[str, dict]:+ js_script = soup.select_one(JS_VIDEO_INFO_SELECTOR)+ js_code: str = str(js_script)+ json_text: str = get_text_between(js_code, "window.initials=", "</script>").removesuffix(";").strip()+ return javascript.parse_json_to_dict(json_text) # type: ignore+++class Format(NamedTuple):+ height: int+ resolution: str+ url: URL+++class XHamsterItem(AliasModel):+ id: str = Field(alias="idHashSlug")+ page_url: HttpURL = Field(alias="pageURL")+ created: int = 0+++class Image(XHamsterItem):+ url: HttpURL = Field(alias="imageURL")+++class Gallery(XHamsterItem):+ title: str+ photos: list[Image]+ quantity: int+++class Video(XHamsterItem):+ title: str+ mp4_file: HttpURL = Field(alias="mp4File")+ sources: dict = Field({})++ def get_formats(self) -> Generator[Format]:+ mp4_sources: dict[str, str] = self.sources.get("mp4") or {}+ yield Format(0, "Unknown", self.mp4_file)+ for resolution, details in mp4_sources.items():+ height = int(resolution.removesuffix("p"))+ link: str = details["link"] if isinstance(details, dict) else details+ url = parse_url(link, relative_to=PRIMARY_BASE_DOMAIN)+ yield Format(height, f"{height}p", url)diff --git a/cyberdrop_dl/utils/javascript.py b/cyberdrop_dl/utils/javascript.pyindex 099867d68..d40af7d96 100644--- a/cyberdrop_dl/utils/javascript.py+++ b/cyberdrop_dl/utils/javascript.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport jsonimport re+from typing import AnyHTTPS_PLACEHOLDER = "<<SAFE_HTTPS>>"HTTP_PLACEHOLDER = "<<SAFE_HTTP>>"@@ -34,7 +35,7 @@ def parse_js_vars(js_text: str, use_regex: bool = False) -> dict:return data-def parse_json_to_dict(js_text: str, use_regex: bool = False) -> dict:+def parse_json_to_dict(js_text: str, use_regex: bool = False) -> dict[str, Any] | list[Any]:json_str = js_text.replace("\t", "").replace("\n", "").strip()json_str = replace_quotes(json_str)if use_regex:@@ -42,7 +43,14 @@ def parse_json_to_dict(js_text: str, use_regex: bool = False) -> dict:json_str = re.sub(*QUOTE_KEYS_REGEX, json_str)json_str = re.sub(*QUOTE_VALUES_REGEX, json_str)json_str = recover_urls(json_str)- return json.loads(json_str)+ result = json.loads(json_str)+ is_list = isinstance(result, list)+ if is_list:+ result = {"data": result}+ clean_dict(result)+ if is_list:+ return result["data"]+ return resultdef replace_quotes(js_text: str) -> str:diff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.pyindex 8ed19d987..1b09c0ba2 100644--- a/cyberdrop_dl/utils/utilities.py+++ b/cyberdrop_dl/utils/utilities.py@@ -7,9 +7,10 @@ import platformimport reimport shutilimport subprocess+from dataclasses import fieldsfrom functools import lru_cache, partial, wrapsfrom pathlib import Path-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Any, ClassVar, Protocolimport aiofilesimport rich@@ -38,6 +39,10 @@ if TYPE_CHECKING:from cyberdrop_dl.utils.data_enums_classes.url_objects import MediaItem, ScrapeItem+class Dataclass(Protocol):+ __dataclass_fields__: ClassVar[dict]++TEXT_EDITORS = "micro", "nano", "vim" # Ordered by preferencesubprocess_get_text = partial(subprocess.run, capture_output=True, text=True, check=False)@@ -365,6 +370,23 @@ def set_default_app_if_none(file_path: Path) -> bool:return False+def get_valid_dict(dataclass: Dataclass | type[Dataclass], info: dict[str, Any]) -> dict[str, Any]:+ """Remove all keys that are not fields in the dataclass"""+ return {k: v for k, v in info.items() if k in get_field_names(dataclass)}+++@lru_cache+def get_field_names(dataclass: Dataclass | type[Dataclass]) -> list[str]:+ return [f.name for f in fields(dataclass)]+++def get_text_between(original_text: str, start: str, end: str) -> str:+ """Extracts the text between two strings in a larger text."""+ start_index = original_text.index(start) + len(start)+ end_index = original_text.index(end, start_index)+ return original_text[start_index:end_index]++def xdg_mime_query(*args) -> str:assert argsarg_list = ["xdg-mime", "query", *args]