Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
feat: add Pawchive support (#2000)
NTFSvolume78be09103664
diff --git a/cyberdrop_dl/config/crawlers.py b/cyberdrop_dl/config/crawlers.pyindex fc90b5ef6..db4c3abaa 100644--- a/cyberdrop_dl/config/crawlers.py+++ b/cyberdrop_dl/config/crawlers.py@@ -8,6 +8,20 @@ from cyberdrop_dl.models.types import HttpURL, NonEmptyStrfrom cyberdrop_dl.models.validators import remove_duplicates+class KemonoConfig(ConfigModel):+ file: bool = True+ "Download the main file in a post (if any)"++ attachments: bool = True+ "Download all attachments in a post (may or may not include `file`)"++ content_urls: bool = True+ "Download any URL found inside the description (text) of a post (slower)"++ embed: bool = True+ "Download the embedded file from third party sites (if any)(mega.nz, pcloud, dropbox, etc..)"++class TikTokConfig(ConfigModel):original: bool = False"Download videos in original quality (slower)"@@ -57,3 +71,4 @@ class Crawlers(ConfigGroup, name=None):generic: GenericCrawlers = Field(default_factory=GenericCrawlers)one_pace: OnePaceConfig = Field(default_factory=OnePaceConfig)tiktok: TikTokConfig = Field(default_factory=TikTokConfig)+ pawchive: KemonoConfig = Field(default_factory=KemonoConfig)diff --git a/cyberdrop_dl/config/default.yaml b/cyberdrop_dl/config/default.yamlindex b8b404f27..d58154638 100644--- a/cyberdrop_dl/config/default.yaml+++ b/cyberdrop_dl/config/default.yaml@@ -35,6 +35,11 @@ crawlers:wordpress_media: []one_pace:prefer_dub: false+ pawchive:+ attachments: true+ content_urls: true+ embed: true+ file: truetiktok:original: falsedeep_scrape: falsediff --git a/cyberdrop_dl/config/schema.json b/cyberdrop_dl/config/schema.jsonindex 098f63806..6683f5dff 100644--- a/cyberdrop_dl/config/schema.json+++ b/cyberdrop_dl/config/schema.json@@ -153,6 +153,9 @@},"tiktok": {"$ref": "#/$defs/TikTokConfig"+ },+ "pawchive": {+ "$ref": "#/$defs/KemonoConfig"}},"title": "Crawlers",@@ -605,6 +608,33 @@"title": "Jdownloader","type": "object"},+ "KemonoConfig": {+ "additionalProperties": false,+ "properties": {+ "file": {+ "default": true,+ "title": "File",+ "type": "boolean"+ },+ "attachments": {+ "default": true,+ "title": "Attachments",+ "type": "boolean"+ },+ "content_urls": {+ "default": true,+ "title": "Content Urls",+ "type": "boolean"+ },+ "embed": {+ "default": true,+ "title": "Embed",+ "type": "boolean"+ }+ },+ "title": "KemonoConfig",+ "type": "object"+ },"LogFiles": {"additionalProperties": false,"properties": {diff --git a/cyberdrop_dl/crawlers/kemono/__init__.py b/cyberdrop_dl/crawlers/kemono/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/cyberdrop_dl/crawlers/kemono/api.py b/cyberdrop_dl/crawlers/kemono/api.pynew file mode 100644index 000000000..2af0b03c2--- /dev/null+++ b/cyberdrop_dl/crawlers/kemono/api.py@@ -0,0 +1,147 @@+from __future__ import annotations++import itertools+from typing import TYPE_CHECKING, Any, ClassVar, Literal, overload, override++from cyberdrop_dl import signature+from cyberdrop_dl.cache import cached_method+from cyberdrop_dl.crawlers.crawler import API+from cyberdrop_dl.crawlers.kemono.models import Post, User, UserPostModel+from cyberdrop_dl.utils.dataclass import deserialize++if TYPE_CHECKING:+ from collections.abc import AsyncGenerator, Generator, Mapping++ from cyberdrop_dl.url_objects import AbsoluteHttpURL+++VALID_QUERY_PARAMS = {"o", "q", "tags", "order", "sort"}+++class KemonoAPI(API):+ ENTRYPOINT: ClassVar[AbsoluteHttpURL]++ def __init_subclass__(cls, **kwargs: Any) -> None:+ assert cls.ENTRYPOINT+ super().__init_subclass__(**kwargs)++ def __post_init__(self) -> None:+ self.post: PostEndpoint = PostEndpoint(self)+ self.creator: CreatorEndpoint = CreatorEndpoint(self)+ self.account: AccountEndpoint = AccountEndpoint(self)++ @override+ @signature.copy(API.request_json)+ async def request_json(self, *args, **kwargs) -> Any: # pyright: ignore[reportMissingParameterType]+ async with self.request(*args, **kwargs) as resp:+ return await resp.json(encoding="utf-8", content_type=False)++ @cached_method(ttl=1800)+ async def creators(self) -> dict[User, str]:+ url = self.ENTRYPOINT / "creators"+ resp: list[dict[str, Any]] = await self.request_json(url)+ return {User(u["service"], u["id"]): u["name"] for u in resp}++ async def search(self, query: Mapping[str, str]) -> AsyncGenerator[map[UserPostModel]]:+ url = self.ENTRYPOINT / "posts"+ query = dict(_filter_query(query))+ assert query+ url = url.update_query(query)+ async for posts in self.pager(url):+ yield map(UserPostModel.model_validate, posts)++ async def search_hash(self, file_hash: str) -> dict[str, Any]:+ url = self.ENTRYPOINT / "search_hash" / file_hash+ return await self.request_json(url)++ async def pager(+ self,+ url: AbsoluteHttpURL,+ step_size: int = 50,+ key: str | None = None,+ ) -> AsyncGenerator[list[dict[str, Any]]]:+ for offset in itertools.count(int(url.query.get("o") or 0), step_size):+ data = await self.request_json(url.update_query(o=offset))+ if key:+ data = data[key]+ if not data:+ break+ count = len(data)+ yield data+ if count < step_size:+ break+++class KemonoAPIEndpoint:+ api: KemonoAPI++ def __init__(self, api: KemonoAPI) -> None:+ self.api = api++ def __repr__(self) -> str:+ return f"<{type(self).__name__}>"+++class AccountEndpoint(KemonoAPIEndpoint):+ @overload+ async def favorites(self, type_: Literal["post"]) -> AsyncGenerator[map[Post]]: ...++ @overload+ async def favorites(self, type_: Literal["artist"]) -> AsyncGenerator[map[User]]: ...++ async def favorites(+ self, type_: Literal["artist", "post"]+ ) -> AsyncGenerator[map[Post]] | AsyncGenerator[map[User]]:+ url = self.api.ENTRYPOINT / "account/favorites"+ cls_ = User if type_ == "artist" else Post++ def parse(item: dict[str, Any]):+ return deserialize(cls_, item)++ async for page in self.api.pager(url):+ yield map(parse, page) # pyright: ignore[reportReturnType]+++class CreatorEndpoint(KemonoAPIEndpoint):+ async def profile(self, service: str, creator_id: str) -> dict[str, Any]:+ url = self.api.ENTRYPOINT / service / "user" / creator_id / "profile"+ return await self.api.request_json(url)++ async def links(self, service: str, creator_id: str) -> dict[str, Any]:+ url = self.api.ENTRYPOINT / service / "user" / creator_id / "links"+ return await self.api.request_json(url)++ async def tags(self, service: str, creator_id: str) -> dict[str, Any]:+ url = self.api.ENTRYPOINT / service / "user" / creator_id / "tags"+ return await self.api.request_json(url)++ async def posts(+ self, service: str, creator_id: str, query: Mapping[str, str] | None = None+ ) -> AsyncGenerator[map[UserPostModel]]:+ url = self.api.ENTRYPOINT / service / "user" / creator_id / "posts"+ if query:+ url = url.update_query(dict(_filter_query(query)))++ async for posts in self.api.pager(url):+ yield map(UserPostModel.model_validate, posts)+++class PostEndpoint(KemonoAPIEndpoint):+ async def __call__(self, service: str, creator_id: str, post_id: str) -> UserPostModel:+ url = self.api.ENTRYPOINT / service / "user" / creator_id / "post" / post_id+ resp = await self.api.request_json(url)+ return UserPostModel.model_validate(resp.get("post", resp))++ async def comments(self, service: str, creator_id: str, post_id: str) -> dict[str, Any]:+ url = self.api.ENTRYPOINT / service / "user" / creator_id / "post" / post_id / "comments"+ return await self.api.request_json(url)++ async def revisions(self, service: str, creator_id: str, post_id: str) -> dict[str, Any]:+ url = self.api.ENTRYPOINT / service / "user" / creator_id / "post" / post_id / "revisions"+ return await self.api.request_json(url)+++def _filter_query(query: Mapping[str, str]) -> Generator[tuple[str, str]]:+ for name, value in query.items():+ if value and name in VALID_QUERY_PARAMS:+ yield name, valuediff --git a/cyberdrop_dl/crawlers/kemono/kemono.py b/cyberdrop_dl/crawlers/kemono/kemono.pynew file mode 100644index 000000000..800e10131--- /dev/null+++ b/cyberdrop_dl/crawlers/kemono/kemono.py@@ -0,0 +1,224 @@+from __future__ import annotations++import re+from abc import abstractmethod+from collections.abc import Generator+from pathlib import Path+from typing import TYPE_CHECKING, Any, ClassVar, Literal++from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths+from cyberdrop_dl.exceptions import NoExtensionError, ScrapeError+from cyberdrop_dl.utils import unique+from cyberdrop_dl.utils.errors import error_handling_wrapper++if TYPE_CHECKING:+ from collections.abc import Generator, Iterable++ from cyberdrop_dl.config.crawlers import KemonoConfig+ from cyberdrop_dl.crawlers.kemono.api import KemonoAPI+ from cyberdrop_dl.crawlers.kemono.models import File, PostModel, UserPostModel+ from cyberdrop_dl.url_objects import AbsoluteHttpURL, ScrapeItem+++_find_http_urls = re.compile(r"(?:http(?!.*\.\.)[^ ]*?)(?=($|\n|\r\n|\r|\s|\"|\[/URL]|']\[|]\[|\[/img]|</|'))").finditer+++class KemonoBaseCrawler(Crawler, is_abc=True):+ __kemono_api__: ClassVar[type[KemonoAPI]]+ __kemono_cdn__: ClassVar[AbsoluteHttpURL]++ SUPPORTED_PATHS: ClassVar[SupportedPaths] = {+ "Creator": "/<service>/user/<user_id>",+ "Favorites": (+ r"/favorites?type=post|artist",+ r"/account/favorites/posts|artists",+ ),+ "Search": "/search?q=...",+ "Post": "/<service>/user/<user_id>/post/<post_id>",+ "Direct links": (+ "/data/...",+ "/thumbnail/...",+ ),+ }+ DEFAULT_POST_TITLE_FORMAT: ClassVar[str] = "{date} - {title}"++ @property+ @abstractmethod+ def __kemono_config__(self) -> KemonoConfig: ...++ def __init_subclass__(cls, **kwargs: Any) -> None:+ assert cls.__kemono_api__+ assert cls.__kemono_cdn__+ return super().__init_subclass__(**kwargs)++ def __post_init__(self) -> None:+ self.api: KemonoAPI = self.__kemono_api__.from_crawler(self)++ async def __async_post_init__(self) -> None:+ with self.catch_errors(self.PRIMARY_URL), self.disable_on_error("Unable to get list of creators from API"):+ _ = await self.api.creators()++ async def fetch(self, scrape_item: ScrapeItem) -> None:+ match scrape_item.url.parts[1:]:+ case [service, "user", creator_id, "post", post_id]:+ return await self.post(scrape_item, service, creator_id, post_id)+ case [service, "user", creator_id]:+ return await self.creator(scrape_item, service, creator_id)+ case ["favorites"] if (type_ := scrape_item.url.query.get("type")) in ("post", "artist", None):+ return await self.favorites(scrape_item, type_ or "artist")+ case ["account", "favorites", slug] if (type_ := slug.removesuffix("s")) in ("post", "artist"):+ return await self.favorites(scrape_item, type_)+ case ["posts"] if search_query := scrape_item.url.query.get("q"):+ return await self.search(scrape_item, search_query)+ case ["thumbnail" | "thumbnails" | "data", _, *_]:+ return await self._direct_file(scrape_item)+ case _:+ raise ValueError++ @error_handling_wrapper+ async def search(self, scrape_item: ScrapeItem, search_query: str) -> None:+ title = self.create_title(f"{search_query} [search]")+ scrape_item.setup_as_profile(title)+ async for posts in self.api.search(scrape_item.url.query):+ await self.__iter_user_posts(scrape_item, posts)++ @error_handling_wrapper+ async def creator(self, scrape_item: ScrapeItem, service: str, creator_id: str) -> None:+ scrape_item.setup_as_profile("")+ async for posts in self.api.creator.posts(service, creator_id, scrape_item.url.query):+ await self.__iter_user_posts(scrape_item, posts)++ @error_handling_wrapper+ async def post(self, scrape_item: ScrapeItem, service: str, creator_id: str, post_id: str) -> None:+ post = await self.api.post(service, creator_id, post_id)+ await self._user_post(scrape_item, post)++ @error_handling_wrapper+ async def favorites(self, scrape_item: ScrapeItem, type_: Literal["post", "artist"]) -> None:+ session_cookie = self.cookies.get("session")+ if not session_cookie:+ msg = "No session cookie found, cannot scrape favorites"+ raise ScrapeError(401, msg)++ scrape_item.setup_as_profile(self.create_title(f"My favorite {type_}s"))+ try:+ async for favorites in await self.api.account.favorites(type_):+ for fav in favorites:+ url = self.PRIMARY_URL / fav.web_path_qs+ self.create_task(self.run(scrape_item.create_child(url)))+ scrape_item.add_children()+ finally:+ self.update_cookies({"session": ""})++ @error_handling_wrapper+ async def _direct_file(self, scrape_item: ScrapeItem, url: AbsoluteHttpURL | None = None) -> None:+ scrape_item.url = _thumbnail_to_src(scrape_item.url)+ link = _thumbnail_to_src(url or scrape_item.url)+ checksum = Path(link.name).stem+ if await self.check_complete_by_hash(link, "sha256", checksum):+ return++ name = link.query.get("f") or link.name+ try:+ filename, ext = self.get_filename_and_ext(name)+ except NoExtensionError:+ # Some patreon URLs have another URL as the filename:+ # ex: https://kemono.su/data/7a...27ad7e40bd.jpg?f=https://www.patreon.com/media-u/Z0F..00672794_+ filename, ext = self.get_filename_and_ext(link.name)++ await self.handle_file(link, scrape_item, name, ext, custom_filename=filename)++ @error_handling_wrapper+ async def _user_post(self, scrape_item: ScrapeItem, post: UserPostModel) -> None:+ self.__check_for_ads(post)+ user_name = (await self.api.creators())[post.user]+ title = self.create_title(user_name, post.user_id)+ scrape_item.setup_as_album(title, album_id=post.user_id)+ post_title = self.create_separate_post_title(post.title, post.id, post.timestamp)+ scrape_item.append_folders(post_title)+ self._post(scrape_item, post)++ def _post(self, scrape_item: ScrapeItem, post: PostModel) -> None:+ scrape_item.uploaded_at = post.timestamp+ self.create_eager_task(self.write_metadata(scrape_item, f"post_{post.id}", post))+ self._extract_post_files(scrape_item, post)+ self._extract_urls_from_post_content(scrape_item, post)++ def _extract_post_files(self, scrape_item: ScrapeItem, post: PostModel) -> None:+ for url in unique(self.__prepare_files(post)):+ self.create_eager_task(self._direct_file(scrape_item, url))+ scrape_item.add_children()++ if self.__kemono_config__.embed and post.embed:+ embed_url = self.parse_url(post.embed.url)+ self.handle_external_links(scrape_item.create_child(embed_url))+ scrape_item.add_children()++ def _extract_urls_from_post_content(self, scrape_item: ScrapeItem, post: PostModel) -> None:+ if not (post.content and self.__kemono_config__.content_urls):+ return++ for link in _extract_urls(post.content):+ try:+ url = self.parse_url(link, trim=False)+ except ValueError:+ self.log.error("Unable to parse URL from %s in post #%s", link, post.id)+ continue++ if self.DOMAIN in url.host:+ continue++ self.handle_external_links(scrape_item.create_child(url))+ scrape_item.add_children()++ def __check_for_ads(self, post: PostModel) -> None:+ if _has_ads(post):+ self.log.warning(f"Post #{post.id} contains advertisements")++ def __prepare_files(self, post: PostModel) -> Generator[AbsoluteHttpURL]:+ if not post.has_full:+ self.log.warning("Post #%s has not been fully imported. Some (or all) files may be missing", post.id)++ def files() -> Generator[File]:+ if self.__kemono_config__.file and post.file:+ yield post.file+ if self.__kemono_config__.attachments:+ yield from post.attachments++ for file in files():+ if file.deferred or not file.path:+ self.log.warning("Skipping file '%s' in post #%s [incomplete import]", file.name, post.id)+ continue++ server = self.parse_url(file.server) if file.server else self.__kemono_cdn__+ url = server / f"data{file.path}"+ yield url.with_query(f=file.name or url.name)++ async def __iter_user_posts(self, scrape_item: ScrapeItem, posts: Iterable[UserPostModel]) -> None:+ for post in posts:+ self.__check_for_ads(post)+ new_item = scrape_item.create_child(self.parse_url(post.web_path_qs))+ if post.content or not self.__kemono_config__.content_urls:+ await self._user_post(new_item, post)+ else:+ self.create_task(self.run(new_item))+ scrape_item.add_children()+++def _thumbnail_to_src(og_url: AbsoluteHttpURL) -> AbsoluteHttpURL:+ url = og_url.with_path(og_url.path.replace("/thumbnails/", "/").replace("/thumbnail/", "/"))+ if name := og_url.query.get("f"):+ return url.with_query(f=name)+ return url+++def _has_ads(post: PostModel) -> bool:+ if post.content and "#ad" in post.content:+ return True++ ci_tags = {tag.casefold() for tag in post.tags}+ return bool(ci_tags.intersection({"ad", "#ad", "ads", "#ads"}))+++def _extract_urls(content: str) -> Generator[str]:+ return unique(match.group() for match in _find_http_urls(content))diff --git a/cyberdrop_dl/crawlers/kemono/models.py b/cyberdrop_dl/crawlers/kemono/models.pynew file mode 100644index 000000000..f2b97f57a--- /dev/null+++ b/cyberdrop_dl/crawlers/kemono/models.py@@ -0,0 +1,97 @@+import dataclasses+import datetime+from typing import Annotated, override++from pydantic import AfterValidator, BeforeValidator, Field++from cyberdrop_dl import env+from cyberdrop_dl.models import DeferredModel+from cyberdrop_dl.models.validators import falsy_as, falsy_as_none++[email protected](slots=True, frozen=True, order=True)+class User:+ service: str+ id: str++ @property+ def web_path_qs(self) -> str:+ return f"{self.service}/user/{self.id}"++[email protected](slots=True, frozen=True, order=True)+class Post:+ service: str+ user: str+ id: str++ @property+ def web_path_qs(self) -> str:+ return f"{self.service}/user/{self.user}/post/{self.id}"++[email protected](slots=True, frozen=True)+class File:+ path: str = ""+ name: str | None = None # Sometimes present+ server: str | None = None # Sometimes present in attachments+ deferred: bool = False++[email protected](slots=True, frozen=True)+class Embed:+ url: str+ subject: str+ description: str+++def _parse_tags(tags: object) -> object:+ tags = falsy_as(tags, ())+ if type(tags) is str:+ if tags.startswith("{") and tags.endswith("}"):+ tags = tags[1:-1]+ return [t.strip('"') for t in tags.split(",")]+ return tags+++def _assume_utc[T: datetime.datetime](date: T) -> T:+ if date.tzinfo is None:+ return date.replace(tzinfo=datetime.UTC)+ return date+++type AwareDatetime = Annotated[datetime.datetime, AfterValidator(_assume_utc)]+++class PostModel(DeferredModel, extra="allow" if env.DEBUG_MODE else "ignore"):+ id: str+ content: str | None = None # search results has no "content" key, only "substring"++ file: Annotated[File | None, BeforeValidator(falsy_as_none)] = None+ attachments: tuple[File, ...] = ()+ published: AwareDatetime | None = None+ added: AwareDatetime | None = None+ edited: AwareDatetime | None = None+ timestamp: int | None = None+ tags: Annotated[tuple[str, ...], BeforeValidator(_parse_tags)] = ()+ embed: Annotated[Embed | None, BeforeValidator(falsy_as_none)] = None+ has_full: bool = True++ @override+ def model_post_init(self, *_: object) -> None:+ if date := self.published or self.added:+ self.timestamp = int(date.timestamp())+++class UserPostModel(PostModel):+ service: str+ user_id: str = Field(validation_alias="user")+ title: str++ @property+ def user(self) -> User:+ return User(self.service, self.user_id)++ @property+ def web_path_qs(self) -> str:+ return f"{self.service}/user/{self.user_id}/post/{self.id}"diff --git a/cyberdrop_dl/crawlers/kemono/pawchive.py b/cyberdrop_dl/crawlers/kemono/pawchive.pynew file mode 100644index 000000000..481e3cd26--- /dev/null+++ b/cyberdrop_dl/crawlers/kemono/pawchive.py@@ -0,0 +1,29 @@+from __future__ import annotations++from typing import TYPE_CHECKING, ClassVar, override++from cyberdrop_dl.crawlers.kemono.api import KemonoAPI+from cyberdrop_dl.crawlers.kemono.kemono import KemonoBaseCrawler+from cyberdrop_dl.url_objects import AbsoluteHttpURL++if TYPE_CHECKING:+ from cyberdrop_dl.config.crawlers import KemonoConfig+++class PawchiveAPI(KemonoAPI):+ # https://pawchive.pw/api/swagger_schema+ ENTRYPOINT: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://pawchive.pw/api/v1")+++class PawchiveCrawler(KemonoBaseCrawler):+ __kemono_api__: ClassVar[type[KemonoAPI]] = PawchiveAPI+ __kemono_cdn__: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://file.pawchive.pw")++ PRIMARY_URL: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://pawchive.pw")+ DOMAIN: ClassVar[str] = "pawchive"+ OLD_DOMAINS: ClassVar[tuple[str, ...]] = ("pawchive.st",)++ @property+ @override+ def __kemono_config__(self) -> KemonoConfig:+ return self.config.crawlers.pawchivediff --git a/docs/assets/pawchive_embed.png b/docs/assets/pawchive_embed.pngnew file mode 100644index 000000000..2385328b5Binary files /dev/null and b/docs/assets/pawchive_embed.png differdiff --git a/docs/reference/config/crawlers.md b/docs/reference/config/crawlers.mdindex 487d270e0..a47e48da9 100644--- a/docs/reference/config/crawlers.md+++ b/docs/reference/config/crawlers.md@@ -14,12 +14,7 @@ The name of the crawer is the title of their section in the page (in bold).```yamlcrawlers:- generic:- chevereto: []- discourse: []- kvs: []- wordpress_html: []- wordpress_media: []+ disabled: []```# `generic`@@ -70,6 +65,16 @@ Supported generic crawlers:| --------------- | ------- || `list[HttpURL]` | `[]` |+```yaml+crawlers:+ generic:+ chevereto: []+ discourse: []+ kvs: []+ wordpress_html: []+ wordpress_media: []+```+# Bandcamp## `formats`@@ -114,6 +119,58 @@ Download audios as `.mp3` files even if WAV (high quality) versions are availablDownload episodes with english audio tracks instead of japanese (if available)+# Pawchive++## `file`++| Type | Default |+| ------ | ------- |+| `Bool` | `true` |++Download the main file in a post (if any)++## `attachments`++| Type | Default |+| ------ | ------- |+| `Bool` | `true` |++Download all attachments in a post (may or may not include `file`)++## `content_urls`++| Type | Default |+| ------ | ------- |+| `Bool` | `true` |++Scan the description (text) in a post and download any URL found++{% hint style="warning" %}+This option slows down scraping significally. The default response from a search query does not return the content of each post.+`cyberdrop-dl` needs to make an additional request for each post to get its content (50x requests in total).+{% endhint %}++## `embed`++| Type | Default |+| ------ | ------- |+| `Bool` | `true` |++Download the embedded file from third party sites (if any)(mega.nz, pcloud, dropbox, etc..)++Embedded files show up as clickable boxes on the website:++++```yaml+crawlers:+ pawchive:+ attachments: true+ content_urls: true+ embed: true+ file: true+```+# Tiktok## `original`diff --git a/tests/crawlers/test_cases/pawchive.py b/tests/crawlers/test_cases/pawchive.pynew file mode 100644index 000000000..4304bb93e--- /dev/null+++ b/tests/crawlers/test_cases/pawchive.py@@ -0,0 +1,51 @@+DOMAIN = "pawchive"+TEST_CASES = [+ {+ "url": "https://pawchive.pw/patreon/user/36069133/post/162746868",+ "results": [+ {+ "url": "https://file.pawchive.pw/data/78/c9/78c98dc60e50aa82c0bcedb80507ad6e510a361a2352a7da8acc73511285f9d9.jpg?f=691949417.jpg",+ "filename": "691949417.jpg",+ "debrid_url": None,+ "original_filename": "691949417.jpg",+ "referer": "https://pawchive.pw/patreon/user/36069133/post/162746868",+ "album_id": "36069133",+ "uploaded_at": 1783094455,+ "download_folder": "re:Natalie Gold (Pawchive)",+ },+ {+ "url": "https://file.pawchive.pw/data/1c/55/1c55feb918e8c9685215d42a09e397d375ab7359168b8ed4090a444b7d8a24d6.mp4?f=691949417.mp4",+ "filename": "691949417.mp4",+ "debrid_url": None,+ "original_filename": "691949417.mp4",+ "referer": "https://pawchive.pw/patreon/user/36069133/post/162746868",+ "album_id": "36069133",+ "download_folder": "re:Natalie Gold (Pawchive)",+ },+ {+ "url": "https://file.pawchive.pw/data/a7/70/a7709ff3f6b955fc8e6e0c3ffac60e66e2ade2f0b29e26209e927557ef8dfd18.png?f=691949550.png",+ "filename": "691949550.png",+ "debrid_url": None,+ "original_filename": "691949550.png",+ "referer": "https://pawchive.pw/patreon/user/36069133/post/162746868",+ "album_id": "36069133",+ "download_folder": "re:Natalie Gold (Pawchive)",+ },+ ],+ "count": 3,+ },+ {+ "url": "https://pawchive.pw/patreon/user/177727722",+ "results": [+ {+ "url": "re:https://file.pawchive.pw/data/",+ "debrid_url": None,+ "referer": "re:https://pawchive.pw/patreon/user/177727722/post/",+ "album_id": "177727722",+ "uploaded_at": int,+ "download_folder": "re:KRAPAO (Pawchive)",+ },+ ],+ "count": range(11, 20),+ },+]diff --git a/tests/crawlers/test_pawchive.py b/tests/crawlers/test_pawchive.pynew file mode 100644index 000000000..97e1cb81f--- /dev/null+++ b/tests/crawlers/test_pawchive.py@@ -0,0 +1,134 @@+import asyncio+import datetime+from typing import Any++import aiohttp+import pytest++from cyberdrop_dl.crawlers.kemono.kemono import _extract_urls, _has_ads+from cyberdrop_dl.crawlers.kemono.models import Embed, File, UserPostModel, _parse_tags++pytestmark = pytest.mark.crawler_test_case+++def request_json(url: str) -> Any:+ async def fetch():+ async with aiohttp.request("GET", url) as resp:+ return await resp.json(encoding="utf8", content_type=None)++ return asyncio.run(fetch())++[email protected](scope="session")+def post_resp() -> dict[str, Any]:+ return request_json("https://pawchive.st/api/v1/patreon/user/3295915/post/129540190")++[email protected](scope="session")+def post_resp_w_embeds() -> dict[str, Any]:+ return request_json("https://pawchive.pw/api/v1/patreon/user/47101380/post/128071303")+++def post(post_resp: dict[str, Any]) -> UserPostModel:+ return UserPostModel.model_validate(post_resp)+++def test_post_validation(post_resp: dict[str, Any]) -> None:+ post = UserPostModel.model_validate(post_resp)+ content = """<p>Hey everyone! Its been a long time in the making. I'm really proud of this one and I hope you all like is as much as I do! I really tried my</p><p>Hey everyone!</p><p>Its been a long time in the making. I'm really proud of this one and I hope you all like is as much as I do! I really tried my best to do the characters justice and add a bit more comedy in this one!</p><p>In the next week I'll be doing an update on the other projects and when they're projected to finish! Right now I just have Alya and Sono Bisque Doll in the making but I'll probably be planning another in the next month or so using a poll!</p><h3><strong>Here is the </strong><a href="https://www.dropbox.com/scl/fi/msac9283y2oieluv3pfcz/DDN-PATRON-ONLY.mp4?rlkey=l1vofvgtumm0cimqr0k5dm47p&st=mvhmkx04&dl=0">LINK </a><strong>to the full animation!</strong></h3><p>Thanks for your patience and everything!</p>"""+ assert post.id == "129540190"+ assert post.content == content+ assert post.file is None+ assert post.attachments == (+ File(+ path="/4f/3a/4f3a65f8e123dfc1fb0a91ae7f001b598c96135695e977701daf55d528145d74.png",+ name="Timeline 1_0242.00_08_06_14.Still002.png",+ server=None,+ ),+ )+ assert post.published == datetime.datetime(2025, 5, 21, 18, 11, 4, tzinfo=datetime.UTC)+ assert post.added == datetime.datetime(2026, 6, 11, 21, 15, 32, 24479, tzinfo=datetime.UTC)+ assert post.edited == datetime.datetime(2026, 7, 3, 21, 13, 46, tzinfo=datetime.UTC)+ assert post.timestamp == 1747851064+ assert post.tags == ("Animation", "Announcement")+ assert post.embed is None+ assert post.has_full is True+ assert post.service == "patreon"+ assert post.user_id == "3295915"+ assert post.title == "DANDADAN FULL ANIMATION!!"+ assert post.web_path_qs == "patreon/user/3295915/post/129540190"+ assert _has_ads(post) is False+++ ("content", "expected"),+ [+ (+ "<p>Who would have through that good guys had a 'no killing' rule?...</p><p><a href=\"https://www.dropbox.com/scl/fi/wsgws25ma0hyqggfwkwcd/Harley-Quinn-4x01-4x02.mp4?rlkey=lqf7wqu7mj6uwjlysoewqg0fw&st=00z4mrmq&dl=0\">https://www.dropbox.com/scl/fi/wsgws25ma0hyqggfwkwcd/Harley-Quinn-4x01-4x02.mp4?rlkey=lqf7wqu7mj6uwjlysoewqg0fw&st=00z4mrmq&dl=0</a></p>",+ [+ "https://www.dropbox.com/scl/fi/wsgws25ma0hyqggfwkwcd/Harley-Quinn-4x01-4x02.mp4?rlkey=lqf7wqu7mj6uwjlysoewqg0fw&st=00z4mrmq&dl=0"+ ],+ ),+ (+ "<p>Hey everyone! Its been a long time in the making. I'm really proud of this one and I hope you all like is as much as I do! I really tried my</p><p>Hey everyone!</p><p>Its been a long time in the making. I'm really proud of this one and I hope you all like is as much as I do! I really tried my best to do the characters justice and add a bit more comedy in this one!</p><p>In the next week I'll be doing an update on the other projects and when they're projected to finish! Right now I just have Alya and Sono Bisque Doll in the making but I'll probably be planning another in the next month or so using a poll!</p><h3><strong>Here is the </strong><a href=\"https://www.dropbox.com/scl/fi/ze2v1bih3lwvdjqn9syde/DDN-PATRON-ONLY.mp4?rlkey=oidlzqufodhr0nra3jfrgguxx&st=urfuvf73&dl=0\">LINK </a><strong>to the full animation!</strong></h3><p>Thanks for your patience and everything!</p>",+ [+ "https://www.dropbox.com/scl/fi/ze2v1bih3lwvdjqn9syde/DDN-PATRON-ONLY.mp4?rlkey=oidlzqufodhr0nra3jfrgguxx&st=urfuvf73&dl=0"+ ],+ ),+ ],+)+def test_extract_urls_from_content(content: str, expected: list[str]) -> None:+ found = list(_extract_urls(content))+ assert found+ assert found == expected+++def test_validation_of_post_not_archived_yet(post_resp_w_embeds: dict[str, Any]) -> None:+ post = UserPostModel.model_validate(post_resp_w_embeds)+ assert post.id == "128071303"+ assert post.content == ""+ assert post.file == File(+ path="/83/66/8366796e0d9fadd5e22ae8f8ea32d1b539d54e25e9da19f906fa36d1cf973cc2.jpg",+ name="461372899.jpg",+ server=None,+ )+ assert post.attachments == ()+ assert post.published == datetime.datetime(2025, 5, 3, 17, 12, 47, tzinfo=datetime.UTC)+ assert post.added == datetime.datetime(2026, 6, 10, 21, 30, 49, 920931, tzinfo=datetime.UTC)+ assert post.edited is None+ assert post.timestamp == 1746292367+ assert post.tags == ("Naughty ASMR",)+ assert post.embed == Embed(+ url="https://u.pcloud.link/publink/show?code=XZDlYb5ZlyjdRy0vl0bJWMbT2L2cp5RbUCFX",+ subject="ASMR ~ Girl Next Door ~ Patreon EXCLUSIVE.mp4 - Shared with pCloud",+ description="Store videos in pCloud. Share them with just the right people. Access them on any device. Create a free account now!",+ )+ assert post.has_full is False+ assert post.service == "patreon"+ assert post.user_id == "47101380"+ assert post.title == "ASMR ~ Girl Next Door ~ Patreon EXCLUSIVE"+++ ("tags", "expected"),+ [+ (+ '{animation,"animation 2d",anime,"fan animation",fanart,fedorartt,"genshin impact"}',+ ["animation", "animation 2d", "anime", "fan animation", "fanart", "fedorartt", "genshin impact"],+ ),+ (+ 'animation,"animation 2d",anime,"fan animation",fanart,fedorartt,"genshin impact"',+ ["animation", "animation 2d", "anime", "fan animation", "fanart", "fedorartt", "genshin impact"],+ ),+ (+ ["animation", "animation 2d", "anime", "fan animation", "fanart", "fedorartt", "genshin impact"],+ ["animation", "animation 2d", "anime", "fan animation", "fanart", "fedorartt", "genshin impact"],+ ),+ ("null", ()),+ (None, ()),+ ],+)+def test_tags_validation(tags: object, expected: list[str]) -> None:+ result = _parse_tags(tags)+ assert result == expected