Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: unify all forums into a single XenForo crawler (#354)

NTFSvolumef5d8d3c0b9c9
diff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.py
index 57dfb97c4..6ef8d1692 100644
--- a/cyberdrop_dl/main.py
+++ b/cyberdrop_dl/main.py
@@ -7,7 +7,6 @@ import os
import sys
from functools import wraps
from pathlib import Path
-from textwrap import indent
from time import perf_counter
from typing import TYPE_CHECKING
@@ -190,12 +189,13 @@ def ui_error_handling_wrapper(func: Callable) -> None:
try:
return await func(*args, **kwargs)
except* Exception as e:
- exc_list = str(e)
+ exceptions = [e]
if isinstance(e, ExceptionGroup):
- exc_list = "\n".join(map(str, e.exceptions))
- exc_list = indent(exc_list, " ")
- msg = f"An error occurred, please report this to the developer with your logs file:\n{exc_list}"
- log_with_color(msg, "bold red", 50, show_in_stats=False, exc_info=e)
+ exceptions = e.exceptions
+ msg = "An error occurred, please report this to the developer with your logs file:"
+ log_with_color(msg, "bold red", 50, show_in_stats=False)
+ for exc in exceptions:
+ log_with_color(f" {exc}", "bold red", 50, show_in_stats=False, exc_info=exc)
return wrapper
diff --git a/cyberdrop_dl/scraper/crawler.py b/cyberdrop_dl/scraper/crawler.py
index 5046827bb..4d54e59fb 100644
--- a/cyberdrop_dl/scraper/crawler.py
+++ b/cyberdrop_dl/scraper/crawler.py
@@ -4,6 +4,7 @@ import asyncio
import copy
from abc import ABC, abstractmethod
from dataclasses import field
+from functools import wraps
from http.cookiejar import MozillaCookieJar
from typing import TYPE_CHECKING, Any, ClassVar
@@ -18,6 +19,8 @@ from cyberdrop_dl.utils.logger import log
from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_download_path, remove_file_id
if TYPE_CHECKING:
+ from collections.abc import Callable
+
from cyberdrop_dl.clients.scraper_client import ScraperClient
from cyberdrop_dl.managers.manager import Manager
@@ -156,17 +159,18 @@ class Crawler(ABC):
"""Returns (scrape_post, continue_scraping)"""
scrape_single_forum_post = self.manager.config_manager.settings_data.download_options.scrape_single_forum_post
+ scrape_post = continue_scraping = True
+
if scrape_single_forum_post:
- if not post_number:
- return True, False
- if post_number == current_post_number:
- return True, False
- return False, True
+ if not post_number or post_number == current_post_number:
+ continue_scraping = False
+ else:
+ scrape_post = False
- if post_number and post_number > current_post_number:
- return False, True
+ elif post_number and post_number > current_post_number:
+ scrape_post = False
- return True, True
+ return scrape_post, continue_scraping
def handle_external_links(self, scrape_item: ScrapeItem) -> None:
"""Maps external links to the scraper class."""
@@ -179,7 +183,7 @@ class Crawler(ABC):
session_cookie: str,
username: str,
password: str,
- wait_time: int = 0,
+ wait_time: int = 5,
) -> None:
"""Logs into a forum."""
if session_cookie:
@@ -271,7 +275,7 @@ class Crawler(ABC):
scrape_item.album_id = album_id or scrape_item.album_id
return scrape_item
- def create_title(self, title: str, album_id: str | None, thread_id: str | None) -> str:
+ def create_title(self, title: str, album_id: str | None = None, thread_id: str | None = None) -> str:
"""Creates the title for the scrape item."""
download_options = self.manager.config_manager.settings_data.download_options
if not title:
@@ -288,3 +292,18 @@ class Crawler(ABC):
title = f"{title} ({self.folder_domain})"
return title
+
+
+def create_task_id(func: Callable) -> None:
+ """Wrapper handles task_id creation and removal for ScrapeItems"""
+
+ @wraps(func)
+ async def wrapper(self: Crawler, *args, **kwargs):
+ scrape_item: ScrapeItem = args[0]
+ task_id = self.scraping_progress.add_task(scrape_item.url)
+ try:
+ return await func(self, *args, **kwargs)
+ finally:
+ self.scraping_progress.remove_task(task_id)
+
+ return wrapper
diff --git a/cyberdrop_dl/scraper/crawlers/celebforum_crawler.py b/cyberdrop_dl/scraper/crawlers/celebforum_crawler.py
index 07c8dc275..0dfdfe7dc 100644
--- a/cyberdrop_dl/scraper/crawlers/celebforum_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/celebforum_crawler.py
@@ -1,348 +1,21 @@
from __future__ import annotations
-import contextlib
from typing import TYPE_CHECKING
-from aiolimiter import AsyncLimiter
from yarl import URL
-from cyberdrop_dl.clients.errors import MaxChildrenError
-from cyberdrop_dl.scraper.crawler import Crawler
-from cyberdrop_dl.utils.data_enums_classes.url_objects import FORUM, FORUM_POST, ScrapeItem
-from cyberdrop_dl.utils.logger import log
-from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_filename_and_ext
+from .xenforo_crawler import PostSelectors, Selector, XenforoCrawler, XenforoSelectors
if TYPE_CHECKING:
- from bs4 import BeautifulSoup, Tag
-
from cyberdrop_dl.managers.manager import Manager
-class CelebForumCrawler(Crawler):
+class CelebForumCrawler(XenforoCrawler):
+ primary_base_domain = URL("https://celebforum.to")
+ post_selectors = PostSelectors(
+ date=Selector("time", "data-time"),
+ )
+ selectors = XenforoSelectors(posts=post_selectors)
+
def __init__(self, manager: Manager) -> None:
super().__init__(manager, "celebforum", "CelebForum")
- self.primary_base_domain = URL("https://celebforum.to")
- self.logged_in = False
- self.login_attempts = 0
- self.request_limiter = AsyncLimiter(10, 1)
-
- self.title_selector = "h1[class=p-title-value]"
- self.title_trash_selector = "a"
- self.posts_selector = "div[class*=message-main]"
- self.post_date_selector = "time"
- self.post_date_attribute = "data-time"
- self.posts_number_selector = "li[class=u-concealed] a"
- self.posts_number_attribute = "href"
- self.quotes_selector = "blockquote"
- self.posts_content_selector = "div[class=bbWrapper]"
- self.next_page_selector = "a[class*=pageNav-jump--next]"
- self.next_page_attribute = "href"
- self.links_selector = "a"
- self.links_attribute = "href"
- self.attachment_url_part = "attachments"
- self.images_selector = "img[class*=bbImage]"
- self.images_attribute = "src"
- self.videos_selector = "video source"
- self.iframe_selector = "iframe[class=saint-iframe]"
- self.videos_attribute = "src"
- self.embeds_selector = "iframe"
- self.embeds_attribute = "src"
- self.attachments_block_selector = "section[class=message-attachments]"
- self.attachments_selector = "a"
- self.attachments_attribute = "href"
-
- """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
-
- async def fetch(self, scrape_item: ScrapeItem) -> None:
- """Determines where to send the scrape item based on the url."""
- task_id = self.scraping_progress.add_task(scrape_item.url)
-
- if not self.logged_in and self.login_attempts == 0:
- login_url = self.primary_base_domain / "login"
- host_cookies = self.client.client_manager.cookies._cookies.get((self.primary_base_domain.host, ""), {})
- session_cookie = host_cookies.get("xf_user").value if "xf_user" in host_cookies else None
- if not session_cookie:
- session_cookie = self.manager.config_manager.authentication_data.forums.celebforum_xf_user_cookie
-
- username = self.manager.config_manager.authentication_data.forums.celebforum_username
- password = self.manager.config_manager.authentication_data.forums.celebforum_password
- wait_time = 5
-
- self.login_attempts += 1
- await self.forum_login(login_url, session_cookie, username, password, wait_time)
-
- if self.logged_in:
- await self.forum(scrape_item)
- else:
- log("CelebForum login failed. Skipping.", 40)
-
- self.scraping_progress.remove_task(task_id)
-
- @error_handling_wrapper
- async def forum(self, scrape_item: ScrapeItem) -> None:
- """Scrapes an album."""
- continue_scraping = True
-
- thread_url = scrape_item.url
- post_number = 0
- scrape_item.type = FORUM
- scrape_item.children = scrape_item.children_limit = 0
-
- with contextlib.suppress(IndexError, TypeError):
- scrape_item.children_limit = (
- self.manager.config_manager.settings_data.download_options.maximum_number_of_children[scrape_item.type]
- )
-
- post_sections = (scrape_item.url.parts[3], scrape_item.url.fragment)
- if len(scrape_item.url.parts) > 3 and any("post-" in sec for sec in post_sections):
- url_parts = str(scrape_item.url).rsplit("post-", 1)
- thread_url = URL(url_parts[0].rstrip("#"))
- post_number = int(url_parts[-1].strip("/")) if len(url_parts) == 2 else 0
-
- current_post_number = 0
- while True:
- async with self.request_limiter:
- soup: BeautifulSoup = await self.client.get_soup(self.domain, thread_url, origin=scrape_item)
-
- title_block = soup.select_one(self.title_selector)
- for elem in title_block.find_all(self.title_trash_selector):
- elem.decompose()
-
- thread_id = thread_url.parts[2].split(".")[-1]
- title = self.create_title(title_block.text.replace("\n", ""), None, thread_id)
-
- posts = soup.select(self.posts_selector)
- for post in posts:
- current_post_number = int(
- post.select_one(self.posts_number_selector)
- .get(self.posts_number_attribute)
- .split("/")[-1]
- .split("post-")[-1],
- )
- scrape_post, continue_scraping = self.check_post_number(post_number, current_post_number)
-
- if scrape_post:
- date = int(post.select_one(self.post_date_selector).get(self.post_date_attribute))
- new_scrape_item = self.create_scrape_item(
- scrape_item,
- thread_url,
- title,
- False,
- None,
- date,
- add_parent=thread_url.joinpath(f"post-{current_post_number}"),
- )
-
- for elem in post.find_all(self.quotes_selector):
- elem.decompose()
- post_content = post.select_one(self.posts_content_selector)
- await self.post(new_scrape_item, post_content, current_post_number)
-
- scrape_item.children += 1
- if scrape_item.children_limit and scrape_item.children >= scrape_item.children_limit:
- raise MaxChildrenError(origin=scrape_item)
-
- if not continue_scraping:
- break
-
- next_page = soup.select_one(self.next_page_selector)
- if next_page and continue_scraping:
- thread_url = next_page.get(self.next_page_attribute)
- if thread_url:
- if thread_url.startswith("/"):
- thread_url = self.primary_base_domain / thread_url[1:]
- thread_url = URL(thread_url)
- continue
- else:
- break
-
- post_string = f"post-{current_post_number}"
- if "page-" in scrape_item.url.raw_name or "post-" in scrape_item.url.raw_name:
- last_post_url = scrape_item.url.parent / post_string
- else:
- last_post_url = scrape_item.url / post_string
- await self.manager.log_manager.write_last_post_log(last_post_url)
-
- @error_handling_wrapper
- async def post(self, scrape_item: ScrapeItem, post_content: Tag, post_number: int) -> None:
- """Scrapes a post."""
- if self.manager.config_manager.settings_data.download_options.separate_posts:
- scrape_item = self.create_scrape_item(scrape_item, scrape_item.url, "")
- scrape_item.add_to_parent_title("post-" + str(post_number))
-
- scrape_item.type = FORUM_POST
- scrape_item.children = scrape_item.children_limit = 0
-
- with contextlib.suppress(IndexError, TypeError):
- scrape_item.children_limit = (
- self.manager.config_manager.settings_data.download_options.maximum_number_of_children[scrape_item.type]
- )
-
- posts_scrapers = [self.links, self.images, self.videos, self.embeds, self.attachments]
-
- for scraper in posts_scrapers:
- scrape_item.children += await scraper(scrape_item, post_content)
- if scrape_item.children_limit and scrape_item.children >= scrape_item.children_limit:
- raise MaxChildrenError(origin=scrape_item)
-
- @error_handling_wrapper
- async def links(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes links from a post."""
- links = post_content.select(self.links_selector)
- new_children = 0
- for link_obj in links:
- link = link_obj.get(self.links_attribute)
- if not link:
- continue
-
- link = link.replace(".th.", ".").replace(".md.", ".")
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- try:
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown link type: {link}", 30)
- continue
- except TypeError:
- log(f"Scrape Failed: encountered while handling {link}", 40)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def images(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes images from a post."""
- images = post_content.select(self.images_selector)
- new_children = 0
- for image in images:
- link = image.get(self.images_attribute)
- if not link:
- continue
-
- parent_check = image.parent.get("href")
- if parent_check:
- continue
-
- link = link.replace(".th.", ".").replace(".md.", ".")
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown image type: {link}", 30)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def videos(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes videos from a post."""
- videos = post_content.select(self.videos_selector)
- videos.extend(post_content.select(self.iframe_selector))
- new_children = 0
- for video in videos:
- link = video.get(self.videos_attribute)
- if not link:
- continue
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
-
- link = URL(link)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def embeds(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes embeds from a post."""
- embeds = post_content.select(self.embeds_selector)
- new_children = 0
- for embed in embeds:
- link = embed.get(self.embeds_attribute)
- if not link:
- continue
-
- link = link.replace("ifr", "watch")
-
- link = URL(link)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def attachments(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes attachments from a post."""
- attachment_block = post_content.select_one(self.attachments_block_selector)
- new_children = 0
- if not attachment_block:
- return new_children
-
- attachments = attachment_block.select(self.attachments_selector)
- for attachment in attachments:
- link = attachment.get(self.attachments_attribute)
- if not link:
- continue
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown image type: {link}", 30)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
-
- @error_handling_wrapper
- async def handle_internal_links(self, link: URL, scrape_item: ScrapeItem) -> None:
- """Handles internal links."""
- filename, ext = get_filename_and_ext(link.name, True)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "Attachments", True)
- await self.handle_file(link, new_scrape_item, filename, ext)
diff --git a/cyberdrop_dl/scraper/crawlers/chevereto_crawler.py b/cyberdrop_dl/scraper/crawlers/chevereto_crawler.py
index 42e4d98c2..0e9713904 100644
--- a/cyberdrop_dl/scraper/crawlers/chevereto_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/chevereto_crawler.py
@@ -117,7 +117,7 @@ class CheveretoCrawler(Crawler):
True,
add_parent=scrape_item.url,
)
- await self.handle_direct_link(new_scrape_item)
+ await self.fetch(new_scrape_item)
@error_handling_wrapper
async def album(self, scrape_item: ScrapeItem) -> None:
diff --git a/cyberdrop_dl/scraper/crawlers/f95zone_crawler.py b/cyberdrop_dl/scraper/crawlers/f95zone_crawler.py
index 7cea515de..532eca5e3 100644
--- a/cyberdrop_dl/scraper/crawlers/f95zone_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/f95zone_crawler.py
@@ -1,364 +1,43 @@
from __future__ import annotations
-import contextlib
from typing import TYPE_CHECKING
-from aiolimiter import AsyncLimiter
from yarl import URL
-from cyberdrop_dl.clients.errors import MaxChildrenError
-from cyberdrop_dl.scraper.crawler import Crawler
-from cyberdrop_dl.utils.data_enums_classes.url_objects import FORUM, FORUM_POST, ScrapeItem
-from cyberdrop_dl.utils.logger import log
-from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_filename_and_ext
+from cyberdrop_dl.utils.utilities import error_handling_wrapper
-if TYPE_CHECKING:
- from bs4 import BeautifulSoup, Tag
+from .xenforo_crawler import PostSelectors, Selector, XenforoCrawler, XenforoSelectors
+if TYPE_CHECKING:
from cyberdrop_dl.managers.manager import Manager
+ from cyberdrop_dl.utils.data_enums_classes.url_objects import ScrapeItem
+
+class F95ZoneCrawler(XenforoCrawler):
+ primary_base_domain = URL("https://f95zone.to")
+ post_selectors = PostSelectors(
+ date=Selector("time", "data-time"),
+ number=Selector("a[class=u-concealed]", "href"),
+ )
+ selectors = XenforoSelectors(posts=post_selectors)
-class F95ZoneCrawler(Crawler):
def __init__(self, manager: Manager) -> None:
super().__init__(manager, "f95zone", "F95Zone")
- self.primary_base_domain = URL("https://f95zone.to")
- self.logged_in = False
- self.login_attempts = 0
- self.request_limiter = AsyncLimiter(10, 1)
-
- self.title_selector = "h1[class=p-title-value]"
- self.title_trash_selector = "a"
- self.posts_selector = "div[class*=message-main]"
- self.post_date_selector = "time"
- self.post_date_attribute = "data-time"
- self.posts_number_selector = "a[class=u-concealed]"
- self.posts_number_attribute = "href"
- self.quotes_selector = "blockquote"
- self.posts_content_selector = "div[class*=message-content]"
- self.next_page_selector = "a[class*=pageNav-jump--next]"
- self.next_page_attribute = "href"
- self.links_selector = "a"
- self.links_attribute = "href"
- self.attachment_url_part = "attachments"
- self.images_selector = "img[class*=bbImage]"
- self.images_attribute = "data-src"
- self.videos_selector = "video source"
- self.iframe_selector = "iframe[class=saint-iframe]"
- self.videos_attribute = "src"
- self.embeds_selector = "iframe"
- self.embeds_attribute = "src"
- self.attachments_block_selector = "section[class=message-attachments]"
- self.attachments_selector = "a"
- self.attachments_attribute = "href"
-
- """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
-
- async def fetch(self, scrape_item: ScrapeItem) -> None:
- """Determines where to send the scrape item based on the url."""
- task_id = self.scraping_progress.add_task(scrape_item.url)
-
- if not self.logged_in and self.login_attempts == 0:
- login_url = self.primary_base_domain / "login"
- host_cookies = self.client.client_manager.cookies._cookies.get((self.primary_base_domain.host, ""), {})
- session_cookie = host_cookies.get("xf_user").value if "xf_user" in host_cookies else None
- if not session_cookie:
- session_cookie = self.manager.config_manager.authentication_data.forums.f95zone_xf_user_cookie
-
- username = self.manager.config_manager.authentication_data.forums.f95zone_username
- password = self.manager.config_manager.authentication_data.forums.f95zone_password
- wait_time = 5
-
- self.login_attempts += 1
- await self.forum_login(login_url, session_cookie, username, password, wait_time)
-
- if self.logged_in:
- await self.forum(scrape_item)
- else:
- log("F95Zone login failed. Skipping.", 40)
-
- self.scraping_progress.remove_task(task_id)
-
- @error_handling_wrapper
- async def forum(self, scrape_item: ScrapeItem) -> None:
- """Scrapes an album."""
- continue_scraping = True
-
- thread_url = scrape_item.url
- post_number = 0
- scrape_item.type = FORUM
- scrape_item.children = scrape_item.children_limit = 0
-
- with contextlib.suppress(IndexError, TypeError):
- scrape_item.children_limit = (
- self.manager.config_manager.settings_data.download_options.maximum_number_of_children[scrape_item.type]
- )
-
- post_sections = (scrape_item.url.parts[3], scrape_item.url.fragment)
- if len(scrape_item.url.parts) > 3 and any("post-" in sec for sec in post_sections):
- url_parts = str(scrape_item.url).rsplit("post-", 1)
- thread_url = URL(url_parts[0].rstrip("#"))
- post_number = int(url_parts[-1].strip("/")) if len(url_parts) == 2 else 0
-
- current_post_number = 0
- while True:
- async with self.request_limiter:
- soup: BeautifulSoup = await self.client.get_soup(self.domain, thread_url, origin=scrape_item)
-
- title_block = soup.select_one(self.title_selector)
- for elem in title_block.find_all(self.title_trash_selector):
- elem.decompose()
-
- thread_id = thread_url.parts[2].split(".")[-1]
- title = self.create_title(title_block.text.replace("\n", ""), None, thread_id)
-
- posts = soup.select(self.posts_selector)
- for post in posts:
- current_post_number = int(
- post.select_one(self.posts_number_selector)
- .get(self.posts_number_attribute)
- .split("/")[-1]
- .split("post-")[-1],
- )
- scrape_post, continue_scraping = self.check_post_number(post_number, current_post_number)
-
- if scrape_post:
- date = int(post.select_one(self.post_date_selector).get(self.post_date_attribute))
- new_scrape_item = self.create_scrape_item(
- scrape_item,
- thread_url,
- title,
- False,
- None,
- date,
- add_parent=scrape_item.url.joinpath(f"post-{current_post_number}"),
- )
-
- for elem in post.find_all(self.quotes_selector):
- elem.decompose()
- post_content = post.select_one(self.posts_content_selector)
- await self.post(new_scrape_item, post_content, current_post_number)
-
- scrape_item.children += 1
- if scrape_item.children_limit and scrape_item.children >= scrape_item.children_limit:
- raise MaxChildrenError(origin=scrape_item)
-
- if not continue_scraping:
- break
-
- next_page = soup.select_one(self.next_page_selector)
- if next_page and continue_scraping:
- thread_url = next_page.get(self.next_page_attribute)
- if thread_url:
- if thread_url.startswith("/"):
- thread_url = self.primary_base_domain / thread_url[1:]
- thread_url = URL(thread_url)
- continue
- else:
- break
- post_string = f"post-{current_post_number}"
- if "page-" in scrape_item.url.raw_name or "post-" in scrape_item.url.raw_name:
- last_post_url = scrape_item.url.parent / post_string
- else:
- last_post_url = scrape_item.url / post_string
- await self.manager.log_manager.write_last_post_log(last_post_url)
-
- @error_handling_wrapper
- async def post(self, scrape_item: ScrapeItem, post_content: Tag, post_number: int) -> None:
- """Scrapes a post."""
- if self.manager.config_manager.settings_data.download_options.separate_posts:
- scrape_item = self.create_scrape_item(scrape_item, scrape_item.url, "")
- scrape_item.add_to_parent_title("post-" + str(post_number))
-
- scrape_item.type = FORUM_POST
- scrape_item.children = scrape_item.children_limit = 0
-
- with contextlib.suppress(IndexError, TypeError):
- scrape_item.children_limit = (
- self.manager.config_manager.settings_data.download_options.maximum_number_of_children[scrape_item.type]
- )
-
- posts_scrapers = [self.links, self.images, self.videos, self.embeds, self.attachments]
-
- for scraper in posts_scrapers:
- scrape_item.children += await scraper(scrape_item, post_content)
- if scrape_item.children_limit and scrape_item.children >= scrape_item.children_limit:
- raise MaxChildrenError(origin=scrape_item)
- @error_handling_wrapper
- async def links(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes links from a post."""
- links = post_content.select(self.links_selector)
- new_children = 0
- for link_obj in links:
- link = link_obj.get(self.links_attribute)
- if not link:
- continue
-
- link = link.replace(".th.", ".").replace(".md.", ".")
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if "masked" in link.path:
- link = await self.handle_link_confirmation(link)
- if not link:
- continue
-
- try:
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.host:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown link type: {link}", 30)
- except TypeError:
- log(f"Scrape Failed: encountered while handling {link}", 40)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
+ async def is_confirmation_link(self, link: URL) -> bool:
+ parts = link.parts
+ if (len(parts) >= 1 and parts[1] == "masked") or "f95zone.to/masked/" in str(link):
+ return True
+ return False
@error_handling_wrapper
- async def images(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes images from a post."""
- images = post_content.select(self.images_selector)
- new_children = 0
- for image in images:
- link = image.get(self.images_attribute)
- if not link:
- continue
-
- parent_check = image.parent.get("href")
- if parent_check:
- continue
-
- link = link.replace(".th.", ".").replace(".md.", ".")
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.host:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown image type: {link}", 30)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def videos(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes videos from a post."""
- videos = post_content.select(self.videos_selector)
- videos.extend(post_content.select(self.iframe_selector))
- new_children = 0
- for video in videos:
- link = video.get(self.videos_attribute)
- if not link:
- continue
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
-
- link = URL(link)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
-
- return new_children
-
- @error_handling_wrapper
- async def embeds(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes embeds from a post."""
- embeds = post_content.select(self.embeds_selector)
- new_children = 0
- for embed in embeds:
- link = embed.get(self.embeds_attribute)
- if not link:
- continue
-
- link = link.replace("ifr", "watch")
-
- link = URL(link)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def attachments(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes attachments from a post."""
- attachment_block = post_content.select_one(self.attachments_block_selector)
- new_children = 0
- if not attachment_block:
- return new_children
-
- attachments = attachment_block.select(self.attachments_selector)
- for attachment in attachments:
- link = attachment.get(self.attachments_attribute)
- if not link:
- continue
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.host:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown image type: {link}", 30)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
-
- @error_handling_wrapper
- async def handle_internal_links(self, link: URL, scrape_item: ScrapeItem) -> None:
- """Handles internal links."""
- filename, ext = get_filename_and_ext(link.name, True)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "Attachments", True)
- await self.handle_file(link, new_scrape_item, filename, ext)
-
- @error_handling_wrapper
- async def handle_link_confirmation(self, link: URL) -> URL | None:
- """Handles link confirmation."""
+ async def handle_confirmation_link(self, link: URL, *, origin: ScrapeItem | None = None) -> URL | None:
+ """Override to handle protected link confirmation."""
async with self.request_limiter:
- await self.client.get_soup(self.domain, link)
- async with self.request_limiter:
- JSON_Resp = await self.client.post_data(self.domain, link, data={"xhr": "1", "download": "1"})
+ JSON_Resp = await self.client.post_data(
+ self.domain, link, data={"xhr": "1", "download": "1"}, origin=origin
+ )
if JSON_Resp["status"] == "ok":
return URL(JSON_Resp["msg"])
- return None
+ return
diff --git a/cyberdrop_dl/scraper/crawlers/leakedmodels_crawler.py b/cyberdrop_dl/scraper/crawlers/leakedmodels_crawler.py
index 1689a0407..0946d36b0 100644
--- a/cyberdrop_dl/scraper/crawlers/leakedmodels_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/leakedmodels_crawler.py
@@ -1,351 +1,21 @@
from __future__ import annotations
-import contextlib
from typing import TYPE_CHECKING
-from aiolimiter import AsyncLimiter
from yarl import URL
-from cyberdrop_dl.clients.errors import MaxChildrenError
-from cyberdrop_dl.scraper.crawler import Crawler
-from cyberdrop_dl.utils.data_enums_classes.url_objects import FORUM, FORUM_POST, ScrapeItem
-from cyberdrop_dl.utils.logger import log
-from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_filename_and_ext
+from .xenforo_crawler import PostSelectors, Selector, XenforoCrawler, XenforoSelectors
if TYPE_CHECKING:
- from bs4 import BeautifulSoup, Tag
-
from cyberdrop_dl.managers.manager import Manager
-class LeakedModelsCrawler(Crawler):
+class LeakedModelsCrawler(XenforoCrawler):
+ primary_base_domain = URL("https://LeakedModels.com")
+ post_selectors = PostSelectors(
+ date=Selector("time", "data-time"),
+ )
+ selectors = XenforoSelectors(posts=post_selectors)
+
def __init__(self, manager: Manager) -> None:
super().__init__(manager, "leakedmodels", "LeakedModels")
- self.primary_base_domain = URL("https://LeakedModels.com")
- self.logged_in = False
- self.login_attempts = 0
- self.request_limiter = AsyncLimiter(10, 1)
-
- self.title_selector = "h1[class=p-title-value]"
- self.title_trash_selector = "span"
- self.posts_selector = "div[class*=message-main]"
- self.post_date_selector = "time"
- self.post_date_attribute = "data-time"
- self.posts_number_selector = "li[class=u-concealed] a"
- self.posts_number_attribute = "href"
- self.quotes_selector = "blockquote"
- self.posts_content_selector = "div[class*=message-content]"
- self.next_page_selector = "a[class*=pageNav-jump--next]"
- self.next_page_attribute = "href"
- self.links_selector = "a"
- self.links_attribute = "href"
- self.attachment_url_part = "attachments"
- self.images_selector = "img[class*=bbImage]"
- self.images_attribute = "src"
- self.videos_selector = "video source"
- self.iframe_selector = "iframe[class=saint-iframe]"
- self.videos_attribute = "src"
- self.embeds_selector = "iframe"
- self.embeds_attribute = "src"
- self.attachments_block_selector = "section[class*=message-attachments]"
- self.attachments_selector = "a"
- self.attachments_attribute = "href"
-
- """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
-
- async def fetch(self, scrape_item: ScrapeItem) -> None:
- """Determines where to send the scrape item based on the url."""
- task_id = self.scraping_progress.add_task(scrape_item.url)
-
- if "threads" in scrape_item.url.parts:
- if not self.logged_in and self.login_attempts == 0:
- login_url = self.primary_base_domain / "forum" / "login"
- host_cookies = self.client.client_manager.cookies._cookies.get((self.primary_base_domain.host, ""), {})
- session_cookie = host_cookies.get("xf_user").value if "xf_user" in host_cookies else None
- if not session_cookie:
- session_cookie = self.manager.config_manager.authentication_data.forums.leakedmodels_xf_user_cookie
-
- username = self.manager.config_manager.authentication_data.forums.leakedmodels_username
- password = self.manager.config_manager.authentication_data.forums.leakedmodels_password
- wait_time = 5
-
- self.login_attempts += 1
- await self.forum_login(login_url, session_cookie, username, password, wait_time)
-
- if self.logged_in:
- await self.forum(scrape_item)
- else:
- log("LeakedModels login failed. Skipping.", 40)
- else:
- log(f"Scrape Failed: Unknown URL Path for {scrape_item.url}", 40)
- await self.manager.log_manager.write_unsupported_urls_log(
- scrape_item.url,
- scrape_item.parents[0] if scrape_item.parents else None,
- )
-
- self.scraping_progress.remove_task(task_id)
-
- @error_handling_wrapper
- async def forum(self, scrape_item: ScrapeItem) -> None:
- """Scrapes an album."""
- continue_scraping = True
-
- thread_url = scrape_item.url
- post_number = 0
- scrape_item.type = FORUM
- scrape_item.children = scrape_item.children_limit = 0
-
- with contextlib.suppress(IndexError, TypeError):
- scrape_item.children_limit = (
- self.manager.config_manager.settings_data.download_options.maximum_number_of_children[scrape_item.type]
- )
- post_sections = (scrape_item.url.parts[3], scrape_item.url.fragment)
- if len(scrape_item.url.parts) > 3 and any("post-" in sec for sec in post_sections):
- url_parts = str(scrape_item.url).rsplit("post-", 1)
- thread_url = URL(url_parts[0].rstrip("#"))
- post_number = int(url_parts[-1].strip("/")) if len(url_parts) == 2 else 0
-
- current_post_number = 0
- while True:
- async with self.request_limiter:
- soup: BeautifulSoup = await self.client.get_soup(self.domain, thread_url, origin=scrape_item)
-
- title_block = soup.select_one(self.title_selector)
- for elem in title_block.find_all(self.title_trash_selector):
- elem.decompose()
-
- thread_id = thread_url.parts[2].split(".")[-1]
- title = self.create_title(title_block.text.replace("\n", ""), None, thread_id)
-
- posts = soup.select(self.posts_selector)
- for post in posts:
- current_post_number = int(
- post.select_one(self.posts_number_selector)
- .get(self.posts_number_attribute)
- .split("/")[-1]
- .split("post-")[-1],
- )
- scrape_post, continue_scraping = await self.check_post_number(post_number, current_post_number)
-
- if scrape_post:
- date = int(post.select_one(self.post_date_selector).get(self.post_date_attribute))
- new_scrape_item = self.create_scrape_item(
- scrape_item,
- thread_url,
- title,
- False,
- None,
- date,
- add_parent=scrape_item.url.joinpath(f"post-{current_post_number}"),
- )
-
- for elem in post.find_all(self.quotes_selector):
- elem.decompose()
- post_content = post.select_one(self.posts_content_selector)
- await self.post(new_scrape_item, post_content, current_post_number)
-
- scrape_item.children += 1
- if scrape_item.children_limit and scrape_item.children >= scrape_item.children_limit:
- raise MaxChildrenError(origin=scrape_item)
-
- if not continue_scraping:
- break
-
- next_page = soup.select_one(self.next_page_selector)
- if next_page and continue_scraping:
- thread_url = next_page.get(self.next_page_attribute)
- if thread_url:
- if thread_url.startswith("/"):
- thread_url = self.primary_base_domain / thread_url[1:]
- thread_url = URL(thread_url)
- continue
- else:
- break
- post_string = f"post-{current_post_number}"
- if "page-" in scrape_item.url.raw_name or "post-" in scrape_item.url.raw_name:
- last_post_url = scrape_item.url.parent / post_string
- else:
- last_post_url = scrape_item.url / post_string
- await self.manager.log_manager.write_last_post_log(last_post_url)
-
- @error_handling_wrapper
- async def post(self, scrape_item: ScrapeItem, post_content: Tag, post_number: int) -> None:
- """Scrapes a post."""
- if self.manager.config_manager.settings_data.download_options.separate_posts:
- scrape_item = self.create_scrape_item(scrape_item, scrape_item.url, "")
- scrape_item.add_to_parent_title("post-" + str(post_number))
-
- scrape_item.type = FORUM_POST
- scrape_item.children = scrape_item.children_limit = 0
-
- with contextlib.suppress(IndexError, TypeError):
- scrape_item.children_limit = (
- self.manager.config_manager.settings_data.download_options.maximum_number_of_children[scrape_item.type]
- )
-
- posts_scrapers = [self.links, self.images, self.videos, self.embeds, self.attachments]
-
- for scraper in posts_scrapers:
- scrape_item.children += await scraper(scrape_item, post_content)
- if scrape_item.children_limit and scrape_item.children >= scrape_item.children_limit:
- raise MaxChildrenError(origin=scrape_item)
-
- @error_handling_wrapper
- async def links(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes links from a post."""
- links = post_content.select(self.links_selector)
- new_children = 0
- for link_obj in links:
- test_for_img = link_obj.select_one("img")
- if test_for_img is not None:
- continue
-
- link = link_obj.get(self.links_attribute)
- if not link:
- continue
-
- link = link.replace(".th.", ".").replace(".md.", ".")
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- try:
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown link type: {link}", 30)
- except TypeError:
- log(f"Scrape Failed: encountered while handling {link}", 40)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def images(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes images from a post."""
- images = post_content.select(self.images_selector)
- new_children = 0
- for image in images:
- link = image.get(self.images_attribute)
- if not link:
- continue
-
- link = link.replace(".th.", ".").replace(".md.", ".")
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown image type: {link}", 30)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def videos(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes videos from a post."""
- videos = post_content.select(self.videos_selector)
- videos.extend(post_content.select(self.iframe_selector))
- new_children = 0
- for video in videos:
- link = video.get(self.videos_attribute)
- if not link:
- continue
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
-
- link = URL(link)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def embeds(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes embeds from a post."""
- embeds = post_content.select(self.embeds_selector)
- new_children = 0
- for embed in embeds:
- link = embed.get(self.embeds_attribute)
- if not link:
- continue
-
- link = link.replace("ifr", "watch")
-
- link = URL(link)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def attachments(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes attachments from a post."""
- attachment_block = post_content.select_one(self.attachments_block_selector)
- new_children = 0
- if not attachment_block:
- return new_children
- attachments = attachment_block.select(self.attachments_selector)
- for attachment in attachments:
- link = attachment.get(self.attachments_attribute)
- if not link:
- continue
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown image type: {link}", 30)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
-
- @error_handling_wrapper
- async def handle_internal_links(self, link: URL, scrape_item: ScrapeItem) -> None:
- """Handles internal links."""
- filename, ext = get_filename_and_ext(link.name, True)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "Attachments", True)
- await self.handle_file(link, new_scrape_item, filename, ext)
diff --git a/cyberdrop_dl/scraper/crawlers/nudostar_crawler.py b/cyberdrop_dl/scraper/crawlers/nudostar_crawler.py
index 449ed64d2..be33d9f9c 100644
--- a/cyberdrop_dl/scraper/crawlers/nudostar_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/nudostar_crawler.py
@@ -1,355 +1,22 @@
from __future__ import annotations
-import contextlib
-import re
from typing import TYPE_CHECKING
-from aiolimiter import AsyncLimiter
from yarl import URL
-from cyberdrop_dl.clients.errors import MaxChildrenError
-from cyberdrop_dl.scraper.crawler import Crawler
-from cyberdrop_dl.utils.data_enums_classes.url_objects import FORUM, FORUM_POST, ScrapeItem
-from cyberdrop_dl.utils.logger import log
-from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_filename_and_ext
+from .xenforo_crawler import PostSelectors, Selector, XenforoCrawler, XenforoSelectors
if TYPE_CHECKING:
- from bs4 import BeautifulSoup, Tag
-
from cyberdrop_dl.managers.manager import Manager
-class NudoStarCrawler(Crawler):
+class NudoStarCrawler(XenforoCrawler):
+ primary_base_domain = URL("https://nudostar.com")
+ post_selectors = PostSelectors(
+ date=Selector("time", "data-time"),
+ number=Selector("a[class=u-concealed]", "href"),
+ )
+ selectors = XenforoSelectors(posts=post_selectors)
+
def __init__(self, manager: Manager) -> None:
super().__init__(manager, "nudostar", "NudoStar")
- self.primary_base_domain = URL("https://nudostar.com")
- self.logged_in = False
- self.login_attempts = 0
- self.request_limiter = AsyncLimiter(10, 1)
-
- self.title_selector = "h1[class=p-title-value]"
- self.title_trash_selector = "span"
- self.posts_selector = "div[class*=message-main]"
- self.post_date_selector = "time"
- self.post_date_attribute = "data-time"
- self.posts_number_selector = "a[class=u-concealed]"
- self.posts_number_attribute = "href"
- self.quotes_selector = "blockquote"
- self.posts_content_selector = "div[class*=message-userContent]"
- self.next_page_selector = "a[class*=pageNav-jump--next]"
- self.next_page_attribute = "href"
- self.links_selector = "a"
- self.links_attribute = "href"
- self.attachment_url_part = "attachments"
- self.images_selector = "img[class*=bbImage]"
- self.images_attribute = "src"
- self.videos_selector = "video source"
- self.iframe_selector = "iframe[class=saint-iframe]"
- self.videos_attribute = "src"
- self.embeds_selector = "span[data-s9e-mediaembed-iframe]"
- self.embeds_attribute = "data-s9e-mediaembed-iframe"
- self.attachments_block_selector = "section[class=message-attachments]"
- self.attachments_selector = "a"
- self.attachments_attribute = "href"
-
- """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
-
- async def fetch(self, scrape_item: ScrapeItem) -> None:
- """Determines where to send the scrape item based on the url."""
- task_id = self.scraping_progress.add_task(scrape_item.url)
-
- if not self.logged_in and self.login_attempts == 0:
- login_url = self.primary_base_domain / "forum/login"
- host_cookies = self.client.client_manager.cookies._cookies.get((self.primary_base_domain.host, ""), {})
- session_cookie = host_cookies.get("xf_user").value if "xf_user" in host_cookies else None
- if not session_cookie:
- session_cookie = self.manager.config_manager.authentication_data.forums.nudostar_xf_user_cookie
-
- username = self.manager.config_manager.authentication_data.forums.nudostar_username
- password = self.manager.config_manager.authentication_data.forums.nudostar_password
- wait_time = 5
-
- self.login_attempts += 1
- await self.forum_login(login_url, session_cookie, username, password, wait_time)
-
- if self.logged_in:
- await self.forum(scrape_item)
- else:
- log("Nudostar login failed. Skipping.", 40)
-
- self.scraping_progress.remove_task(task_id)
-
- @error_handling_wrapper
- async def forum(self, scrape_item: ScrapeItem) -> None:
- """Scrapes an album."""
- continue_scraping = True
-
- thread_url = scrape_item.url
- post_number = 0
- scrape_item.type = FORUM
- scrape_item.children = scrape_item.children_limit = 0
-
- with contextlib.suppress(IndexError, TypeError):
- scrape_item.children_limit = (
- self.manager.config_manager.settings_data.download_options.maximum_number_of_children[scrape_item.type]
- )
- post_sections = (scrape_item.url.parts[3], scrape_item.url.fragment)
- if len(scrape_item.url.parts) > 3 and any("post-" in sec for sec in post_sections):
- url_parts = str(scrape_item.url).rsplit("post-", 1)
- thread_url = URL(url_parts[0].rstrip("#"))
- post_number = int(url_parts[-1].strip("/")) if len(url_parts) == 2 else 0
-
- current_post_number = 0
- while True:
- async with self.request_limiter:
- soup: BeautifulSoup = await self.client.get_soup(self.domain, thread_url, origin=scrape_item)
-
- title_block = soup.select_one(self.title_selector)
- for elem in title_block.find_all(self.title_trash_selector):
- elem.decompose()
-
- thread_id = thread_url.parts[2].split(".")[-1]
- title = self.create_title(title_block.text.replace("\n", ""), None, thread_id)
-
- posts = soup.select(self.posts_selector)
- for post in posts:
- current_post_number = int(
- post.select_one(self.posts_number_selector)
- .get(self.posts_number_attribute)
- .split("/")[-1]
- .split("post-")[-1],
- )
- scrape_post, continue_scraping = self.check_post_number(post_number, current_post_number)
-
- if scrape_post:
- date = int(post.select_one(self.post_date_selector).get(self.post_date_attribute))
- new_scrape_item = self.create_scrape_item(
- scrape_item,
- thread_url,
- title,
- False,
- None,
- date,
- add_parent=scrape_item.url.joinpath(f"post-{current_post_number}"),
- )
-
- for elem in post.find_all(self.quotes_selector):
- elem.decompose()
- post_content = post.select_one(self.posts_content_selector)
- await self.post(new_scrape_item, post_content, current_post_number)
-
- scrape_item.children += 1
- if scrape_item.children_limit and scrape_item.children >= scrape_item.children_limit:
- raise MaxChildrenError(origin=scrape_item)
-
- if not continue_scraping:
- break
-
- next_page = soup.select_one(self.next_page_selector)
- if next_page and continue_scraping:
- thread_url = next_page.get(self.next_page_attribute)
- if thread_url:
- if thread_url.startswith("/"):
- thread_url = self.primary_base_domain / thread_url[1:]
- thread_url = URL(thread_url)
- continue
- else:
- break
- post_string = f"post-{current_post_number}"
- if "page-" in scrape_item.url.raw_name or "post-" in scrape_item.url.raw_name:
- last_post_url = scrape_item.url.parent / post_string
- else:
- last_post_url = scrape_item.url / post_string
- await self.manager.log_manager.write_last_post_log(last_post_url)
-
- @error_handling_wrapper
- async def post(self, scrape_item: ScrapeItem, post_content: Tag, post_number: int) -> None:
- """Scrapes a post."""
- if self.manager.config_manager.settings_data.download_options.separate_posts:
- scrape_item = self.create_scrape_item(scrape_item, scrape_item.url, "")
- scrape_item.add_to_parent_title("post-" + str(post_number))
-
- scrape_item.type = FORUM_POST
- scrape_item.children = scrape_item.children_limit = 0
-
- with contextlib.suppress(IndexError, TypeError):
- scrape_item.children_limit = (
- self.manager.config_manager.settings_data.download_options.maximum_number_of_children[scrape_item.type]
- )
-
- posts_scrapers = [self.links, self.images, self.videos, self.embeds, self.attachments]
-
- for scraper in posts_scrapers:
- scrape_item.children += await scraper(scrape_item, post_content)
- if scrape_item.children_limit and scrape_item.children >= scrape_item.children_limit:
- raise MaxChildrenError(origin=scrape_item)
-
- @error_handling_wrapper
- async def links(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes links from a post."""
- links = post_content.select(self.links_selector)
- new_children = 0
- for link_obj in links:
- link = link_obj.get(self.links_attribute)
- if not link:
- continue
-
- test_for_img = link_obj.select_one("img")
- if test_for_img and "nudostar.com" not in link:
- continue
-
- link = link.replace(".th.", ".").replace(".md.", ".")
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- try:
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown link type: {link}", 30)
- except TypeError:
- log(f"Scrape Failed: encountered while handling {link}", 40)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def images(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes images from a post."""
- images = post_content.select(self.images_selector)
- new_children = 0
- for image in images:
- link = image.get(self.images_attribute)
- if not link:
- continue
-
- parent_nudo_check = image.parent.get("href")
- if parent_nudo_check:
- continue
-
- link = link.replace(".th.", ".").replace(".md.", ".")
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown image type: {link}", 30)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def videos(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes videos from a post."""
- videos = post_content.select(self.videos_selector)
- videos.extend(post_content.select(self.iframe_selector))
- new_children = 0
-
- for video in videos:
- link = video.get(self.videos_attribute)
- if not link:
- continue
-
- if link.startswith("//"):
- link = "https:" + link
-
- link = URL(link)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def embeds(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes embeds from a post."""
- embeds = post_content.select(self.embeds_selector)
- new_children = 0
- for embed in embeds:
- data = embed.get(self.embeds_attribute)
- if not data:
- continue
-
- data = data.replace(r"\/\/", "https://www.")
- data = data.replace("\\", "")
-
- embed = re.search(
- r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)",
- data,
- )
- if not embed:
- embed = re.search(
- r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\/[-a-zA-Z0-9@:%._\+~#=]*\/[-a-zA-Z0-9@:?&%._\+~#=]*",
- data,
- )
-
- if embed:
- link = embed.group(0).replace("www.", "")
- if link.endswith("/"):
- link = link[:-1]
- link = URL(link)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def attachments(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes attachments from a post."""
- attachment_block = post_content.select_one(self.attachments_block_selector)
- new_children = 0
- if not attachment_block:
- return new_children
- attachments = attachment_block.select(self.attachments_selector)
- for attachment in attachments:
- link = attachment.get(self.attachments_attribute)
- if not link:
- continue
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown image type: {link}", 30)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
-
- @error_handling_wrapper
- async def handle_internal_links(self, link: URL, scrape_item: ScrapeItem) -> None:
- """Handles internal links."""
- temp_link = URL(str(link)[:-1]) if str(link).endswith("/") else link
- filename, ext = get_filename_and_ext(temp_link.name, True)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "Attachments", True)
- await self.handle_file(link, new_scrape_item, filename, ext)
diff --git a/cyberdrop_dl/scraper/crawlers/simpcity_crawler.py b/cyberdrop_dl/scraper/crawlers/simpcity_crawler.py
index 532e6f252..5ce7aed44 100644
--- a/cyberdrop_dl/scraper/crawlers/simpcity_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/simpcity_crawler.py
@@ -1,369 +1,18 @@
from __future__ import annotations
-import contextlib
-import re
from typing import TYPE_CHECKING
-from aiolimiter import AsyncLimiter
from yarl import URL
-from cyberdrop_dl.clients.errors import MaxChildrenError
-from cyberdrop_dl.scraper.crawler import Crawler
-from cyberdrop_dl.utils.data_enums_classes.url_objects import FORUM, FORUM_POST, ScrapeItem
-from cyberdrop_dl.utils.logger import log
-from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_filename_and_ext
+from .xenforo_crawler import XenforoCrawler
if TYPE_CHECKING:
- from bs4 import BeautifulSoup, Tag
-
from cyberdrop_dl.managers.manager import Manager
-class SimpCityCrawler(Crawler):
+class SimpCityCrawler(XenforoCrawler):
+ primary_base_domain = URL("https://simpcity.su")
+ login_required = False
+
def __init__(self, manager: Manager) -> None:
super().__init__(manager, "simpcity", "SimpCity")
- self.primary_base_domain = URL("https://simpcity.su")
- self.logged_in = False
- self.login_attempts = 0
- self.request_limiter = AsyncLimiter(10, 1)
-
- self.title_selector = "h1[class=p-title-value]"
- self.title_trash_selector = "span"
- self.posts_selector = "div[class*=message-main]"
- self.post_date_selector = "time"
- self.post_date_attribute = "data-timestamp"
- self.posts_number_selector = "li[class=u-concealed] a"
- self.posts_number_attribute = "href"
- self.quotes_selector = "blockquote"
- self.posts_content_selector = "div[class*=message-userContent]"
- self.next_page_selector = "a[class*=pageNav-jump--next]"
- self.next_page_attribute = "href"
- self.links_selector = "a"
- self.links_attribute = "href"
- self.attachment_url_part = "attachments"
- self.images_selector = "img[class*=bbImage]"
- self.images_attribute = "src"
- self.videos_selector = "video source"
- self.iframe_selector = "iframe[class=saint-iframe]"
- self.videos_attribute = "src"
- self.embeds_selector = "span[data-s9e-mediaembed-iframe]"
- self.embeds_attribute = "data-s9e-mediaembed-iframe"
- self.attachments_block_selector = "section[class=message-attachments]"
- self.attachments_selector = "a"
- self.attachments_attribute = "href"
-
- """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
-
- async def fetch(self, scrape_item: ScrapeItem) -> None:
- """Determines where to send the scrape item based on the url."""
- task_id = self.scraping_progress.add_task(scrape_item.url)
-
- if not self.logged_in and self.login_attempts == 0:
- login_url = self.primary_base_domain / "login"
- host_cookies = self.client.client_manager.cookies._cookies.get((self.primary_base_domain.host, ""), {})
- session_cookie = host_cookies.get("xf_user").value if "xf_user" in host_cookies else None
- if not session_cookie:
- session_cookie = self.manager.config_manager.authentication_data.forums.simpcity_xf_user_cookie
-
- session_cookie = self.manager.config_manager.authentication_data.forums.simpcity_xf_user_cookie
- username = self.manager.config_manager.authentication_data.forums.simpcity_username
- password = self.manager.config_manager.authentication_data.forums.simpcity_password
- wait_time = 5
-
- if session_cookie or (username and password):
- self.login_attempts += 1
- await self.forum_login(login_url, session_cookie, username, password, wait_time)
-
- if not self.logged_in and self.login_attempts == 1:
- log("SimpCity login failed. Scraping without an account.", 40)
-
- await self.forum(scrape_item)
-
- self.scraping_progress.remove_task(task_id)
-
- @error_handling_wrapper
- async def forum(self, scrape_item: ScrapeItem) -> None:
- """Scrapes an album."""
- continue_scraping = True
-
- thread_url = scrape_item.url
- post_number = 0
- scrape_item.type = FORUM
- scrape_item.children = scrape_item.children_limit = 0
-
- with contextlib.suppress(IndexError, TypeError):
- scrape_item.children_limit = (
- self.manager.config_manager.settings_data.download_options.maximum_number_of_children[scrape_item.type]
- )
- post_sections = (scrape_item.url.parts[3], scrape_item.url.fragment)
- if len(scrape_item.url.parts) > 3 and any("post-" in sec for sec in post_sections):
- url_parts = str(scrape_item.url).rsplit("post-", 1)
- thread_url = URL(url_parts[0].rstrip("#"))
- post_number = int(url_parts[-1].strip("/")) if len(url_parts) == 2 else 0
-
- current_post_number = 0
- while True:
- thread_url = scrape_item.url if current_post_number == 0 else thread_url
- async with self.request_limiter:
- soup: BeautifulSoup = await self.client.get_soup(self.domain, thread_url, origin=scrape_item)
-
- title_block = soup.select_one(self.title_selector)
- for elem in title_block.find_all(self.title_trash_selector):
- elem.decompose()
-
- thread_id = thread_url.parts[2].split(".")[-1]
- title = self.create_title(title_block.text.replace("\n", ""), None, thread_id)
-
- posts = soup.select(self.posts_selector)
- for post in posts:
- current_post_number = int(
- post.select_one(self.posts_number_selector)
- .get(self.posts_number_attribute)
- .split("/")[-1]
- .split("post-")[-1],
- )
- scrape_post, continue_scraping = self.check_post_number(post_number, current_post_number)
-
- if scrape_post:
- date = None
- with contextlib.suppress(AttributeError):
- date = int(post.select_one(self.post_date_selector).get(self.post_date_attribute))
- new_scrape_item = self.create_scrape_item(
- scrape_item,
- thread_url,
- title,
- False,
- None,
- date,
- add_parent=scrape_item.url.joinpath(f"post-{current_post_number}"),
- )
-
- # for elem in post.find_all(self.quotes_selector):
- # elem.decompose()
- post_content = post.select_one(self.posts_content_selector)
- await self.post(new_scrape_item, post_content, current_post_number)
-
- scrape_item.children += 1
- if scrape_item.children_limit and scrape_item.children >= scrape_item.children_limit:
- raise MaxChildrenError(origin=scrape_item)
-
- if not continue_scraping:
- break
-
- next_page = soup.select_one(self.next_page_selector)
- if next_page and continue_scraping:
- thread_url = next_page.get(self.next_page_attribute)
- if thread_url:
- if thread_url.startswith("/"):
- thread_url = self.primary_base_domain / thread_url[1:]
- thread_url = URL(thread_url)
- continue
- else:
- break
- post_string = f"post-{current_post_number}"
- if "page-" in scrape_item.url.raw_name or "post-" in scrape_item.url.raw_name:
- last_post_url = scrape_item.url.parent / post_string
- else:
- last_post_url = scrape_item.url / post_string
- await self.manager.log_manager.write_last_post_log(last_post_url)
-
- @error_handling_wrapper
- async def post(self, scrape_item: ScrapeItem, post_content: Tag, post_number: int) -> None:
- """Scrapes a post."""
- if self.manager.config_manager.settings_data.download_options.separate_posts:
- scrape_item = self.create_scrape_item(scrape_item, scrape_item.url, "")
- scrape_item.add_to_parent_title("post-" + str(post_number))
-
- scrape_item.type = FORUM_POST
- scrape_item.children = scrape_item.children_limit = 0
-
- with contextlib.suppress(IndexError, TypeError):
- scrape_item.children_limit = (
- self.manager.config_manager.settings_data.download_options.maximum_number_of_children[scrape_item.type]
- )
-
- posts_scrapers = [self.links, self.images, self.videos, self.embeds, self.attachments]
-
- for scraper in posts_scrapers:
- scrape_item.children += await scraper(scrape_item, post_content)
- if scrape_item.children_limit and scrape_item.children >= scrape_item.children_limit:
- raise MaxChildrenError(origin=scrape_item)
-
- @error_handling_wrapper
- async def links(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes links from a post."""
- links = post_content.select(self.links_selector)
- new_children = 0
- for link_obj in links:
- test_for_img = link_obj.select_one("img")
- if test_for_img is not None and self.attachment_url_part not in link_obj.get(self.links_attribute):
- continue
-
- link = link_obj.get(self.links_attribute)
- if not link:
- continue
-
- link = link.replace(".th.", ".").replace(".md.", ".")
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- try:
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown link type: {link}", 30)
- except TypeError:
- log(f"Scrape Failed: encountered while handling {link}", 40)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def images(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes images from a post."""
- images = post_content.select(self.images_selector)
- new_children = 0
- for image in images:
- link = image.get(self.images_attribute)
- if not link:
- continue
-
- parent_simp_check = image.parent.get("data-simp")
- if parent_simp_check and "init" in parent_simp_check:
- continue
-
- link = link.replace(".th.", ".").replace(".md.", ".")
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts:
- continue
- else:
- log(f"Unknown image type: {link}", 30)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def videos(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes videos from a post."""
- videos = post_content.select(self.videos_selector)
- videos.extend(post_content.select(self.iframe_selector))
- new_children = 0
- for video in videos:
- link = video.get(self.videos_attribute)
- if not link:
- continue
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
-
- link = URL(link)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def embeds(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes embeds from a post."""
- embeds = post_content.select(self.embeds_selector)
- new_children = 0
- for embed in embeds:
- data = embed.get(self.embeds_attribute)
- if not data:
- continue
-
- data = data.replace(r"\/\/", "https://www.")
- data = data.replace("\\", "")
-
- embed = re.search(
- r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)",
- data,
- )
- if not embed:
- embed = re.search(
- r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\/[-a-zA-Z0-9@:%._\+~#=]*\/[-a-zA-Z0-9@:?&%._\+~#=]*",
- data,
- )
-
- if embed:
- link = embed.group(0).replace("www.", "")
- if link.endswith("/"):
- link = link[:-1]
- link = URL(link)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def attachments(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes attachments from a post."""
- attachment_block = post_content.select_one(self.attachments_block_selector)
- new_children = 0
- if not attachment_block:
- return new_children
- attachments = attachment_block.select(self.attachments_selector)
- for attachment in attachments:
- link = attachment.get(self.attachments_attribute)
- if not link:
- continue
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown image type: {link}", 30)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
-
- @error_handling_wrapper
- async def handle_internal_links(self, link: URL, scrape_item: ScrapeItem) -> None:
- """Handles internal links."""
- filename, ext = get_filename_and_ext(link.name, True)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "Attachments", True)
- await self.handle_file(link, new_scrape_item, filename, ext)
diff --git a/cyberdrop_dl/scraper/crawlers/socialmediagirls_crawler.py b/cyberdrop_dl/scraper/crawlers/socialmediagirls_crawler.py
index 61ca8d3b7..10a1be8bf 100644
--- a/cyberdrop_dl/scraper/crawlers/socialmediagirls_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/socialmediagirls_crawler.py
@@ -1,379 +1,23 @@
from __future__ import annotations
-import contextlib
-import re
from typing import TYPE_CHECKING
-from aiolimiter import AsyncLimiter
from yarl import URL
-from cyberdrop_dl.clients.errors import MaxChildrenError
-from cyberdrop_dl.scraper.crawler import Crawler
-from cyberdrop_dl.utils.data_enums_classes.url_objects import FORUM, FORUM_POST, ScrapeItem
-from cyberdrop_dl.utils.logger import log
-from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_filename_and_ext
+from .xenforo_crawler import PostSelectors, Selector, XenforoCrawler, XenforoSelectors
if TYPE_CHECKING:
- from bs4 import BeautifulSoup, Tag
-
from cyberdrop_dl.managers.manager import Manager
-class SocialMediaGirlsCrawler(Crawler):
+class SocialMediaGirlsCrawler(XenforoCrawler):
+ primary_base_domain = URL("https://forums.socialmediagirls.com")
+ post_selectors = PostSelectors(
+ content=Selector("div[class=bbWrapper]", None),
+ images=Selector("img[class*=bbImage]", "data-src"),
+ date=Selector("time", "data-time"),
+ )
+ selectors = XenforoSelectors(posts=post_selectors)
+
def __init__(self, manager: Manager) -> None:
super().__init__(manager, "socialmediagirls", "SocialMediaGirls")
- self.primary_base_domain = URL("https://forums.socialmediagirls.com")
- self.logged_in = False
- self.login_attempts = 0
- self.request_limiter = AsyncLimiter(10, 1)
-
- self.title_selector = "h1[class=p-title-value]"
- self.title_trash_selector = "span"
- self.posts_selector = "div[class*=message-main]"
- self.post_date_selector = "time"
- self.post_date_attribute = "data-time"
- self.posts_number_selector = "li[class=u-concealed] a"
- self.posts_number_attribute = "href"
- self.quotes_selector = "blockquote"
- self.posts_content_selector = "div[class=bbWrapper]"
- self.next_page_selector = "a[class*=pageNav-jump--next]"
- self.next_page_attribute = "href"
- self.links_selector = "a"
- self.links_attribute = "href"
- self.attachment_url_part = "attachments"
- self.images_selector = "img[class*=bbImage]"
- self.images_attribute = "data-src"
- self.videos_selector = "video source"
- self.iframe_selector = "iframe[class=saint-iframe]"
- self.videos_attribute = "src"
- self.embeds_selector = "span[data-s9e-mediaembed-iframe]"
- self.embeds_attribute = "data-s9e-mediaembed-iframe"
- self.attachments_block_selector = "section[class=message-attachments]"
- self.attachments_selector = "a"
- self.attachments_attribute = "href"
-
- """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
-
- async def fetch(self, scrape_item: ScrapeItem) -> None:
- """Determines where to send the scrape item based on the url."""
- task_id = self.scraping_progress.add_task(scrape_item.url)
-
- if not self.logged_in and self.login_attempts == 0:
- login_url = self.primary_base_domain / "login"
- host_cookies = self.client.client_manager.cookies._cookies.get((self.primary_base_domain.host, ""), {})
- session_cookie = host_cookies.get("xf_user").value if "xf_user" in host_cookies else None
- if not session_cookie:
- session_cookie = self.manager.config_manager.authentication_data.forums.socialmediagirls_xf_user_cookie
-
- username = self.manager.config_manager.authentication_data.forums.socialmediagirls_username
- password = self.manager.config_manager.authentication_data.forums.socialmediagirls_password
- wait_time = 10
-
- self.login_attempts += 1
- await self.forum_login(login_url, session_cookie, username, password, wait_time)
-
- if self.logged_in:
- await self.forum(scrape_item)
- else:
- log("SocialMediaGirls login failed. Skipping.", 40)
-
- self.scraping_progress.remove_task(task_id)
-
- @error_handling_wrapper
- async def forum(self, scrape_item: ScrapeItem) -> None:
- """Scrapes an album."""
- continue_scraping = True
-
- thread_url = scrape_item.url
- post_number = 0
- scrape_item.type = FORUM
- scrape_item.children = scrape_item.children_limit = 0
-
- with contextlib.suppress(IndexError, TypeError):
- scrape_item.children_limit = (
- self.manager.config_manager.settings_data.download_options.maximum_number_of_children[scrape_item.type]
- )
- thread_index = scrape_item.url.parts.index("threads")
- post_sections = (scrape_item.url.parts[thread_index + 1], scrape_item.url.fragment)
- if len(scrape_item.url.parts) > 3 and any("post-" in sec for sec in post_sections):
- url_parts = str(scrape_item.url).rsplit("post-", 1)
- thread_url = URL(url_parts[0].rstrip("#"))
- post_number = int(url_parts[-1].strip("/")) if len(url_parts) == 2 else 0
-
- current_post_number = 0
- while True:
- async with self.request_limiter:
- soup: BeautifulSoup = await self.client.get_soup(self.domain, thread_url, origin=scrape_item)
-
- title_block = soup.select_one(self.title_selector)
- for elem in title_block.find_all(self.title_trash_selector):
- elem.decompose()
-
- thread_id = thread_url.parts[2].split(".")[-1]
- title = self.create_title(title_block.text.replace("\n", ""), None, thread_id)
-
- posts = soup.select(self.posts_selector)
- for post in posts:
- current_post_number = int(
- post.select_one(self.posts_number_selector)
- .get(self.posts_number_attribute)
- .split("/")[-1]
- .split("post-")[-1],
- )
- scrape_post, continue_scraping = self.check_post_number(post_number, current_post_number)
-
- if scrape_post:
- date = int(post.select_one(self.post_date_selector).get(self.post_date_attribute))
- new_scrape_item = self.create_scrape_item(
- scrape_item,
- thread_url,
- title,
- False,
- None,
- date,
- add_parent=scrape_item.url.joinpath(f"post-{current_post_number}"),
- )
-
- for elem in post.find_all(self.quotes_selector):
- elem.decompose()
- post_content = post.select_one(self.posts_content_selector)
- await self.post(new_scrape_item, post_content, current_post_number)
- scrape_item.children += 1
- if scrape_item.children_limit and scrape_item.children >= scrape_item.children_limit:
- raise MaxChildrenError(origin=scrape_item)
-
- if not continue_scraping:
- break
-
- next_page = soup.select_one(self.next_page_selector)
- if next_page and continue_scraping:
- thread_url = next_page.get(self.next_page_attribute)
- if thread_url:
- if thread_url.startswith("/"):
- thread_url = self.primary_base_domain / thread_url[1:]
- thread_url = URL(thread_url)
- continue
- else:
- break
- post_string = f"post-{current_post_number}"
- if "page-" in scrape_item.url.raw_name or "post-" in scrape_item.url.raw_name:
- last_post_url = scrape_item.url.parent / post_string
- else:
- last_post_url = scrape_item.url / post_string
- await self.manager.log_manager.write_last_post_log(last_post_url)
-
- @error_handling_wrapper
- async def post(self, scrape_item: ScrapeItem, post_content: Tag, post_number: int) -> None:
- """Scrapes a post."""
- if self.manager.config_manager.settings_data.download_options.separate_posts:
- scrape_item = self.create_scrape_item(scrape_item, scrape_item.url, "")
- scrape_item.add_to_parent_title("post-" + str(post_number))
-
- scrape_item.type = FORUM_POST
- scrape_item.children = scrape_item.children_limit = 0
-
- with contextlib.suppress(IndexError, TypeError):
- scrape_item.children_limit = (
- self.manager.config_manager.settings_data.download_options.maximum_number_of_children[scrape_item.type]
- )
-
- posts_scrapers = [self.links, self.images, self.videos, self.embeds, self.attachments]
-
- for scraper in posts_scrapers:
- scrape_item.children += await scraper(scrape_item, post_content)
- if scrape_item.children_limit and scrape_item.children >= scrape_item.children_limit:
- raise MaxChildrenError(origin=scrape_item)
-
- @error_handling_wrapper
- async def links(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes links from a post."""
- links = post_content.select(self.links_selector)
- new_children = 0
- for link_obj in links:
- test_for_img = link_obj.select_one("img")
- if test_for_img is not None:
- continue
-
- link = link_obj.get(self.links_attribute)
- if not link:
- continue
-
- link = link.replace(".th.", ".").replace(".md.", ".")
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = str(self.primary_base_domain) + link
- link = URL(link, encoded=True)
- if "link-confirmation" in link.path:
- link = await self.handle_link_confirmation(link)
- if link is None:
- return new_children
- try:
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts or "smgmedia" in link.host:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown link type: {link}", 30)
- continue
- except TypeError:
- log(f"Scrape Failed: encountered while handling {link}", 40)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def images(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes images from a post."""
- images = post_content.select(self.images_selector)
- new_children = 0
- for image in images:
- link = image.get(self.images_attribute)
- if link is None:
- continue
-
- parent_simp_check = image.parent.get("data-simp")
- if parent_simp_check and "init" in parent_simp_check:
- continue
-
- link = link.replace(".th.", ".").replace(".md.", ".")
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts or "smgmedia" in link.host:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown image type: {link}", 30)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def videos(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes videos from a post."""
- videos = post_content.select(self.videos_selector)
- videos.extend(post_content.select(self.iframe_selector))
- new_children = 0
-
- for video in videos:
- link = video.get(self.videos_attribute)
- if not link:
- continue
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
-
- link = URL(link)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def embeds(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes embeds from a post."""
- embeds = post_content.select(self.embeds_selector)
- new_children = 0
- for embed in embeds:
- data = embed.get(self.embeds_attribute)
- if not data:
- continue
-
- data = data.replace(r"\/\/", "https://www.")
- data = data.replace("\\", "")
-
- embed = re.search(
- r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)",
- data,
- )
- if not embed:
- embed = re.search(
- r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\/[-a-zA-Z0-9@:%._\+~#=]*\/[-a-zA-Z0-9@:?&%._\+~#=]*",
- data,
- )
-
- if embed:
- link = embed.group(0).replace("www.", "")
- if link.endswith("/"):
- link = link[:-1]
- link = URL(link)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def attachments(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes attachments from a post."""
- attachment_block = post_content.select_one(self.attachments_block_selector)
- new_children = 0
- if not attachment_block:
- return new_children
- attachments = attachment_block.select(self.attachments_selector)
- for attachment in attachments:
- link = attachment.get(self.attachments_attribute)
- if not link:
- continue
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts or "smgmedia" in link.host:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown image type: {link}", 30)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
-
- @error_handling_wrapper
- async def handle_internal_links(self, link: URL, scrape_item: ScrapeItem) -> None:
- """Handles internal links."""
- filename, ext = get_filename_and_ext(link.name, True)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "Attachments", True)
- await self.handle_file(link, new_scrape_item, filename, ext)
-
- @error_handling_wrapper
- async def handle_link_confirmation(self, link: URL) -> URL | None:
- """Handles link confirmation."""
- async with self.request_limiter:
- soup: BeautifulSoup = await self.client.get_soup(self.domain, link)
- confirm_button = soup.select_one("a[class*=button--cta]")
- if confirm_button:
- return URL(confirm_button.get("href"))
- return None
diff --git a/cyberdrop_dl/scraper/crawlers/xbunker_crawler.py b/cyberdrop_dl/scraper/crawlers/xbunker_crawler.py
index 35225e413..576728c15 100644
--- a/cyberdrop_dl/scraper/crawlers/xbunker_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/xbunker_crawler.py
@@ -1,368 +1,24 @@
from __future__ import annotations
-import contextlib
-import re
from typing import TYPE_CHECKING
-from aiolimiter import AsyncLimiter
from yarl import URL
-from cyberdrop_dl.clients.errors import MaxChildrenError
-from cyberdrop_dl.scraper.crawler import Crawler
-from cyberdrop_dl.utils.data_enums_classes.url_objects import FORUM, FORUM_POST, ScrapeItem
-from cyberdrop_dl.utils.logger import log
-from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_filename_and_ext
+from .xenforo_crawler import PostSelectors, Selector, XenforoCrawler, XenforoSelectors
if TYPE_CHECKING:
- from bs4 import BeautifulSoup, Tag
-
from cyberdrop_dl.managers.manager import Manager
-class XBunkerCrawler(Crawler):
+class XBunkerCrawler(XenforoCrawler):
+ primary_base_domain = URL("https://xbunker.nu/")
+ post_selectors = PostSelectors(
+ content=Selector("div[class=bbWrapper]", None),
+ images=Selector("img[class*=bbImage], a[class*=js-lbImage]", "data-src"),
+ date=Selector("time", "data-time"),
+ )
+ selectors = XenforoSelectors(posts=post_selectors)
+
def __init__(self, manager: Manager) -> None:
super().__init__(manager, "xbunker", "XBunker")
- self.primary_base_domain = URL("https://xbunker.nu/")
- self.logged_in = False
- self.login_attempts = 0
- self.request_limiter = AsyncLimiter(10, 1)
-
- self.title_selector = "h1[class=p-title-value]"
- self.title_trash_selector = "a"
- self.posts_selector = "div[class*=message-main]"
- self.post_date_selector = "time"
- self.post_date_attribute = "data-time"
- self.posts_number_selector = "li[class=u-concealed] a"
- self.posts_number_attribute = "href"
- self.quotes_selector = "blockquote"
- self.posts_content_selector = "div[class=bbWrapper]"
- self.next_page_selector = "a[class*=pageNav-jump--next]"
- self.next_page_attribute = "href"
- self.links_selector = "a"
- self.links_attribute = "href"
- self.attachment_url_part = "data"
- self.extra_attachment_url_part = "attachments"
- self.images_selector = "img[class*=bbImage]"
- self.images_attribute = "data-src"
- self.videos_selector = "video source"
- self.iframe_selector = "iframe[class=saint-iframe]"
- self.videos_attribute = "src"
- self.embeds_selector = "span[data-s9e-mediaembed-iframe]"
- self.embeds_attribute = "data-s9e-mediaembed-iframe"
- self.attachments_block_selector = "section[class=message-attachments]"
- self.attachments_selector = "a"
- self.attachments_attribute = "href"
-
- self.extra_image_selector = "a[class*=js-lbImage]"
- self.extra_image_attribute = "href"
-
- """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
-
- async def fetch(self, scrape_item: ScrapeItem) -> None:
- """Determines where to send the scrape item based on the url."""
- task_id = self.scraping_progress.add_task(scrape_item.url)
-
- if not self.logged_in and self.login_attempts == 0:
- login_url = self.primary_base_domain / "login"
- host_cookies = self.client.client_manager.cookies._cookies.get((self.primary_base_domain.host, ""), {})
- session_cookie = host_cookies.get("xf_user").value if "xf_user" in host_cookies else None
- if not session_cookie:
- session_cookie = self.manager.config_manager.authentication_data.forums.xbunker_xf_user_cookie
-
- username = self.manager.config_manager.authentication_data.forums.xbunker_username
- password = self.manager.config_manager.authentication_data.forums.xbunker_password
- wait_time = 5
-
- self.login_attempts += 1
- await self.forum_login(login_url, session_cookie, username, password, wait_time)
-
- if self.logged_in:
- await self.forum(scrape_item)
- else:
- log("XBunker login failed. Skipping.", 40)
-
- self.scraping_progress.remove_task(task_id)
-
- @error_handling_wrapper
- async def forum(self, scrape_item: ScrapeItem) -> None:
- """Scrapes an album."""
- continue_scraping = True
-
- thread_url = scrape_item.url
- post_number = 0
- scrape_item.type = FORUM
- scrape_item.children = scrape_item.children_limit = 0
-
- with contextlib.suppress(IndexError, TypeError):
- scrape_item.children_limit = (
- self.manager.config_manager.settings_data.download_options.maximum_number_of_children[scrape_item.type]
- )
- post_sections = (scrape_item.url.parts[3], scrape_item.url.fragment)
- if len(scrape_item.url.parts) > 3 and any("post-" in sec for sec in post_sections):
- url_parts = str(scrape_item.url).rsplit("post-", 1)
- thread_url = URL(url_parts[0].rstrip("#"))
- post_number = int(url_parts[-1].strip("/")) if len(url_parts) == 2 else 0
-
- current_post_number = 0
- while True:
- async with self.request_limiter:
- soup: BeautifulSoup = await self.client.get_soup(self.domain, thread_url, origin=scrape_item)
-
- title_block = soup.select_one(self.title_selector)
- for elem in title_block.find_all(self.title_trash_selector):
- elem.decompose()
-
- thread_id = thread_url.parts[2].split(".")[-1]
- title = self.create_title(title_block.text.replace("\n", ""), None, thread_id)
-
- posts = soup.select(self.posts_selector)
- for post in posts:
- current_post_number = int(
- post.select_one(self.posts_number_selector)
- .get(self.posts_number_attribute)
- .split("/")[-1]
- .split("post-")[-1],
- )
- scrape_post, continue_scraping = self.check_post_number(post_number, current_post_number)
-
- if scrape_post:
- date = int(post.select_one(self.post_date_selector).get(self.post_date_attribute))
- new_scrape_item = self.create_scrape_item(
- scrape_item,
- thread_url,
- title,
- False,
- None,
- date,
- add_parent=scrape_item.url.joinpath(f"post-{current_post_number}"),
- )
-
- for elem in post.find_all(self.quotes_selector):
- elem.decompose()
- post_content = post.select_one(self.posts_content_selector)
- await self.post(new_scrape_item, post_content, current_post_number)
-
- scrape_item.children += 1
- if scrape_item.children_limit and scrape_item.children >= scrape_item.children_limit:
- raise MaxChildrenError(origin=scrape_item)
-
- if not continue_scraping:
- break
-
- next_page = soup.select_one(self.next_page_selector)
- if next_page and continue_scraping:
- thread_url = next_page.get(self.next_page_attribute)
- if thread_url:
- if thread_url.startswith("/"):
- thread_url = self.primary_base_domain / str, thread_url[1:]
- thread_url = URL(thread_url)
- continue
- else:
- break
- post_string = f"post-{current_post_number}"
- if "page-" in scrape_item.url.raw_name or "post-" in scrape_item.url.raw_name:
- last_post_url = scrape_item.url.parent / post_string
- else:
- last_post_url = scrape_item.url / post_string
- await self.manager.log_manager.write_last_post_log(last_post_url)
-
- @error_handling_wrapper
- async def post(self, scrape_item: ScrapeItem, post_content: Tag, post_number: int) -> None:
- """Scrapes a post."""
- if self.manager.config_manager.settings_data.download_options.separate_posts:
- scrape_item = self.create_scrape_item(scrape_item, scrape_item.url, "")
- scrape_item.add_to_parent_title("post-" + str(post_number))
-
- scrape_item.type = FORUM_POST
- scrape_item.children = scrape_item.children_limit = 0
-
- with contextlib.suppress(IndexError, TypeError):
- scrape_item.children_limit = (
- self.manager.config_manager.settings_data.download_options.maximum_number_of_children[scrape_item.type]
- )
-
- posts_scrapers = [self.links, self.images, self.videos, self.embeds, self.attachments]
-
- for scraper in posts_scrapers:
- scrape_item.children += await scraper(scrape_item, post_content)
- if scrape_item.children_limit and scrape_item.children >= scrape_item.children_limit:
- raise MaxChildrenError(origin=scrape_item)
-
- @error_handling_wrapper
- async def links(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes links from a post."""
- links = post_content.select(self.links_selector)
- new_children = 0
- for link_obj in links:
- test_for_img = link_obj.select_one("img")
- if test_for_img is not None:
- continue
-
- link = link_obj.get(self.links_attribute)
- if not link:
- continue
-
- link = link.replace(".th.", ".").replace(".md.", ".")
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
- try:
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts or self.extra_attachment_url_part in link.parts:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown link type: {link}", 30)
- continue
- except TypeError:
- log(f"Scrape Failed: encountered while handling {link}", 40)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def images(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes images from a post."""
- images = post_content.select(self.images_selector)
- images.extend(post_content.select(self.extra_image_selector))
- new_children = 0
- for image in images:
- link = image.get(self.images_attribute)
- if not link:
- link = image.get(self.extra_image_attribute)
- if not link:
- continue
-
- link = link.replace(".th.", ".").replace(".md.", ".")
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts or self.extra_attachment_url_part in link.parts:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown image type: {link}", 30)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def videos(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes videos from a post."""
- videos = post_content.select(self.videos_selector)
- videos.extend(post_content.select(self.iframe_selector))
- new_children = 0
-
- for video in videos:
- link = video.get(self.videos_attribute)
- if not link:
- continue
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
-
- link = URL(link)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def embeds(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes embeds from a post."""
- embeds = post_content.select(self.embeds_selector)
- new_children = 0
- for embed in embeds:
- data = embed.get(self.embeds_attribute)
- if not data:
- continue
-
- data = data.replace(r"\/\/", "https://www.")
- data = data.replace("\\", "")
-
- embed = re.search(
- r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)",
- data,
- )
- if not embed:
- embed = re.search(
- r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\/[-a-zA-Z0-9@:%._\+~#=]*\/[-a-zA-Z0-9@:?&%._\+~#=]*",
- data,
- )
-
- if embed:
- link = embed.group(0).replace("www.", "")
- if link.endswith("/"):
- link = link[:-1]
- link = URL(link)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- @error_handling_wrapper
- async def attachments(self, scrape_item: ScrapeItem, post_content: Tag) -> int:
- """Scrapes attachments from a post."""
- attachment_block = post_content.select_one(self.attachments_block_selector)
- new_children = 0
- if not attachment_block:
- return new_children
- attachments = attachment_block.select(self.attachments_selector)
- for attachment in attachments:
- link = attachment.get(self.attachments_attribute)
- if not link:
- continue
-
- if link.endswith("/"):
- link = link[:-1]
-
- if link.startswith("//"):
- link = "https:" + link
- elif link.startswith("/"):
- link = self.primary_base_domain / link[1:]
- link = URL(link)
-
- if self.domain not in link.host:
- new_scrape_item = self.create_scrape_item(scrape_item, link, "")
- self.handle_external_links(new_scrape_item)
- elif self.attachment_url_part in link.parts or self.extra_attachment_url_part in link.parts:
- await self.handle_internal_links(link, scrape_item)
- else:
- log(f"Unknown image type: {link}", 30)
- new_children += 1
- if scrape_item.children_limit and (new_children + scrape_item.children) >= scrape_item.children_limit:
- break
- return new_children
-
- """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
-
- @error_handling_wrapper
- async def handle_internal_links(self, link: URL, scrape_item: ScrapeItem) -> None:
- """Handles internal links."""
- filename, ext = get_filename_and_ext(link.name, True)
- new_scrape_item = self.create_scrape_item(scrape_item, link, "Attachments", True)
- await self.handle_file(link, new_scrape_item, filename, ext)
+ self.attachment_url_part += "data"
diff --git a/cyberdrop_dl/scraper/crawlers/xenforo_crawler.py b/cyberdrop_dl/scraper/crawlers/xenforo_crawler.py
new file mode 100644
index 000000000..f596fb789
--- /dev/null
+++ b/cyberdrop_dl/scraper/crawlers/xenforo_crawler.py
@@ -0,0 +1,357 @@
+from __future__ import annotations
+
+import contextlib
+import re
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING
+
+from aiolimiter import AsyncLimiter
+from yarl import URL
+
+from cyberdrop_dl.scraper.crawler import Crawler, create_task_id
+from cyberdrop_dl.utils.data_enums_classes.url_objects import FORUM, FORUM_POST, ScrapeItem
+from cyberdrop_dl.utils.logger import log
+from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_filename_and_ext
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncGenerator
+
+ from bs4 import BeautifulSoup, Tag
+
+ from cyberdrop_dl.managers.manager import Manager
+
+
+HTTP_URL_REGEX_STRS = [
+ r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)",
+ r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\/[-a-zA-Z0-9@:%._\+~#=]*\/[-a-zA-Z0-9@:?&%._\+~#=]*",
+]
+
+HTTP_URL_PATTERNS = [re.compile(regex) for regex in HTTP_URL_REGEX_STRS]
+
+
+@dataclass(frozen=True)
+class Selector:
+ element: str
+ attribute: str = None
+
+
+@dataclass(frozen=True)
+class PostSelectors(Selector):
+ element: str = "div[class*=message-main]"
+ attachments: Selector = field(default=Selector("section[class=message-attachments] a ", "href"))
+ content: Selector = field(default=Selector("div[class*=message-userContent]", None))
+ date: Selector = field(default=Selector("time", "data-timestamp"))
+ embeds: Selector = field(default=Selector("span[data-s9e-mediaembed-iframe]", "data-s9e-mediaembed-iframe"))
+ iframe: Selector = field(default=Selector("iframe[class=saint-iframe]", "href"))
+ images: Selector = field(default=Selector("img[class*=bbImage]", "src"))
+ links: Selector = field(default=Selector("a", "href"))
+ number: Selector = field(default=Selector("li[class=u-concealed] a", "href"))
+ videos: Selector = field(default=Selector("video source", "src"))
+
+
+@dataclass(frozen=True)
+class XenforoSelectors:
+ next_page: Selector = field(default=Selector("a[class*=pageNav-jump--next]", "href"))
+ posts: PostSelectors = field(default=PostSelectors())
+ title: Selector = field(default=Selector("h1[class=p-title-value]", None))
+ title_trash: Selector = field(default=Selector("span", None))
+ quotes: Selector = field(default=Selector("blockquote", None))
+
+
+@dataclass(frozen=True)
+class ForumPost:
+ soup: BeautifulSoup
+ selectors: PostSelectors
+
+ @property
+ def content(self) -> Tag:
+ return self.soup.select_one(self.selectors.content.element)
+
+ @property
+ def date(self):
+ date = None
+ with contextlib.suppress(AttributeError):
+ date = int(self.content.select_one(self.selectors.date.element).get(self.selectors.date.attribute))
+ return date
+
+ @property
+ def number(self):
+ number = self.soup.select_one(self.selectors.number.element)
+ return int(number.get(self.selectors.number.attribute).split("/")[-1].split("post-")[-1])
+
+
+class XenforoCrawler(Crawler):
+ login_required = True
+ primary_base_domain = None
+ selectors = XenforoSelectors()
+
+ def __init__(self, manager: Manager, site: str, folder_domain: str | None = None) -> None:
+ super().__init__(manager, site, folder_domain)
+ self.primary_base_domain = self.primary_base_domain or URL(f"https://{site}")
+ self.attachment_url_part = ["attachments"]
+ self.attachment_url_hosts = ["smgmedia", "attachments.f95zone"]
+ self.logged_in = False
+ self.login_attempts = 0
+ self.request_limiter = AsyncLimiter(10, 1)
+
+ """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
+
+ @create_task_id
+ async def fetch(self, scrape_item: ScrapeItem) -> None:
+ """Determines where to send the scrape item based on the url."""
+ if "threads" not in scrape_item.url.parts:
+ log(f"Scrape Failed: Unknown URL path: {scrape_item.url}", 40)
+ return
+
+ if not self.logged_in and self.login_attempts == 0:
+ await self.try_login()
+
+ await self.thread(scrape_item)
+
+ async def try_login(self) -> None:
+ login_url = self.primary_base_domain / "login"
+ host_cookies: dict = self.client.client_manager.cookies.filter_cookies(self.primary_base_domain)
+ session_cookie = host_cookies.get("xf_user")
+ session_cookie = session_cookie.value if session_cookie else None
+ forums_auth_data = self.manager.config_manager.authentication_data.forums
+ if session_cookie:
+ self.logged_in = True
+ return
+
+ session_cookie = getattr(forums_auth_data, f"{self.domain}_xf_user_cookie")
+ username = getattr(forums_auth_data, f"{self.domain}_username")
+ password = getattr(forums_auth_data, f"{self.domain}_password")
+
+ if session_cookie or (username and password):
+ self.login_attempts += 1
+ await self.forum_login(login_url, session_cookie, username, password)
+
+ if not self.logged_in:
+ msg = f"{self.folder_domain} login failed. "
+ if not self.login_required:
+ msg += "Scraping without an account."
+ log(msg, 40)
+
+ @error_handling_wrapper
+ async def thread(self, scrape_item: ScrapeItem) -> None:
+ """Scrapes a forum thread."""
+ if not self.logged_in and self.login_required:
+ return
+
+ scrape_item.set_type(FORUM, self.manager)
+
+ thread_url = scrape_item.url
+ post_number = 0
+ post_sections = {scrape_item.url.fragment}
+ threads_part_index = scrape_item.url.parts.index("threads")
+ thread_id = thread_url.parts[threads_part_index].split(".")[-1].split("#")[0]
+ post_part_index = threads_part_index + 1
+ if len(scrape_item.url.parts) > post_part_index:
+ post_sections.add(scrape_item.url.parts[post_part_index])
+
+ if any("post-" in sec for sec in post_sections):
+ url_parts = str(scrape_item.url).rsplit("post-", 1)
+ thread_url = URL(url_parts[0].rstrip("#"))
+ post_number = int(url_parts[-1].strip("/")) if len(url_parts) == 2 else 0
+
+ last_scraped_post_number = None
+ async for soup in self.thread_pager(scrape_item):
+ title_block = soup.select_one(self.selectors.title.element)
+ trash: list[Tag] = title_block.find_all(self.selectors.title_trash.element)
+ for element in trash:
+ element.decompose()
+
+ title = self.create_title(title_block.text.replace("\n", ""), thread_id=thread_id)
+ posts = soup.select(self.selectors.posts.element)
+ continue_scraping = False
+ for post in posts:
+ current_post = ForumPost(post, selectors=self.selectors.posts)
+ last_scraped_post_number = current_post.number
+ scrape_post, continue_scraping = self.check_post_number(post_number, current_post.number)
+
+ if scrape_post:
+ new_scrape_item = self.create_scrape_item(
+ scrape_item,
+ thread_url,
+ title,
+ possible_datetime=current_post.date,
+ add_parent=scrape_item.url.joinpath(f"post-{current_post.number}"),
+ )
+ trash: list[Tag] = title_block.find_all(self.selectors.quotes.element)
+ for element in trash:
+ element.decompose()
+
+ await self.post(new_scrape_item, current_post)
+ scrape_item.add_children()
+
+ if not continue_scraping:
+ break
+ if not continue_scraping:
+ break
+
+ await self.write_last_forum_post(scrape_item, last_scraped_post_number)
+
+ async def post(self, scrape_item: ScrapeItem, post: ForumPost) -> None:
+ """Scrapes a post."""
+ if self.manager.config_manager.settings_data.download_options.separate_posts:
+ scrape_item.add_to_parent_title(f"post-{post.number}")
+
+ scrape_item.set_type(FORUM_POST, self.manager)
+ posts_scrapers = [self.attachments, self.embeds, self.images, self.links, self.videos]
+ for scraper in posts_scrapers:
+ await scraper(scrape_item, post)
+
+ async def links(self, scrape_item: ScrapeItem, post: ForumPost) -> None:
+ """Scrapes links from a post."""
+ selector = post.selectors.links
+ links = post.content.select(selector.element)
+ links = [link for link in links if self.is_valid_post_link(link)]
+ await self.process_children(scrape_item, links, selector.attribute)
+
+ async def images(self, scrape_item: ScrapeItem, post: ForumPost) -> None:
+ """Scrapes images from a post."""
+ selector = post.selectors.images
+ images = post.content.select(selector.element)
+ await self.process_children(scrape_item, images, selector.attribute)
+
+ async def videos(self, scrape_item: ScrapeItem, post: ForumPost) -> None:
+ """Scrapes videos from a post."""
+ selector = post.selectors.videos
+ iframe_selector = post.selectors.iframe
+ videos = post.content.select(selector.element)
+ videos.extend(post.content.select(iframe_selector.element))
+ await self.process_children(scrape_item, videos, selector.attribute)
+
+ async def embeds(self, scrape_item: ScrapeItem, post: ForumPost) -> None:
+ """Scrapes embeds from a post."""
+ selector = post.selectors.embeds
+ embeds = post.content.select(selector.element)
+ await self.process_children(scrape_item, embeds, selector.attribute)
+
+ async def attachments(self, scrape_item: ScrapeItem, post: ForumPost) -> None:
+ """Scrapes attachments from a post."""
+ selector = post.selectors.attachments
+ attachments = post.content.select(selector.attribute)
+ await self.process_children(scrape_item, attachments, selector.attribute)
+
+ """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
+
+ def process_embed(self, data: str) -> URL:
+ if not data:
+ return
+ data = data.replace(r"\/\/", "https://www.").replace("\\", "")
+ embed = re.search(HTTP_URL_PATTERNS[0], data) or re.search(HTTP_URL_PATTERNS[1], data)
+ return embed.group(0).replace("www.", "") if embed else data
+
+ async def process_children(self, scrape_item: ScrapeItem, links: list[Tag], selector: str) -> None:
+ for link_obj in links:
+ link: Tag = link_obj.get(selector) or link_obj.get("href")
+ if not link:
+ continue
+ if not isinstance(link, str):
+ parent_simp_check = link.parent.get("data-simp")
+ if parent_simp_check and "init" in parent_simp_check:
+ continue
+ if selector == self.selectors.posts.embeds.attribute:
+ link = self.process_embed(link)
+ if not link:
+ continue
+ if str(link).startswith("data:image/svg"):
+ continue
+ link = await self.get_absolute_link(link)
+ await self.handle_link(scrape_item, link)
+ scrape_item.add_children()
+
+ def is_attachment(self, link: URL | str) -> bool:
+ if not link:
+ return False
+ if isinstance(link, str):
+ link = URL(link)
+ return any(part in link.parts for part in self.attachment_url_part) or any(
+ host in link.host for host in self.attachment_url_hosts
+ )
+
+ async def handle_link(self, scrape_item: ScrapeItem, link: URL) -> None:
+ if not link:
+ return
+ try:
+ if self.domain not in link.host:
+ new_scrape_item = self.create_scrape_item(scrape_item, link)
+ new_scrape_item.reset_childen()
+ self.handle_external_links(new_scrape_item)
+ elif self.is_attachment(link):
+ await self.handle_internal_link(link, scrape_item)
+ else:
+ log(f"Unknown link type: {link}", 30)
+ except TypeError:
+ log(f"Scrape Failed: encountered while handling {link}", 40)
+
+ async def handle_internal_link(self, link: URL, scrape_item: ScrapeItem) -> None:
+ """Handles internal links."""
+ filename, ext = get_filename_and_ext(link.name, True)
+ new_scrape_item = self.create_scrape_item(scrape_item, link, "Attachments", part_of_album=True)
+ await self.handle_file(link, new_scrape_item, filename, ext)
+
+ async def is_confirmation_link(self, link: URL) -> bool:
+ return False
+
+ @error_handling_wrapper
+ async def handle_confirmation_link(self, link: URL, *, origin: ScrapeItem | None = None) -> URL | None:
+ """Handles link confirmation."""
+ async with self.request_limiter:
+ soup: BeautifulSoup = await self.client.get_soup(self.domain, link, origin=origin)
+ confirm_button = soup.select_one("a[class*=button--cta]")
+ if confirm_button:
+ return URL(confirm_button.get("href"))
+ return None
+
+ async def write_last_forum_post(self, scrape_item: ScrapeItem, post_number: int) -> None:
+ if not post_number:
+ return
+ post_string = f"post-{post_number}"
+ if "page-" in scrape_item.url.raw_name or "post-" in scrape_item.url.raw_name:
+ last_post_url = scrape_item.url.parent / post_string
+ else:
+ last_post_url = scrape_item.url / post_string
+ await self.manager.log_manager.write_last_post_log(last_post_url)
+
+ async def thread_pager(self, scrape_item: ScrapeItem) -> AsyncGenerator[BeautifulSoup]:
+ """Generator of forum thread pages."""
+ page_url = scrape_item.url
+ while True:
+ async with self.request_limiter:
+ soup: BeautifulSoup = await self.client.get_soup(self.domain, page_url, origin=scrape_item)
+ next_page = soup.select_one(self.selectors.next_page.element)
+ yield soup
+ if next_page:
+ page_url = next_page.get(self.selectors.next_page.attribute)
+ if page_url:
+ if page_url.startswith("/"):
+ page_url = self.primary_base_domain / page_url[1:]
+ page_url = URL(page_url)
+ log(f"scraping page: {page_url}")
+ continue
+ break
+
+ def is_valid_post_link(self, link_obj: Tag) -> bool:
+ is_image = link_obj.select_one("img")
+ link = link_obj.get(self.selectors.posts.links.element)
+ return not (is_image and self.is_attachment(link))
+
+ async def get_absolute_link(self, link: URL | str) -> URL:
+ if isinstance(link, str):
+ encoded = "%" in link
+ link = link.replace(".th.", ".").replace(".md.", ".").replace("ifr", "watch")
+ if link.endswith("/"):
+ link = link[:-1]
+ if link.startswith("//"):
+ link = "https:" + link
+ elif link.startswith("/"):
+ link = self.primary_base_domain.joinpath(link[1:], encoded=encoded)
+
+ if isinstance(link, str):
+ link = URL(link, encoded=encoded)
+ if await self.is_confirmation_link(link) or any(keyword in link.path for keyword in ("link-confirmation",)):
+ link = await self.handle_confirmation_link(link)
+
+ return link
diff --git a/cyberdrop_dl/utils/data_enums_classes/url_objects.py b/cyberdrop_dl/utils/data_enums_classes/url_objects.py
index ca2e37448..57bfc6f40 100644
--- a/cyberdrop_dl/utils/data_enums_classes/url_objects.py
+++ b/cyberdrop_dl/utils/data_enums_classes/url_objects.py
@@ -1,16 +1,20 @@
from __future__ import annotations
+import contextlib
from dataclasses import dataclass, field
from enum import IntEnum
from pathlib import Path
from typing import TYPE_CHECKING
+from cyberdrop_dl.clients.errors import MaxChildrenError
from cyberdrop_dl.utils.utilities import sanitize_folder
if TYPE_CHECKING:
from rich.progress import TaskID
from yarl import URL
+ from cyberdrop_dl.managers.manager import Manager
+
class ScrapeItemType(IntEnum):
FORUM = 0
@@ -67,6 +71,7 @@ class ScrapeItem:
type: int | None = field(default=None, init=False)
completed_at: int | None = field(default=None, init=False)
created_at: int | None = field(default=None, init=False)
+ children_limits: list[int] = field(default=list, init=False)
def add_to_parent_title(self, title: str) -> None:
"""Adds a title to the parent title."""
@@ -74,3 +79,18 @@ class ScrapeItem:
return
title = sanitize_folder(title)
self.parent_title = (self.parent_title + "/" + title) if self.parent_title else title
+
+ def set_type(self, scrape_item_type: ScrapeItemType, manager: Manager) -> None:
+ self.type = scrape_item_type
+ self.children_limit = manager.config_manager.settings_data.download_options.maximum_number_of_children
+ self.reset_childen()
+
+ def reset_childen(self) -> None:
+ self.children = self.children_limit = 0
+ with contextlib.suppress(IndexError, TypeError):
+ self.children_limit = self.children_limit[self.type]
+
+ def add_children(self, number: int = 1) -> None:
+ self.children += number
+ if self.children_limit and self.children >= self.children_limit:
+ raise MaxChildrenError(origin=self)