Skip to content

Bulk asynchronous downloader for multiple file hosts

feat: allow mapping URLs to generic crawlers (#1092)

NTFSvolumea5484250dbab
diff --git a/cyberdrop_dl/config/config_model.py b/cyberdrop_dl/config/config_model.py
index 797886155..32d67695b 100755
--- a/cyberdrop_dl/config/config_model.py
+++ b/cyberdrop_dl/config/config_model.py
@@ -92,7 +92,8 @@ class Logs(PathAliasModel):
@field_validator("logs_expire_after", mode="before")
@staticmethod
def parse_logs_duration(input_date: timedelta | str | int | None) -> timedelta | str | None:
- return falsy_as(input_date, None, to_timedelta)
+ if value := falsy_as(input_date, None):
+ return to_timedelta(value)
def _set_output_filenames(self, now: datetime) -> None:
self.log_folder.mkdir(exist_ok=True, parents=True)
@@ -136,7 +137,7 @@ class MediaDurationLimits(BaseModel):
@field_validator("*", mode="before")
@staticmethod
- def parse_runtime_duration(input_date: timedelta | str | int | None) -> timedelta:
+ def parse_runtime_duration(input_date: timedelta | str | int | None) -> timedelta | str:
"""Parses `datetime.timedelta`, `str` or `int` into a timedelta format.
for `str`, the expected format is `value unit`, ex: `5 days`, `10 minutes`, `1 year`
valid units:
diff --git a/cyberdrop_dl/config/global_model.py b/cyberdrop_dl/config/global_model.py
index 61281d22a..b7a7fef78 100755
--- a/cyberdrop_dl/config/global_model.py
+++ b/cyberdrop_dl/config/global_model.py
@@ -5,7 +5,7 @@ from pydantic import BaseModel, ByteSize, NonNegativeFloat, PositiveInt, field_s
from yarl import URL
from cyberdrop_dl.config._common import ConfigModel, Field
-from cyberdrop_dl.models.types import ByteSizeSerilized, HttpURL, NonEmptyStr
+from cyberdrop_dl.models.types import ByteSizeSerilized, HttpURL, ListNonEmptyStr, ListPydanticURL, NonEmptyStr
from cyberdrop_dl.models.validators import falsy_as, to_bytesize, to_timedelta
MIN_REQUIRED_FREE_SPACE = to_bytesize("512MB")
@@ -14,7 +14,7 @@ DEFAULT_REQUIRED_FREE_SPACE = to_bytesize("5GB")
class General(BaseModel):
allow_insecure_connections: bool = False
- disable_crawlers: list[NonEmptyStr] = []
+ disable_crawlers: ListNonEmptyStr = []
enable_generic_crawler: bool = True
flaresolverr: HttpURL | None = None
max_file_name_length: PositiveInt = 95
@@ -24,11 +24,6 @@ class General(BaseModel):
user_agent: NonEmptyStr = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0"
pause_on_insufficient_space: bool = False
- @field_validator("disable_crawlers", mode="before")
- @classmethod
- def as_list(cls, value: str | list[str]) -> list[str]:
- return falsy_as(value, [])
-
@field_validator("disable_crawlers", mode="after")
@classmethod
def unique_list(cls, value: list[str]) -> list[str]:
@@ -40,7 +35,7 @@ class General(BaseModel):
@field_validator("flaresolverr", "proxy", mode="before")
@classmethod
- def convert_to_str(cls, value: URL | str) -> str | None:
+ def convert_to_str(cls, value: str) -> str | None:
return falsy_as(value, None, str)
@field_validator("required_free_space", mode="after")
@@ -64,7 +59,7 @@ class RateLimiting(BaseModel):
@field_validator("file_host_cache_expire_after", "forum_cache_expire_after", mode="before")
@staticmethod
- def parse_cache_duration(input_date: timedelta | str | int) -> timedelta:
+ def parse_cache_duration(input_date: timedelta | str | int) -> timedelta | str:
return to_timedelta(input_date)
@property
@@ -84,7 +79,14 @@ class UIOptions(BaseModel):
vi_mode: bool = False
+class GenericCrawlerInstances(BaseModel):
+ wordpress_media: ListPydanticURL = []
+ wordpress_html: ListPydanticURL = []
+ discourse: ListPydanticURL = []
+
+
class GlobalSettings(ConfigModel):
general: General = Field(General(), "General")
rate_limiting_options: RateLimiting = Field(RateLimiting(), "Rate_Limiting_Options")
ui_options: UIOptions = Field(UIOptions(), "UI_Options")
+ generic_crawlers_instances: GenericCrawlerInstances = GenericCrawlerInstances()
diff --git a/cyberdrop_dl/crawlers/__init__.py b/cyberdrop_dl/crawlers/__init__.py
index f8e6a04df..fd4a8a2f7 100644
--- a/cyberdrop_dl/crawlers/__init__.py
+++ b/cyberdrop_dl/crawlers/__init__.py
@@ -102,7 +102,7 @@ from .yandex_disk import YandexDiskCrawler
from .youjizz import YouJizzCrawler
FORUM_CRAWLERS = DISCOURSE_CRAWLERS.union(XF_CRAWLERS)
-GENERIC_CRAWLERS = WP_GENERIC_CRAWLERS.union({DiscourseCrawler})
+GENERIC_CRAWLERS: set[type[Crawler]] = WP_GENERIC_CRAWLERS.union({DiscourseCrawler})
ALL_CRAWLERS: set[type[Crawler]] = {
crawler for name, crawler in globals().items() if name.endswith("Crawler") and crawler is not Crawler
}
diff --git a/cyberdrop_dl/crawlers/_forum.py b/cyberdrop_dl/crawlers/_forum.py
index 7409ee832..7fb70bd93 100644
--- a/cyberdrop_dl/crawlers/_forum.py
+++ b/cyberdrop_dl/crawlers/_forum.py
@@ -41,10 +41,10 @@ class ForumCrawler(Crawler, is_abc=True):
return
if self.is_attachment(link):
return await self.handle_internal_link(scrape_item.create_new(link))
- if self.PRIMARY_URL.host in scrape_item.url.host and self.stop_thread_recursion(scrape_item):
+ if self.PRIMARY_URL.host in link.host and self.stop_thread_recursion(scrape_item):
msg = f"Skipping nested thread URL {scrape_item.url} found on {scrape_item.origin}"
return self.log(msg)
- new_scrape_item = scrape_item.copy()
+ new_scrape_item = scrape_item.create_child(link)
new_scrape_item.type = None
new_scrape_item.reset_childen()
self.handle_external_links(new_scrape_item)
diff --git a/cyberdrop_dl/crawlers/crawler.py b/cyberdrop_dl/crawlers/crawler.py
index ac30a3f6b..c5113a3e6 100644
--- a/cyberdrop_dl/crawlers/crawler.py
+++ b/cyberdrop_dl/crawlers/crawler.py
@@ -4,12 +4,13 @@ import asyncio
import datetime
import re
from abc import ABC, abstractmethod
-from collections.abc import Mapping
+from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
from functools import partial, wraps
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, ParamSpec, TypeAlias, TypeVar, final
+import yarl
from aiolimiter import AsyncLimiter
from yarl import URL
@@ -656,13 +657,16 @@ class Site(NamedTuple):
_CrawlerT = TypeVar("_CrawlerT", bound=Crawler)
-def create_crawlers(urls: list[str], base_crawler: type[_CrawlerT]) -> set[type[_CrawlerT]]:
+def create_crawlers(urls: Iterable[str] | Iterable[yarl.URL], base_crawler: type[_CrawlerT]) -> set[type[_CrawlerT]]:
"""Creates new subclasses of the base crawler from the urls"""
return {_create_subclass(url, base_crawler) for url in urls}
-def _create_subclass(url_string: str, base_class: type[_CrawlerT]) -> type[_CrawlerT]:
- primary_url = remove_trailing_slash(AbsoluteHttpURL(url_string))
+def _create_subclass(url: yarl.URL | str, base_class: type[_CrawlerT]) -> type[_CrawlerT]:
+ if isinstance(url, str):
+ url = AbsoluteHttpURL(url)
+ assert is_absolute_http_url(url)
+ primary_url = remove_trailing_slash(url)
domain = primary_url.host.removeprefix("www.")
class_name = _make_crawler_name(domain)
class_attributes = Site(primary_url, domain)._asdict()
diff --git a/cyberdrop_dl/crawlers/discourse/_discourse.py b/cyberdrop_dl/crawlers/discourse/_discourse.py
index 091f78fa0..c2ae5fd55 100644
--- a/cyberdrop_dl/crawlers/discourse/_discourse.py
+++ b/cyberdrop_dl/crawlers/discourse/_discourse.py
@@ -6,14 +6,14 @@
from __future__ import annotations
import itertools
-import re
from typing import TYPE_CHECKING, Any, ClassVar, TypeVar
+from bs4 import BeautifulSoup
from pydantic import BaseModel
-from cyberdrop_dl.constants import HTTP_REGEX_LINKS
from cyberdrop_dl.crawlers._forum import MessageBoardCrawler
from cyberdrop_dl.exceptions import MaxChildrenError
+from cyberdrop_dl.utils import css
from cyberdrop_dl.utils.dates import to_timestamp
from cyberdrop_dl.utils.utilities import error_handling_wrapper, unique
@@ -97,7 +97,7 @@ class DiscourseCrawler(MessageBoardCrawler, is_generic=True):
last_post_id = None
async for post in self.iter_posts(topic):
new_scrape_item = scrape_item.create_child(
- self.PRIMARY_URL / post.path,
+ self.PRIMARY_URL / post.path.removeprefix("/"),
possible_datetime=to_timestamp(post.created_at),
)
await self.post(new_scrape_item, post)
@@ -108,7 +108,7 @@ class DiscourseCrawler(MessageBoardCrawler, is_generic=True):
break
if last_post_id:
- topic_url = self.PRIMARY_URL / topic.path
+ topic_url = self.PRIMARY_URL / topic.path.removeprefix("/")
post_url = topic_url / str(last_post_id)
await self.write_last_forum_post(topic_url, post_url)
@@ -117,7 +117,7 @@ class DiscourseCrawler(MessageBoardCrawler, is_generic=True):
remaining = topic.stream[offset : offset + _MAX_POSTS_PER_REQUEST]
if not remaining:
return
- stream = await self.make_request(PostStream, f"/t/{topic.id}/posts.json", {"post_ids[]": remaining})
+ stream = await self.make_request(PostStream, f"t/{topic.id}/posts.json", {"post_ids[]": remaining})
for post in stream.posts:
yield post
if topic.init_post_number != 1 and self.scrape_single_forum_post:
@@ -131,10 +131,14 @@ class DiscourseCrawler(MessageBoardCrawler, is_generic=True):
def extract_links(self, post: AvailablePost) -> Iterable[AbsoluteHttpURL]:
def iter_links() -> Iterable[AbsoluteHttpURL]:
+ soup = BeautifulSoup(post.content_html, "html.parser")
+ images = css.iget(soup, *css.images)
+ links = css.iget(soup, *css.links)
external_links = (ref.url for ref in post.link_counts)
- for link_str in unique(itertools.chain(external_links, get_links_by_regex(post.content_html))):
+ for link_str in unique(itertools.chain(external_links, images, links)):
try:
- yield self.parse_url(link_str)
+ if link_str:
+ yield self.parse_url(link_str)
except Exception:
continue
@@ -153,7 +157,3 @@ def _clean_url(url: AbsoluteHttpURL) -> AbsoluteHttpURL:
return url.with_path(original_path, encoded=True, keep_fragment=True, keep_query=True).with_name(
original_name, keep_fragment=True, keep_query=True
)
-
-
-def get_links_by_regex(text: str) -> Iterable[str]:
- return (match.group() for match in re.finditer(HTTP_REGEX_LINKS, text))
diff --git a/cyberdrop_dl/crawlers/discourse/models.py b/cyberdrop_dl/crawlers/discourse/models.py
index 35cb0c3e6..dbded0768 100644
--- a/cyberdrop_dl/crawlers/discourse/models.py
+++ b/cyberdrop_dl/crawlers/discourse/models.py
@@ -50,7 +50,7 @@ class PostStream(BaseModel):
@property
def posts(self) -> Iterable[AvailablePost]:
- for post in self.posts:
+ for post in self.all_posts:
if isinstance(post, AvailablePost):
yield post
@@ -70,4 +70,4 @@ class Topic(PostStream):
@property
def path(self) -> str:
- return f"/t/{self.slug}/{self.id}"
+ return f"t/{self.slug}/{self.id}"
diff --git a/cyberdrop_dl/crawlers/generic.py b/cyberdrop_dl/crawlers/generic.py
index f9c067373..360e2b5a1 100644
--- a/cyberdrop_dl/crawlers/generic.py
+++ b/cyberdrop_dl/crawlers/generic.py
@@ -104,7 +104,7 @@ class GenericCrawler(Crawler):
async def log_unsupported(self, scrape_item: ScrapeItem, msg: str = "") -> None:
log(f"Unsupported URL: {scrape_item.url} {msg}", 30)
- await self.manager.log_manager.write_unsupported_urls_log(scrape_item.url, scrape_item.origin())
+ await self.manager.log_manager.write_unsupported_urls_log(scrape_item.url, scrape_item.origin)
self.manager.progress_manager.scrape_stats_progress.add_unsupported()
diff --git a/cyberdrop_dl/crawlers/reddit.py b/cyberdrop_dl/crawlers/reddit.py
index 668392a1e..b4e1b0ac9 100644
--- a/cyberdrop_dl/crawlers/reddit.py
+++ b/cyberdrop_dl/crawlers/reddit.py
@@ -142,11 +142,9 @@ class RedditCrawler(Crawler):
if "reddit.com" not in link.host:
return self.handle_external_links(new_scrape_item)
- origin = scrape_item.origin()
- parent = scrape_item.parent()
- msg = f"found on {parent}"
- if parent != origin:
- msg += f" from {origin}"
+ msg = f"found on {scrape_item.parent}"
+ if scrape_item.parent != scrape_item.origin:
+ msg += f" from {scrape_item.origin}"
self.log(f"Skipping nested thread URL {link} {msg}")
async def gallery(self, scrape_item: ScrapeItem, submission: Submission) -> None:
diff --git a/cyberdrop_dl/crawlers/xenforo/titsintops.py b/cyberdrop_dl/crawlers/xenforo/titsintops.py
index 5550f2ee4..61c7e342e 100644
--- a/cyberdrop_dl/crawlers/xenforo/titsintops.py
+++ b/cyberdrop_dl/crawlers/xenforo/titsintops.py
@@ -27,11 +27,11 @@ class TitsInTopsCrawler(XenforoCrawler):
def pre_filter_link(self, link: str) -> str:
return link.replace("index.php?", "index.php/").replace("index.php%3F", "index.php/")
- def is_image_or_attachment(self, link_obj: Tag) -> bool:
+ def is_image_username_or_attachment(self, link_obj: Tag) -> bool:
text = css.get_text(link_obj)
if "view attachment" in text.lower():
return True
title = css.get_attr_no_error(link_obj, "title")
if title and "permanent link" in title.lower():
return True
- return super().is_image_or_attachment(link_obj)
+ return super().is_image_username_or_attachment(link_obj)
diff --git a/cyberdrop_dl/crawlers/xenforo/xenforo.py b/cyberdrop_dl/crawlers/xenforo/xenforo.py
index 871d18ecf..ba203eb3a 100644
--- a/cyberdrop_dl/crawlers/xenforo/xenforo.py
+++ b/cyberdrop_dl/crawlers/xenforo/xenforo.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import dataclasses
+import datetime
import re
from typing import TYPE_CHECKING, ClassVar
@@ -14,7 +15,7 @@ from cyberdrop_dl.crawlers._forum import ForumCrawler
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.exceptions import LoginError, MaxChildrenError, ScrapeError
from cyberdrop_dl.utils import css
-from cyberdrop_dl.utils.dates import TimeStamp
+from cyberdrop_dl.utils.dates import to_timestamp
from cyberdrop_dl.utils.utilities import (
error_handling_wrapper,
get_text_between,
@@ -49,7 +50,7 @@ class PostSelectors:
attachments: Selector = Selector(".message-attachments a[href]", "href")
content: Selector = Selector(".message-userContent") # text, links and images (NO attachments)
- date: Selector = Selector("time", "data-timestamp")
+ date: Selector = Selector("time", "datetime")
embeds: Selector = Selector("iframe", "src")
id: Selector = Selector(".u-concealed a[href]", "href") # TODO: This needs a better selector
images: Selector = Selector("img.bbImage", "src")
@@ -73,14 +74,14 @@ class XenforoSelectors:
@dataclasses.dataclass(frozen=True, slots=True, order=True)
class ForumPost:
id: int
- date: TimeStamp
+ date: datetime.datetime
article: Tag = dataclasses.field(compare=False)
content: Tag = dataclasses.field(compare=False)
@staticmethod
def new(article: Tag, selectors: PostSelectors, post_name: str = "post") -> ForumPost:
content = css.select_one(article, selectors.content.element)
- date = TimeStamp(int(css.select_one_get_attr(article, *selectors.date)))
+ date = datetime.datetime.fromisoformat(css.select_one_get_attr(article, *selectors.date))
if selectors.id.element == selectors.id.attribute:
post_id = int(css.get_attr(article, selectors.id.element))
else:
@@ -237,7 +238,9 @@ class XenforoCrawler(ForumCrawler, is_abc=True):
if scrape_this_post:
post_url = thread.url / f"{self.XF_POST_URL_PART_NAME}{current_post.id}"
new_scrape_item = scrape_item.create_new(
- thread.url, possible_datetime=current_post.date, add_parent=post_url
+ thread.url,
+ possible_datetime=to_timestamp(current_post.date),
+ add_parent=post_url,
)
self.manager.task_group.create_task(self.post(new_scrape_item, current_post))
try:
@@ -267,7 +270,7 @@ class XenforoCrawler(ForumCrawler, is_abc=True):
async def _links(self, scrape_item: ScrapeItem, post: ForumPost) -> None:
selector = self.XF_SELECTORS.posts.links
links = css.iselect(post.content, selector.element)
- valid_links = (link for link in links if not self.is_image_or_attachment(link))
+ valid_links = (link for link in links if not self.is_image_username_or_attachment(link))
await self.process_children(scrape_item, valid_links, selector.attribute)
async def _images(self, scrape_item: ScrapeItem, post: ForumPost) -> None:
@@ -362,9 +365,11 @@ class XenforoCrawler(ForumCrawler, is_abc=True):
return await super().handle_internal_link(scrape_item)
- def is_image_or_attachment(self, link_obj: Tag) -> bool:
+ def is_image_username_or_attachment(self, link_obj: Tag) -> bool:
if link_obj.select_one("img"):
return True
+ if link_obj.select_one(".username"):
+ return True
if link_str := css.get_attr_no_error(link_obj, self.XF_SELECTORS.posts.links.element):
return self.is_attachment(link_str)
return False
diff --git a/cyberdrop_dl/data_structures/url_objects.py b/cyberdrop_dl/data_structures/url_objects.py
index 8f4057e20..49ff0ce7c 100644
--- a/cyberdrop_dl/data_structures/url_objects.py
+++ b/cyberdrop_dl/data_structures/url_objects.py
@@ -301,10 +301,12 @@ class ScrapeItem:
setup_as_forum = partialmethod(setup_as, type=FORUM)
setup_as_post = partialmethod(setup_as, type=FORUM_POST)
+ @property
def origin(self) -> AbsoluteHttpURL | None:
if self.parents:
return self.parents[0]
+ @property
def parent(self) -> AbsoluteHttpURL | None:
if self.parents:
return self.parents[-1]
diff --git a/cyberdrop_dl/managers/manager.py b/cyberdrop_dl/managers/manager.py
index 3502a1dcf..e2674d1e6 100644
--- a/cyberdrop_dl/managers/manager.py
+++ b/cyberdrop_dl/managers/manager.py
@@ -192,17 +192,14 @@ class Manager:
self.progress_manager.startup()
def process_additive_args(self) -> None:
- cli_global_options = self.parsed_args.global_settings
+ cli_general_options = self.parsed_args.global_settings.general
cli_ignore_options = self.parsed_args.config_settings.ignore_options
- config_skip_hosts = self.config_manager.settings_data.ignore_options.skip_hosts
- config_only_hosts = self.config_manager.settings_data.ignore_options.only_hosts
- config_disable_crawlers = self.config_manager.global_settings_data.general.disable_crawlers
+ config_ignore_options = self.config_manager.settings_data.ignore_options
+ config_general_options = self.config_manager.global_settings_data.general
- cli_ignore_options.skip_hosts = add_or_remove_lists(config_skip_hosts, cli_ignore_options.skip_hosts)
- cli_ignore_options.only_hosts = add_or_remove_lists(config_only_hosts, cli_ignore_options.only_hosts)
- cli_global_options.general.disable_crawlers = add_or_remove_lists(
- config_disable_crawlers, cli_global_options.general.disable_crawlers
- )
+ add_or_remove_lists(cli_ignore_options.skip_hosts, config_ignore_options.skip_hosts)
+ add_or_remove_lists(cli_ignore_options.only_hosts, config_ignore_options.only_hosts)
+ add_or_remove_lists(cli_general_options.disable_crawlers, config_general_options.disable_crawlers)
def args_consolidation(self) -> None:
"""Consolidates runtime arguments with config values."""
@@ -280,23 +277,17 @@ class Manager:
constants.DISABLE_CACHE = self.parsed_args.cli_only_args.disable_cache
-def add_or_remove_lists(old_list: list[str], new_list: list[str]) -> list[str]:
+def add_or_remove_lists(cli_values: list[str], config_values: list[str]) -> None:
exclude = {"+", "-"}
-
- def add(config_list: list[str], cli_list: list[str]) -> list[str]:
- new_list_as_set = set(config_list + cli_list)
- return sorted(new_list_as_set - exclude)
-
- def remove(config_list: list[str], cli_list: list[str]) -> list[str]:
- new_list_as_set = set(config_list) - set(cli_list)
- return sorted(new_list_as_set - exclude)
-
- if new_list:
- if new_list[0] == "+":
- return add(old_list, new_list)
- if new_list[0] == "-":
- return remove(old_list, new_list)
- return new_list
+ if cli_values:
+ if cli_values[0] == "+":
+ new_values_set = set(config_values + cli_values)
+ cli_values.clear()
+ cli_values.extend(sorted(new_values_set - exclude))
+ elif cli_values[0] == "-":
+ new_values_set = set(config_values) - set(cli_values)
+ cli_values.clear()
+ cli_values.extend(sorted(new_values_set - exclude))
def merge_dicts(dict1: dict[str, Any], dict2: dict[str, Any]) -> dict[str, Any]:
diff --git a/cyberdrop_dl/models/types.py b/cyberdrop_dl/models/types.py
index f16b0d292..07736a0f0 100755
--- a/cyberdrop_dl/models/types.py
+++ b/cyberdrop_dl/models/types.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from pathlib import Path
-from typing import Annotated
+from typing import Annotated, TypeVar
import yarl
from pydantic import (
@@ -22,12 +22,14 @@ from cyberdrop_dl.models.validators import (
to_yarl_url_w_pydantyc_validation,
)
+T = TypeVar("T")
# ~~~~~ Strings ~~~~~~~
StrSerializer = PlainSerializer(str, return_type=str, when_used="json-unless-none")
NonEmptyStr = Annotated[str, StringConstraints(min_length=1, strip_whitespace=True)]
NonEmptyStrOrNone = Annotated[NonEmptyStr | None, BeforeValidator(falsy_as_none)]
ListNonEmptyStr = Annotated[list[NonEmptyStr], BeforeValidator(falsy_as_list)]
+
# ~~~~~ Paths ~~~~~~~
PathOrNone = Annotated[Path | None, BeforeValidator(falsy_as_none)]
LogPath = Annotated[Path, AfterValidator(change_path_suffix(".csv"))]
@@ -41,3 +43,4 @@ HttpURL = Annotated[yarl.URL, PlainValidator(to_yarl_url_w_pydantyc_validation),
# ~~~~~ Others ~~~~~~~
ByteSizeSerilized = Annotated[ByteSize, PlainSerializer(bytesize_to_str, return_type=str)]
ListNonNegativeInt = Annotated[list[NonNegativeInt], BeforeValidator(falsy_as_list)]
+ListPydanticURL = Annotated[list[HttpURL], BeforeValidator(falsy_as_list)]
diff --git a/cyberdrop_dl/models/validators.py b/cyberdrop_dl/models/validators.py
index 529aa3d1e..cede80af2 100755
--- a/cyberdrop_dl/models/validators.py
+++ b/cyberdrop_dl/models/validators.py
@@ -3,21 +3,34 @@ from __future__ import annotations
import re
from datetime import timedelta
from functools import singledispatch
-from typing import TYPE_CHECKING, Any, SupportsIndex, SupportsInt, TypeAlias, TypedDict
-
+from typing import (
+ TYPE_CHECKING,
+ Concatenate,
+ ParamSpec,
+ SupportsIndex,
+ SupportsInt,
+ TypeAlias,
+ TypedDict,
+ TypeVar,
+ overload,
+)
+
+import yarl
from pydantic import AnyUrl, ByteSize, HttpUrl, TypeAdapter
if TYPE_CHECKING:
from collections.abc import Callable
from pathlib import Path
- import yarl
-
_DATE_PATTERN_REGEX = r"(\d+)\s*(second|seconds|minute|minutes|hour|hours|day|days|week|weeks|month|months|year|years)"
_DATE_PATTERN = re.compile(_DATE_PATTERN_REGEX, re.IGNORECASE)
_BYTE_SIZE_ADAPTER = TypeAdapter(ByteSize)
_ConvertibleToInt: TypeAlias = str | SupportsInt | SupportsIndex
+P = ParamSpec("P")
+T = TypeVar("T")
+R = TypeVar("R")
+T2 = TypeVar("T2")
def bytesize_to_str(value: _ConvertibleToInt) -> str:
@@ -36,6 +49,8 @@ def to_yarl_url(value: AnyUrl | str, *args, **kwargs) -> yarl.URL:
def to_yarl_url_w_pydantyc_validation(value: str) -> yarl.URL:
+ if isinstance(value, yarl.URL):
+ value = str(value)
url = HttpUrl(value)
return to_yarl_url(url)
@@ -82,7 +97,7 @@ def str_to_timedelta(input_date: str) -> timedelta:
return timedelta(**time_dict)
-def to_timedelta(input_date: timedelta | str | int) -> timedelta:
+def to_timedelta(input_date: timedelta | str | int) -> timedelta | str:
"""Parses `datetime.timedelta`, `str` or `int` into a timedelta format.
For `str`, the expected format is `<value> <unit>`, ex: `5 days`, `10 minutes`, `1 year`
@@ -95,51 +110,59 @@ def to_timedelta(input_date: timedelta | str | int) -> timedelta:
return falsy_as(input_date, timedelta(0), _parse_as_timedelta)
-@singledispatch
-def _parse_as_timedelta(input_date: timedelta) -> timedelta | str:
- return input_date
+def _parse_as_timedelta(input_date: timedelta | int | str) -> timedelta | str:
+ if isinstance(input_date, timedelta):
+ return input_date
+ if isinstance(input_date, int):
+ return timedelta(days=input_date)
+ try:
+ return str_to_timedelta(input_date)
+ except ValueError:
+ return input_date # Let pydantic try to validate this
-@_parse_as_timedelta.register
-def _(input_date: int) -> timedelta:
- return timedelta(days=input_date)
+@overload
+def falsy_as(value: T, falsy_value: T2, func: None = None) -> T | T2: ...
-@_parse_as_timedelta.register
-def _(input_date: str, raise_error: bool = False) -> timedelta | str:
- try:
- return str_to_timedelta(input_date)
- except ValueError:
- if raise_error:
- raise
- return input_date
+@overload
+def falsy_as(
+ value: T, falsy_value: T2, func: Callable[Concatenate[T, P], R], *args: P.args, **kwargs: P.kwargs
+) -> T2 | R: ...
-def falsy_as(value: Any, falsy_value: Any, func: Callable | None = None, *args, **kwargs) -> Any:
+def falsy_as(
+ value: T,
+ falsy_value: T2,
+ func: Callable[Concatenate[T, P], R] | None = None,
+ *args: P.args,
+ **kwargs: P.kwargs,
+) -> T | T2 | R:
"""If `value` is falsy, returns `falsy_value`
If `value` is NOT falsy AND `func` is provided, returns `func(value, *args, **kwargs)`
Returns `value` otherwise
"""
- if isinstance(value, str) and value.casefold() in ("none", "null"):
- value = None
- if not value:
+ value_ = value
+ if isinstance(value_, str) and value_.casefold() in ("none", "null"):
+ value_ = None
+ if not value_:
return falsy_value
if not func:
- return value
- return func(value, *args, **kwargs)
+ return value_
+ return func(value_, *args, **kwargs)
-def falsy_as_list(value: Any) -> Any:
+def falsy_as_list(value: list[T]) -> list[T]:
return falsy_as(value, [])
-def falsy_as_none(value: Any) -> Any:
+def falsy_as_none(value: T) -> T | None:
return falsy_as(value, None)
-def falsy_as_dict(value: Any) -> Any:
+def falsy_as_dict(value: dict[str, T]) -> dict[str, T]:
return falsy_as(value, {})
diff --git a/cyberdrop_dl/scraper/scrape_mapper.py b/cyberdrop_dl/scraper/scrape_mapper.py
index 4fe7b1390..d3fd40534 100644
--- a/cyberdrop_dl/scraper/scrape_mapper.py
+++ b/cyberdrop_dl/scraper/scrape_mapper.py
@@ -5,7 +5,7 @@ import re
from dataclasses import Field
from datetime import date, datetime
from pathlib import Path
-from typing import TYPE_CHECKING, Self
+from typing import TYPE_CHECKING, Literal, Self
import aiofiles
import arrow
@@ -13,7 +13,10 @@ from yarl import URL
from cyberdrop_dl.constants import BLOCKED_DOMAINS, REGEX_LINKS
from cyberdrop_dl.crawlers import CRAWLERS
-from cyberdrop_dl.crawlers.crawler import Crawler
+from cyberdrop_dl.crawlers.crawler import Crawler, create_crawlers
+from cyberdrop_dl.crawlers.discourse import DiscourseCrawler
+from cyberdrop_dl.crawlers.generic import GenericCrawler
+from cyberdrop_dl.crawlers.wordpress import WordPressHTMLCrawler, WordPressMediaCrawler
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL, MediaItem, ScrapeItem
from cyberdrop_dl.downloader.downloader import Downloader
from cyberdrop_dl.exceptions import JDownloaderError, NoExtensionError
@@ -26,6 +29,7 @@ if TYPE_CHECKING:
from collections.abc import AsyncGenerator, Sequence
from types import TracebackType
+ from cyberdrop_dl.config.global_model import GenericCrawlerInstances, GlobalSettings
from cyberdrop_dl.crawlers import Crawler
from cyberdrop_dl.managers.manager import Manager
@@ -44,6 +48,7 @@ class ScrapeMapper:
self.using_input_file = False
self.groups = set()
self.count = 0
+ self.fallback_generic: GenericCrawler
"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
@@ -51,15 +56,23 @@ class ScrapeMapper:
def group_count(self) -> int:
return len(self.groups)
+ @property
+ def global_settings(self) -> GlobalSettings:
+ return self.manager.config_manager.global_settings_data
+
+ @property
+ def enable_generic_crawler(self) -> bool:
+ return self.global_settings.general.enable_generic_crawler
+
def start_scrapers(self) -> None:
"""Starts all scrapers."""
self.existing_crawlers = get_crawlers_mapping(self.manager)
- if not self.manager.config_manager.global_settings_data.general.enable_generic_crawler:
- _ = self.existing_crawlers.pop(".")
+ self.fallback_generic = GenericCrawler(self.manager)
- disable_crawlers_by_config(
- self.existing_crawlers, self.manager.config_manager.global_settings_data.general.disable_crawlers
- )
+ generic_crawlers = create_generic_crawlers_by_config(self.global_settings.generic_crawlers_instances)
+ for crawler in generic_crawlers:
+ register_crawler(self.existing_crawlers, crawler(self.manager), from_user=True)
+ disable_crawlers_by_config(self.existing_crawlers, self.global_settings.general.disable_crawlers)
def start_jdownloader(self) -> None:
"""Starts JDownloader."""
@@ -212,19 +225,15 @@ class ScrapeMapper:
async def send_to_crawler(self, scrape_item: ScrapeItem) -> None:
"""Maps URLs to their respective handlers."""
scrape_item.url = remove_trailing_slash(scrape_item.url)
- supported_domain = [key for key in self.existing_crawlers if key in scrape_item.url.host]
- is_generic = supported_domain == ["."]
+ crawler_match = match_url_to_crawler(self.existing_crawlers, scrape_item.url)
jdownloader_whitelisted = True
if self.jdownloader_whitelist:
jdownloader_whitelisted = any(domain in scrape_item.url.host for domain in self.jdownloader_whitelist)
- if supported_domain and not is_generic:
- # get most restrictive domain if multiple domain matches
- supported_domain = max(supported_domain, key=len)
- crawler = self.existing_crawlers[supported_domain]
- if not crawler.ready:
- await crawler.startup()
- self.manager.task_group.create_task(crawler.run(scrape_item))
+ if crawler_match:
+ if not crawler_match.ready:
+ await crawler_match.startup()
+ self.manager.task_group.create_task(crawler_match.run(scrape_item))
return
if self.manager.real_debrid_manager.enabled and self.manager.real_debrid_manager.is_supported(
@@ -270,11 +279,10 @@ class ScrapeMapper:
self.manager.progress_manager.scrape_stats_progress.add_unsupported(sent_to_jdownloader=success)
return
- if is_generic:
- generic_crawler = self.existing_crawlers["."]
- if not generic_crawler.ready:
- await generic_crawler.startup()
- self.manager.task_group.create_task(generic_crawler.run(scrape_item))
+ if self.enable_generic_crawler:
+ if not self.fallback_generic.ready:
+ await self.fallback_generic.startup()
+ self.manager.task_group.create_task(self.fallback_generic.run(scrape_item))
return
log(f"Unsupported URL: {scrape_item.url}", 30)
@@ -378,23 +386,63 @@ def get_crawlers_mapping(manager: Manager | None = None, include_generics: bool
global existing_crawlers
if not existing_crawlers:
for crawler in CRAWLERS:
- site_crawler = crawler(manager_)
- if site_crawler.IS_GENERIC and include_generics:
- keys = (site_crawler.GENERIC_NAME,)
+ crawler_instance = crawler(manager_)
+ register_crawler(existing_crawlers, crawler_instance, include_generics)
+ return existing_crawlers
+
+
+def register_crawler(
+ existing_crawlers: dict[str, Crawler],
+ crawler: Crawler,
+ include_generics: bool = False,
+ from_user: bool | Literal["raise"] = False,
+) -> None:
+ if crawler.IS_FALLBACK_GENERIC:
+ return
+ if crawler.IS_GENERIC and include_generics:
+ keys = (crawler.GENERIC_NAME,)
+ else:
+ keys = crawler.SCRAPE_MAPPER_KEYS
+
+ for domain in keys:
+ other = existing_crawlers.get(domain)
+ if from_user:
+ if not other and (match := match_url_to_crawler(existing_crawlers, crawler.PRIMARY_URL)):
+ other = match
+ if other:
+ msg = (
+ f"Unable to assign {crawler.PRIMARY_URL} to generic crawler {crawler.GENERIC_NAME}. "
+ f"URL conflicts with URL format of builtin crawler {other.NAME}. "
+ "URL will be ignored"
+ )
+ if from_user == "raise":
+ raise ValueError(msg)
+ log(msg, 40)
+ continue
else:
- keys = site_crawler.SCRAPE_MAPPER_KEYS
+ log(f"Successfully mapped {crawler.PRIMARY_URL} to generic crawler {crawler.GENERIC_NAME}")
- for domain in keys:
- msg = f"{domain} from {site_crawler.NAME} already registered by {existing_crawlers.get(domain)}"
- assert domain not in existing_crawlers, msg
- existing_crawlers[domain] = site_crawler
- return existing_crawlers
+ elif other:
+ msg = f"{domain} from {crawler.NAME} already registered by {other}"
+ assert domain not in existing_crawlers, msg
+ existing_crawlers[domain] = crawler
def get_unique_crawlers() -> list[Crawler]:
return sorted(set(get_crawlers_mapping(include_generics=True).values()), key=lambda x: x.INFO.site)
+def create_generic_crawlers_by_config(generic_crawlers: GenericCrawlerInstances) -> set[type[Crawler]]:
+ new_crawlers: set[type[Crawler]] = set()
+ if generic_crawlers.wordpress_html:
+ new_crawlers.update(create_crawlers(generic_crawlers.wordpress_html, WordPressHTMLCrawler))
+ if generic_crawlers.wordpress_media:
+ new_crawlers.update(create_crawlers(generic_crawlers.wordpress_media, WordPressMediaCrawler))
+ if generic_crawlers.discourse:
+ new_crawlers.update(create_crawlers(generic_crawlers.discourse, DiscourseCrawler))
+ return new_crawlers
+
+
def disable_crawlers_by_config(existing_crawlers: dict[str, Crawler], crawlers_to_disable: list[str]) -> None:
if not crawlers_to_disable:
return
@@ -422,3 +470,12 @@ def disable_crawlers_by_config(existing_crawlers: dict[str, Crawler], crawlers_t
)
log(f"Crawlers disabled by config: \n{crawlers_info}")
log_spacer(10)
+
+
+def match_url_to_crawler(existing_crawlers: dict[str, Crawler], url: AbsoluteHttpURL) -> Crawler | None:
+ # get most restrictive domain if multiple domain matches
+ try:
+ domain = max((domain for domain in existing_crawlers if domain in url.host), key=len)
+ return existing_crawlers[domain]
+ except (ValueError, TypeError):
+ return
diff --git a/cyberdrop_dl/utils/args.py b/cyberdrop_dl/utils/args.py
index 70e72e3ab..0e33c0e49 100644
--- a/cyberdrop_dl/utils/args.py
+++ b/cyberdrop_dl/utils/args.py
@@ -45,7 +45,7 @@ def is_terminal_in_portrait() -> bool:
"""Check if CDL is being run in portrait mode based on a few conditions."""
# Return True if running in portait mode, False otherwise (landscape mode)
- def check_terminal_size():
+ def check_terminal_size() -> bool:
terminal_size = get_terminal_size()
width, height = terminal_size.columns, terminal_size.lines
aspect_ratio = width / height
@@ -171,16 +171,25 @@ class ParsedArgs(AliasModel):
def _add_args_from_model(
- parser: ArgumentParser | ArgGroup, model: type[BaseModel], *, cli_args: bool = False, deprecated: bool = False
+ parser: ArgumentParser | ArgGroup,
+ model: type[BaseModel],
+ *,
+ cli_args: bool = False,
+ deprecated: bool = False,
+ prefix: str = "",
) -> None:
for name, field in model.model_fields.items():
- cli_name = name.replace("_", "-")
+ full_name = prefix + name
+ cli_name = full_name.replace("_", "-")
arg_type = type(field.default)
+ if issubclass(arg_type, BaseModel):
+ _add_args_from_model(parser, arg_type, cli_args=cli_args, deprecated=deprecated, prefix=f"{cli_name}.")
+ continue
if arg_type not in (list, set, bool):
arg_type = str
help_text = field.description or ""
default = field.default if cli_args else SUPPRESS
- default_options = {"default": default, "dest": name, "help": help_text}
+ default_options = {"default": default, "dest": full_name, "help": help_text}
name_or_flags = [f"--{cli_name}"]
alias: str = field.alias or field.validation_alias or field.serialization_alias # type: ignore
if alias and len(alias) == 1:
@@ -195,7 +204,7 @@ def _add_args_from_model(
parser.add_argument(*name_or_flags, action=action, **default_options)
continue
if cli_name == "links":
- default_options.pop("dest")
+ _ = default_options.pop("dest")
parser.add_argument(cli_name, metavar="LINK(S)", nargs="*", action="extend", **default_options)
continue
if arg_type in (list, set):
@@ -242,7 +251,7 @@ def make_parser() -> tuple[ArgumentParser, dict[str, list[ArgGroup]]]:
cli_only = parser.add_argument_group("CLI-only options")
_add_args_from_model(cli_only, CommandLineOnlyArgs, cli_args=True)
- group_lists = {
+ groups_mapping = {
"config_settings": _create_groups_from_nested_models(parser, ConfigSettings),
"global_settings": _create_groups_from_nested_models(parser, GlobalSettings),
"cli_only_args": [cli_only],
@@ -251,16 +260,16 @@ def make_parser() -> tuple[ArgumentParser, dict[str, list[ArgGroup]]]:
if USING_DEPRECATED_ARGS:
deprecated = parser.add_argument_group("deprecated")
_add_args_from_model(deprecated, DeprecatedArgs, cli_args=True, deprecated=True)
- group_lists["deprecated_args"] = [deprecated]
+ groups_mapping["deprecated_args"] = [deprecated]
- return parser, group_lists
+ return parser, groups_mapping
def get_parsed_args_dict(args: Sequence[str] | None = None) -> dict[str, dict[str, Any]]:
- parser, group_lists = make_parser()
+ parser, groups_mapping = make_parser()
namespace = parser.parse_intermixed_args(args)
parsed_args: dict[str, dict[str, Any]] = {}
- for name, groups in group_lists.items():
+ for name, groups in groups_mapping.items():
parsed_args[name] = {}
for group in groups:
group_dict = {
@@ -270,7 +279,7 @@ def get_parsed_args_dict(args: Sequence[str] | None = None) -> dict[str, dict[st
}
if group_dict:
assert group.title
- parsed_args[name][group.title] = group_dict
+ parsed_args[name][group.title] = parse_nested_values(group_dict)
if USING_DEPRECATED_ARGS:
parsed_args["deprecated_args"] = parsed_args["deprecated_args"].get("deprecated") or {}
@@ -302,3 +311,19 @@ def show_supported_sites() -> NoReturn:
table = get_crawlers_info_as_rich_table()
print(table)
sys.exit(0)
+
+
+def parse_nested_values(data_list: dict[str, Any]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+
+ for command_name, value in data_list.items():
+ inner_names = command_name.split(".")
+ current_level = result
+ for index, key in enumerate(inner_names):
+ if index < len(inner_names) - 1:
+ if key not in current_level:
+ current_level[key] = {}
+ current_level = current_level[key]
+ else:
+ current_level[key] = value
+ return result
diff --git a/cyberdrop_dl/utils/css.py b/cyberdrop_dl/utils/css.py
index e368b4675..2f2ce7d68 100644
--- a/cyberdrop_dl/utils/css.py
+++ b/cyberdrop_dl/utils/css.py
@@ -8,7 +8,7 @@ import bs4.css
from cyberdrop_dl.exceptions import ScrapeError
if TYPE_CHECKING:
- from collections.abc import Callable, Generator, Iterable
+ from collections.abc import Callable, Generator
from bs4 import Tag
@@ -112,10 +112,11 @@ def _parse_srcset(srcset: str) -> str:
return [src.split(" ")[0] for src in srcset.split(", ")][-1]
-def iget(tag: Tag, selector: str, attribute: str) -> Iterable[str]:
+def iget(tag: Tag, selector: str, attribute: str) -> Generator[str | None]:
for inner_tag in iselect(tag, selector):
- yield get_attr(inner_tag, attribute)
+ yield get_attr_or_none(inner_tag, attribute)
iframes = CssAttributeSelector("iframe", "src")
images = CssAttributeSelector("img", "srcset")
+links = CssAttributeSelector(":any-link", "href")
diff --git a/tests/test_scrape_mapper.py b/tests/test_scrape_mapper.py
new file mode 100644
index 000000000..28d11757e
--- /dev/null
+++ b/tests/test_scrape_mapper.py
@@ -0,0 +1,55 @@
+import pytest
+
+from cyberdrop_dl import crawlers
+from cyberdrop_dl.crawlers.crawler import create_crawlers
+from cyberdrop_dl.managers.manager import Manager
+from cyberdrop_dl.scraper import scrape_mapper
+
+_ = scrape_mapper.get_crawlers_mapping()
+
+TEST_BASE_CRAWLER = next(iter(crawlers.GENERIC_CRAWLERS))
+
+
+class MockProgress:
+ scraping_progress = None
+
+
+manager = Manager()
+manager.progress_manager = MockProgress() # type: ignore
+
+
+ "link",
+ [
+ "https://bunkr.com",
+ "https://dropbox.uk",
+ "https://forum.allporncomix.com",
+ "https://cyberfile.me/abhl",
+ "https://forums.plex.tv/"
+ "https://forums.socialmediagirls.com/threads/en-fr-tools-to-download-upload-content-websites-softwares-extensions.13930/#post-2070848",
+ ],
+)
+def test_generic_crawlers_that_match_supported_crawlers_should_not_be_created(link: str) -> None:
+ crawler = next(iter(create_crawlers([link], TEST_BASE_CRAWLER)))
+ with pytest.raises(ValueError) as exc_info:
+ scrape_mapper.register_crawler(scrape_mapper.existing_crawlers, crawler(manager), from_user="raise")
+ assert f"Unable to assign {link.split('/')[0]}" in str(exc_info.value)
+
+
+ "link",
+ [
+ "https://forum.otherforum.com",
+ "https://cyberfolder.me/abhl",
+ "https://meta.discourse.org/",
+ ],
+)
+def test_generic_crawlers_that_do_no_match_supported_crawlers_should_be_created(link: str) -> None:
+ crawler = next(iter(create_crawlers([link], TEST_BASE_CRAWLER)))
+ existing_crawlers = scrape_mapper.existing_crawlers.copy()
+ crawlers_before = set(existing_crawlers.values())
+ scrape_mapper.register_crawler(existing_crawlers, crawler(manager), from_user="raise")
+ new_crawlers = set(existing_crawlers.values()) - crawlers_before
+ assert len(new_crawlers) == 1
+ created_crawler = next(iter(new_crawlers))
+ assert issubclass(type(created_crawler), TEST_BASE_CRAWLER)