Skip to content

Bulk asynchronous downloader for multiple file hosts

fix: handle encrypted URLs (xhamster) (#1264)

NTFSvolume2d14a850c5d8
diff --git a/cyberdrop_dl/crawlers/_chevereto.py b/cyberdrop_dl/crawlers/_chevereto.py
index 5ca7a0a45..ffbc99a9e 100644
--- a/cyberdrop_dl/crawlers/_chevereto.py
+++ b/cyberdrop_dl/crawlers/_chevereto.py
@@ -1,14 +1,13 @@
from __future__ import annotations
import base64
-import itertools
from typing import TYPE_CHECKING, ClassVar
from cyberdrop_dl.crawlers.crawler import Crawler
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.exceptions import PasswordProtectedError
from cyberdrop_dl.utils import css, open_graph
-from cyberdrop_dl.utils.utilities import error_handling_wrapper
+from cyberdrop_dl.utils.utilities import error_handling_wrapper, xor_decrypt
if TYPE_CHECKING:
from bs4 import BeautifulSoup
@@ -190,7 +189,8 @@ class CheveretoCrawler(Crawler, is_generic=True):
self, link_str: str, relative_to: AbsoluteHttpURL | None = None, *, trim: bool | None = None
) -> AbsoluteHttpURL:
if not link_str.startswith("https") and not link_str.startswith("/"):
- link_str = _xor_decrypt(link_str, _DECRYPTION_KEY)
+ encrypted_url = bytes.fromhex(base64.b64decode(link_str).decode())
+ link_str = xor_decrypt(encrypted_url, _DECRYPTION_KEY)
return super().parse_url(link_str, relative_to, trim=trim)
@@ -218,9 +218,3 @@ def _thumbnail_to_src(url: AbsoluteHttpURL) -> AbsoluteHttpURL:
def _sort_by_new(url: AbsoluteHttpURL) -> AbsoluteHttpURL:
init_page = int(url.query.get("page") or 1)
return url.with_query(sort="date_desc", page=init_page)
-
-
-def _xor_decrypt(encrypted_str: str, key: bytes) -> str:
- encrypted_data = bytes.fromhex(base64.b64decode(encrypted_str).decode())
- decrypted_data = bytearray(b_input ^ b_key for b_input, b_key in zip(encrypted_data, itertools.cycle(key)))
- return decrypted_data.decode("utf-8", errors="ignore")
diff --git a/cyberdrop_dl/crawlers/bunkrr.py b/cyberdrop_dl/crawlers/bunkrr.py
index 06a95c5f4..879c23e6f 100644
--- a/cyberdrop_dl/crawlers/bunkrr.py
+++ b/cyberdrop_dl/crawlers/bunkrr.py
@@ -8,7 +8,6 @@ import math
import re
from collections import defaultdict
from dataclasses import dataclass
-from itertools import cycle
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple
@@ -19,7 +18,13 @@ from cyberdrop_dl.crawlers.crawler import Crawler, SupportedDomains, SupportedPa
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.exceptions import DDOSGuardError, NoExtensionError, ScrapeError
from cyberdrop_dl.utils import css, open_graph
-from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_text_between, parse_url, with_suffix_encoded
+from cyberdrop_dl.utils.utilities import (
+ error_handling_wrapper,
+ get_text_between,
+ parse_url,
+ with_suffix_encoded,
+ xor_decrypt,
+)
if TYPE_CHECKING:
from collections.abc import AsyncGenerator
@@ -426,15 +431,10 @@ def decrypt_api_response(api_response: ApiResponse) -> str:
if not api_response.encrypted:
return api_response.url
- def xor_decrypt(encrypted_data: bytearray, key: str) -> str:
- key_bytes = key.encode("utf-8")
- decrypted_data = bytearray(b_input ^ b_key for b_input, b_key in zip(encrypted_data, cycle(key_bytes)))
- return decrypted_data.decode("utf-8", errors="ignore")
-
time_key = math.floor(api_response.timestamp / 3600)
secret_key = f"SECRET_KEY_{time_key}"
- byte_array = bytearray(base64.b64decode(api_response.url))
- return xor_decrypt(byte_array, secret_key)
+ encrypted_url = base64.b64decode(api_response.url)
+ return xor_decrypt(encrypted_url, secret_key.encode())
def get_slug_from_soup(soup: BeautifulSoup) -> str | None:
diff --git a/cyberdrop_dl/crawlers/xhamster.py b/cyberdrop_dl/crawlers/xhamster.py
index d38c48b94..4b46f415e 100644
--- a/cyberdrop_dl/crawlers/xhamster.py
+++ b/cyberdrop_dl/crawlers/xhamster.py
@@ -1,17 +1,16 @@
from __future__ import annotations
+import base64
import dataclasses
import itertools
import json
-from functools import partial
from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple
from aiolimiter import AsyncLimiter
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
-from cyberdrop_dl.utils import css
-from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_text_between, parse_url
+from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_text_between, parse_url, xor_decrypt
if TYPE_CHECKING:
from collections.abc import Iterable
@@ -21,16 +20,19 @@ if TYPE_CHECKING:
_PRIMARY_URL = AbsoluteHttpURL("https://xhamster.com/")
_ALLOW_AV1 = False
_ALLOW_HLS = False
+_DECRYPTION_KEY = b"xh7999"
class Selector:
- JS_WINDOW_INITIALS = "script#initials-script"
VIDEO = "a.video-thumb__image-container"
GALLERY = "a.gallery-thumb__link"
NEXT_PAGE = "a[data-page='next']"
-_parse_url = partial(parse_url, relative_to=_PRIMARY_URL)
+def _parse_url(url: str) -> AbsoluteHttpURL:
+ if url.startswith("eG9y"):
+ url = xor_decrypt(base64.b64decode(url)[4:], _DECRYPTION_KEY)
+ return parse_url(url, relative_to=_PRIMARY_URL)
class XhamsterCrawler(Crawler):
@@ -56,7 +58,7 @@ class XhamsterCrawler(Crawler):
self.request_limiter = AsyncLimiter(4, 1)
self._seen_hosts: set[str] = set()
- def _disable_title_auto_translations(self, url: AbsoluteHttpURL) -> None:
+ def _disable_ai_title_translations(self, url: AbsoluteHttpURL) -> None:
if url.host not in self._seen_hosts:
self.update_cookies({"lang": "en", "video_titles_translation": "0"}, url.origin())
self._seen_hosts.add(url.host)
@@ -72,11 +74,11 @@ class XhamsterCrawler(Crawler):
case []:
return await self.profile(scrape_item)
case ["photos"]:
- return await self.profile(scrape_item, only_photos=True)
+ return await self.profile(scrape_item, download_videos=False)
case ["videos"] if type_ == "users":
- return await self.profile(scrape_item, only_videos=True)
+ return await self.profile(scrape_item, download_photos=False)
case ["exclusive"] if type_ == "creators":
- return await self.profile(scrape_item, only_videos=True)
+ return await self.profile(scrape_item, download_photos=False)
case _:
raise ValueError
case _:
@@ -94,37 +96,44 @@ class XhamsterCrawler(Crawler):
return url
@error_handling_wrapper
- async def profile(self, scrape_item: ScrapeItem, only_photos: bool = False, only_videos: bool = False) -> None:
+ async def profile(
+ self,
+ scrape_item: ScrapeItem,
+ *,
+ download_photos: bool = True,
+ download_videos: bool = True,
+ ) -> None:
url_type, username = scrape_item.url.parts[1:3]
- base_url = scrape_item.url.origin() / url_type / username
- initials = await self._get_window_initials(base_url)
- is_creator_url = url_type == "creators"
- info = initials["infoComponent"]["displayUserModel"] if is_creator_url else initials["displayUserModel"]
-
- # every creator is actually an user
- # 'pageTitle' has the creator's name (for a creator's URL)
- # 'name' and 'displayName' are the actual user's name
- # they are different but we will use the user name in both cases
- name: str = info.get("displayName") or info["name"]
- title = self.create_title(f"{name} [user]")
- scrape_item.setup_as_profile(title)
-
- if is_creator_url:
- user_url = self.parse_url(info["pageURL"])
+ canonical_url = scrape_item.url.origin() / url_type / username
+ initials = await self._get_window_initials(canonical_url)
+ is_creator = url_type == "creators"
+ if is_creator:
+ info: dict[str, Any] = initials["infoComponent"]["displayUserModel"]
+ web_page_url = self.parse_url(info["pageURL"])
has_videos = bool(initials["infoComponent"].get("pornstarTop", {}).get("videoCount", 0))
has_galleries = bool(initials.get("galleriesComponent", {}).get("galleriesTotal", 0))
else:
- user_url = base_url
+ info = initials["displayUserModel"]
+ web_page_url = canonical_url
has_videos = bool(initials["counters"]["videos"])
has_galleries = bool(initials["counters"]["galleries"])
- if has_videos and not only_photos:
- videos_url = user_url / "videos"
+ # every creator is an user, but not every user is a creator
+ # the creator's name and the user_name are different for the same account
+ # we will ignore the creator's name and always use the user_name
+
+ creator_name: str | None = info.get("pageTitle") # noqa: F841
+ user_name: str = info.get("displayName") or info["name"]
+ title = self.create_title(f"{user_name} [user]")
+ scrape_item.setup_as_profile(title)
+
+ if has_videos and download_videos:
+ videos_url = web_page_url / "videos"
await self._iter_profile_pages(scrape_item, videos_url, Selector.VIDEO, "videos")
- if has_galleries and not only_videos:
- gallerys_url = user_url / "photos"
+ if has_galleries and download_photos:
+ gallerys_url = web_page_url / "photos"
await self._iter_profile_pages(scrape_item, gallerys_url, Selector.GALLERY, "galleries")
@error_handling_wrapper
@@ -147,7 +156,7 @@ class XhamsterCrawler(Crawler):
results = await self.get_album_results(gallery_id)
n_pages: int = page_details["paginationProps"]["lastPageNumber"]
- index = 0
+ index: int = 0
images: list[dict[str, Any]] = initials["photosGalleryModel"]["photos"]
for next_page in itertools.count(2):
@@ -198,13 +207,18 @@ class XhamsterCrawler(Crawler):
)
async def _get_window_initials(self, url: AbsoluteHttpURL) -> dict[str, Any]:
- self._disable_title_auto_translations(url)
+ self._disable_ai_title_translations(url)
async with self.request_limiter:
- soup = await self.client.get_soup(self.DOMAIN, url)
+ content = await self.client.get_text(self.DOMAIN, url)
- js_script = css.select_one(soup, Selector.JS_WINDOW_INITIALS)
- json_text = get_text_between(str(js_script), "window.initials=", ";</script>")
- return json.loads(json_text)
+ initials = get_text_between(content, "window.initials=", ";</script>")
+ return json.loads(initials)
+
+
+class Format(NamedTuple):
+ resolution: int
+ codec: str # h264 > av1
+ url: AbsoluteHttpURL
@dataclasses.dataclass(frozen=True, slots=True)
@@ -217,7 +231,7 @@ class Video:
best_mp4: Format
-def _parse_video(initials: dict[str, Any]):
+def _parse_video(initials: dict[str, Any]) -> Video:
video: dict[str, Any] = initials["videoModel"]
hls_sources: list[Format] = []
@@ -245,12 +259,6 @@ def _parse_video(initials: dict[str, Any]):
)
-class Format(NamedTuple):
- resolution: int
- codec: str # h264 > av1
- url: AbsoluteHttpURL
-
-
def _parse_http_sources(initials: dict[str, Any]) -> Iterable[Format]:
seen_urls: set[AbsoluteHttpURL] = set()
@@ -268,7 +276,8 @@ def _parse_http_sources(initials: dict[str, Any]) -> Iterable[Format]:
continue
seen_urls.add(url)
- yield Format(int(quality.removesuffix("p")), codec, url)
+ resolution = int(quality.removesuffix("p"))
+ yield Format(resolution, codec, url)
def _parse_xplayer_sources(initials: dict[str, Any]) -> Iterable[Format]:
diff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.py
index c6f6f4b78..de09c4fbe 100644
--- a/cyberdrop_dl/utils/utilities.py
+++ b/cyberdrop_dl/utils/utilities.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import contextlib
import inspect
+import itertools
import json
import os
import platform
@@ -619,6 +620,11 @@ def call_w_valid_kwargs(cls: Callable[..., R], kwargs: Mapping[str, Any]) -> R:
return cls(**get_valid_kwargs(cls, kwargs))
+def xor_decrypt(encrypted_data: bytes, key: bytes) -> str:
+ data = bytearray(b_input ^ b_key for b_input, b_key in zip(encrypted_data, itertools.cycle(key)))
+ return data.decode("utf-8", errors="ignore")
+
+
log_cyan = partial(log_with_color, style="cyan", level=20)
log_yellow = partial(log_with_color, style="yellow", level=20)
log_green = partial(log_with_color, style="green", level=20)
diff --git a/tests/crawlers/test_cases/xhamster.py b/tests/crawlers/test_cases/xhamster.py
index 99f8f1f8b..f5b758d3c 100644
--- a/tests/crawlers/test_cases/xhamster.py
+++ b/tests/crawlers/test_cases/xhamster.py
@@ -71,12 +71,12 @@ TEST_CASES = [
"datetime": 1738917721,
},
],
- 31,
+ 33,
),
(
"https://xhamster.com/creators/danielagomezz/exclusive",
[],
- 29,
+ 31,
),
(
"https://xhamster.com/creators/danielagomezz/photos",