Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: move xor logic out of Chevereto (JPG5) (#1604)

NTFSvolume8b047e4cccb4
diff --git a/cyberdrop_dl/crawlers/_chevereto.py b/cyberdrop_dl/crawlers/_chevereto.py
index 6909c9693..e050ac055 100644
--- a/cyberdrop_dl/crawlers/_chevereto.py
+++ b/cyberdrop_dl/crawlers/_chevereto.py
@@ -1,17 +1,16 @@
from __future__ import annotations
-import base64
import urllib.parse
-from typing import TYPE_CHECKING, ClassVar, final
+from typing import TYPE_CHECKING, Any, ClassVar, final
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, json, open_graph
-from cyberdrop_dl.utils.utilities import error_handling_wrapper, xor_decrypt
+from cyberdrop_dl.utils.utilities import error_handling_wrapper
if TYPE_CHECKING:
- from collections.abc import Generator
+ from collections.abc import AsyncGenerator, Generator
from bs4 import BeautifulSoup
@@ -29,9 +28,6 @@ class Selector:
MAIN_IMAGE = css.CssAttributeSelector("div#image-viewer img", "src")
-_DECRYPTION_KEY = b"seltilovessimpcity@simpcityhatesscrapers"
-
-
class CheveretoCrawler(Crawler, is_generic=True):
SUPPORTED_PATHS: ClassVar[dict[str, str | tuple[str, ...]]] = {
"Album": (
@@ -56,13 +52,13 @@ class CheveretoCrawler(Crawler, is_generic=True):
),
"Direct links": "",
}
- NEXT_PAGE_SELECTOR = Selector.NEXT_PAGE
+ NEXT_PAGE_SELECTOR: ClassVar[str] = Selector.NEXT_PAGE
DEFAULT_TRIM_URLS: ClassVar[bool] = False
CHEVERETO_SUPPORTS_VIDEO: ClassVar[bool] = True
- def __init_subclass__(cls, **kwargs) -> None:
+ def __init_subclass__(cls, **kwargs: Any) -> None:
if not cls.CHEVERETO_SUPPORTS_VIDEO:
- cls.SUPPORTED_PATHS = paths = cls.SUPPORTED_PATHS.copy() # type: ignore[reportIncompatibleVariableOverride]
+ cls.SUPPORTED_PATHS = paths = cls.SUPPORTED_PATHS.copy() # type: ignore[reportIncompatibleVariableOverride] # pyright: ignore[reportConstantRedefinition]
_ = paths.pop("Video", None)
super().__init_subclass__(**kwargs)
@@ -103,10 +99,26 @@ class CheveretoCrawler(Crawler, is_generic=True):
case _:
return url
+ async def _get_final_album_url(self, url: AbsoluteHttpURL) -> AbsoluteHttpURL:
+ if "category" in url.parts:
+ return url
+
+ # We need the full URL (aka "/<name>.<id>") to fetch sub albums
+ while "." not in (url.name or url.parent.name):
+ url = await self._get_redirect_url(url)
+
+ return url
+
+ async def web_pager(
+ self, url: AbsoluteHttpURL, next_page_selector: str | None = None, *, cffi: bool = False, **kwargs: Any
+ ) -> AsyncGenerator[BeautifulSoup]:
+ async for soup in super().web_pager(_sort_by_new(url), next_page_selector, cffi=cffi, trim=False, **kwargs):
+ yield soup
+
@error_handling_wrapper
async def profile(self, scrape_item: ScrapeItem, *, albums: bool = False) -> None:
title: str = ""
- async for soup in self.web_pager(_sort_by_new(scrape_item.url), trim=False):
+ async for soup in self.web_pager(scrape_item.url):
if not title:
title = self.create_title(open_graph.title(soup))
scrape_item.setup_as_profile(title)
@@ -117,46 +129,33 @@ class CheveretoCrawler(Crawler, is_generic=True):
return
- self._process_page(scrape_item, soup)
-
- async def _get_final_album_url(self, url: AbsoluteHttpURL) -> AbsoluteHttpURL:
- if "category" in url.parts:
- return url
-
- # We need the full URL (aka "/<name>.<id>") to fetch sub albums
- if "." not in url.name:
- url = await self._get_redirect_url(url)
-
- # The first redirect may have only added a trailing slash, try again
- if not url.name and "." not in url.parts[-2]:
- url = await self._get_redirect_url(url)
-
- return url
+ self._iter_album_files(scrape_item, soup)
@error_handling_wrapper
async def album(self, scrape_item: ScrapeItem, album_id: str) -> None:
- results = await self.get_album_results(album_id)
+ results: dict[str, int] = {}
title: str = ""
scrape_item.url = await self._get_final_album_url(scrape_item.url)
- async for soup in self.web_pager(_sort_by_new(scrape_item.url), trim=False):
+ async for soup in self.web_pager(scrape_item.url):
if not title:
- if _is_password_protected(soup):
- await self._unlock_password_protected_album(scrape_item)
+ if soup.select_one("form"):
+ await self._unlock_pw_protected_album(scrape_item, soup)
return await self.album(scrape_item, album_id)
+ results = await self.get_album_results(album_id)
title = open_graph.get_title(soup) or open_graph.description(soup)
title = self.create_title(title, album_id)
scrape_item.setup_as_album(title, album_id=album_id)
- self._process_page(scrape_item, soup, results)
- sub_album_url = scrape_item.url / "sub"
- async for soup in self.web_pager(_sort_by_new(sub_album_url), trim=False):
+ self._iter_album_files(scrape_item, soup, results)
+
+ async for soup in self.web_pager(scrape_item.url / "sub"):
for _, sub_album in self.iter_children(scrape_item, soup, Selector.ITEM):
self.create_task(self.run(sub_album))
- def _process_page(
+ def _iter_album_files(
self, scrape_item: ScrapeItem, soup: BeautifulSoup, results: dict[str, int] | None = None
) -> None:
results = results or {}
@@ -168,17 +167,20 @@ class CheveretoCrawler(Crawler, is_generic=True):
self.create_task(self.direct_file(new_scrape_item, src_url))
scrape_item.add_children()
- async def _unlock_password_protected_album(self, scrape_item: ScrapeItem) -> None:
+ async def _unlock_pw_protected_album(self, scrape_item: ScrapeItem, soup: BeautifulSoup) -> None:
if not scrape_item.password:
raise PasswordProtectedError
soup = await self.request_soup(
_sort_by_new(scrape_item.url / ""),
method="POST",
- data={"content-password": scrape_item.password},
+ data={
+ "auth_token": css.select(soup, "[name=auth_token]", "value"),
+ "content-password": scrape_item.password,
+ },
)
- if _is_password_protected(soup):
+ if soup.select_one("form"):
raise PasswordProtectedError(message="Wrong password")
@error_handling_wrapper
@@ -202,14 +204,6 @@ class CheveretoCrawler(Crawler, is_generic=True):
scrape_item.possible_datetime = self.parse_iso_date(Selector.DATE(soup))
await self.direct_file(scrape_item, source)
- def parse_url(
- 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("/"):
- 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)
-
def _get_album_files(self, soup: BeautifulSoup) -> Generator[tuple[AbsoluteHttpURL, AbsoluteHttpURL]]:
for item in soup.select(".list-item[data-object]"):
web_url = self.parse_url(css.select(item, "a.image-container", "href"))
@@ -219,10 +213,6 @@ class CheveretoCrawler(Crawler, is_generic=True):
yield self.transform_url(web_url), src_url
-def _is_password_protected(soup: BeautifulSoup) -> bool:
- return "This content is password protected" in soup.text
-
-
def _id(slug: str) -> str:
return slug.rsplit(".")[-1]
diff --git a/cyberdrop_dl/crawlers/jpg5.py b/cyberdrop_dl/crawlers/jpg5.py
index 537c368b3..61bd026b6 100644
--- a/cyberdrop_dl/crawlers/jpg5.py
+++ b/cyberdrop_dl/crawlers/jpg5.py
@@ -1,22 +1,27 @@
from __future__ import annotations
-from typing import Final
+import base64
+from typing import TYPE_CHECKING, ClassVar, Final
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL, ScrapeItem
-from cyberdrop_dl.utils.utilities import error_handling_wrapper
+from cyberdrop_dl.utils.utilities import error_handling_wrapper, xor_decrypt
from ._chevereto import CheveretoCrawler
-CDN: Final = "selti-delivery.ru"
+if TYPE_CHECKING:
+ from cyberdrop_dl.crawlers.crawler import RateLimit, SupportedDomains
+
+_CDN: Final = "selti-delivery.ru"
+_DECRYPTION_KEY: Final = b"seltilovessimpcity@simpcityhatesscrapers"
class JPG5Crawler(CheveretoCrawler):
- SUPPORTED_DOMAINS = "selti-delivery.ru", "jpg7.cr", "jpg6.su"
- DOMAIN = "jpg5.su"
- FOLDER_DOMAIN = "JPG5"
- PRIMARY_URL = AbsoluteHttpURL("https://jpg6.su")
- CHEVERETO_SUPPORTS_VIDEO = False
- OLD_DOMAINS = (
+ SUPPORTED_DOMAINS: ClassVar[SupportedDomains] = "selti-delivery.ru", "jpg7.cr", "jpg6.su"
+ DOMAIN: ClassVar[str] = "jpg5.su"
+ FOLDER_DOMAIN: ClassVar[str] = "JPG5"
+ PRIMARY_URL: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://jpg6.su")
+ CHEVERETO_SUPPORTS_VIDEO: ClassVar[bool] = False
+ OLD_DOMAINS: ClassVar[tuple[str, ...]] = (
"host.church",
"jpg.homes",
"jpg.church",
@@ -31,7 +36,7 @@ class JPG5Crawler(CheveretoCrawler):
"jpg5.su",
)
- _RATE_LIMIT = 2, 1
+ _RATE_LIMIT: ClassVar[RateLimit] = 2, 1
@classmethod
def transform_url(cls, url: AbsoluteHttpURL) -> AbsoluteHttpURL:
@@ -47,12 +52,20 @@ class JPG5Crawler(CheveretoCrawler):
) -> None:
link = url or scrape_item.url
- if self.is_subdomain(link) and not link.host.endswith(CDN):
+ if self.is_subdomain(link) and not link.host.endswith(_CDN):
server, *_ = link.host.rsplit(".", 2)
- link = link.with_host(f"{server}.{CDN}")
+ link = link.with_host(f"{server}.{_CDN}")
await super().direct_file(scrape_item, link, assume_ext)
+ def parse_url(
+ 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("/"):
+ 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)
+
def fix_db_referer(referer: str) -> str:
url = AbsoluteHttpURL(referer)