Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: move non cancelling taskgroup to aio

NTFSvolumea94f99378150
diff --git a/cyberdrop_dl/aio.py b/cyberdrop_dl/aio.py
index b2259ffad..28d7725b8 100644
--- a/cyberdrop_dl/aio.py
+++ b/cyberdrop_dl/aio.py
@@ -97,6 +97,39 @@ class EagerTaskGroup(asyncio.TaskGroup):
return self.create_task(coro, name=name, context=context, eager_start=True)
+async def non_cancelling_taskgroup() -> AsyncGenerator[EagerTaskGroup]:
+ """A taskgroup that does not cancel its tasks if an exception is raised within its `async with` context
+
+ Exceptions raised within a task will still cancel all others tasks
+
+ This is mostly just to catch `MaxChildrenError`"""
+
+ context_exc = None
+ task_exc = None
+
+ try:
+ async with EagerTaskGroup() as tg:
+ try:
+ yield tg
+ except Exception as e: # noqa: BLE001
+ context_exc = e
+ except ExceptionGroup as eg:
+ if context_exc is None:
+ raise
+ task_exc = eg
+
+ try:
+ if task_exc is not None and context_exc is not None:
+ raise BaseExceptionGroup(task_exc.message, (*task_exc.exceptions, context_exc)) from None
+ if task_exc is not None:
+ raise task_exc from None
+ if context_exc is not None:
+ raise context_exc from None
+ finally:
+ context_exc = task_exc = None
+
+
@dataclasses.dataclass(frozen=True, slots=True, eq=False)
class TaskManager:
logs: EagerTaskGroup = dataclasses.field(default_factory=EagerTaskGroup)
diff --git a/cyberdrop_dl/crawlers/_forum.py b/cyberdrop_dl/crawlers/_forum.py
index c9d38d06b..c2ebe9dff 100644
--- a/cyberdrop_dl/crawlers/_forum.py
+++ b/cyberdrop_dl/crawlers/_forum.py
@@ -461,7 +461,8 @@ class HTMLMessageBoardCrawler(MessageBoardCrawler, is_abc=True):
scrape_item.append_folders(post_title)
stats: dict[str, int] = {}
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
for scraper in (
self._attachments,
self._images,
@@ -475,6 +476,7 @@ class HTMLMessageBoardCrawler(MessageBoardCrawler, is_abc=True):
stats[scraper_name] = stats.get(scraper_name, 0) + 1
tg.create_task(self.process_child(scrape_item, url, embeds="embeds" in scraper_name))
scrape_item.add_children()
+ await sleep()
if stats:
self.log.info(f"post #{post.id} {stats = }")
diff --git a/cyberdrop_dl/crawlers/archve.py b/cyberdrop_dl/crawlers/archve.py
index 261d66fad..733ce34bc 100644
--- a/cyberdrop_dl/crawlers/archve.py
+++ b/cyberdrop_dl/crawlers/archve.py
@@ -8,7 +8,7 @@ import time
from typing import TYPE_CHECKING, ClassVar, override
from cyberdrop_dl import aio
-from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedPaths
+from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedPaths, auto_task_id
from cyberdrop_dl.exceptions import NoExtensionError, ScrapeError
from cyberdrop_dl.url_objects import AbsoluteHttpURL, ScrapeItem
from cyberdrop_dl.utils import b64_pad, css, extr_text
@@ -68,6 +68,8 @@ class ArchveCrawler(Crawler):
video = await self.api.video(video_id)
await self._video(scrape_item, video)
+ _video_task = auto_task_id(video)
+
async def _video(self, scrape_item: ScrapeItem, video: Video) -> None:
try:
filename, ext = self.get_filename_and_ext(video.title, assume_ext=".mp4")
@@ -99,9 +101,9 @@ class ArchveCrawler(Crawler):
scrape_item.setup_as_album(self.create_title(album.name, album_id), album_id=album_id)
sleep = aio.periodic_sleep(10)
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
for video in album.videos:
- tg.create_task(self.video(scrape_item.create_child(video), video.name))
+ tg.create_task(self._video_task(scrape_item.create_child(video), video.name))
scrape_item.add_children()
await sleep()
@@ -111,11 +113,16 @@ class ArchveCrawler(Crawler):
name = css.select_text(soup, "h1")
scrape_item.setup_as_profile(self.create_title(f"{name} [user]", user_id))
- async for soup in pages:
- for child in self.iter_children(
- scrape_item, soup, ".media-section[aria-labelledby='profile-videos-heading'] .media-grid .media-card"
- ):
- self.create_eager_task(self.video(child, child.url.name))
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
+ async for soup in pages:
+ for child in self.iter_children(
+ scrape_item,
+ soup,
+ ".media-section[aria-labelledby='profile-videos-heading'] .media-grid .media-card",
+ ):
+ tg.create_task(self._video_task(child, child.url.name))
+ await sleep()
@error_handling_wrapper
async def user_albums(self, scrape_item: ScrapeItem, user_id: str) -> None:
diff --git a/cyberdrop_dl/crawlers/bunkr.py b/cyberdrop_dl/crawlers/bunkr.py
index d53c72811..ed3b27d26 100644
--- a/cyberdrop_dl/crawlers/bunkr.py
+++ b/cyberdrop_dl/crawlers/bunkr.py
@@ -135,7 +135,7 @@ class BunkrCrawler(Crawler):
sleep = aio.periodic_sleep(10)
downloaded = await self.get_completed_by_album(album_id)
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
for file in self._parse_files(css.select_text(soup, Selector.ALBUM_FILES)):
# This is not the real src but our custom __db_path__ will resolve it to the same db entry
if self.parse_url(file.cdnEndpoint) in downloaded:
diff --git a/cyberdrop_dl/crawlers/clonr.py b/cyberdrop_dl/crawlers/clonr.py
index ebe56ad09..e3720a5b7 100644
--- a/cyberdrop_dl/crawlers/clonr.py
+++ b/cyberdrop_dl/crawlers/clonr.py
@@ -57,9 +57,9 @@ class ClonrCrawler(Crawler):
return
sleep = aio.periodic_sleep(10)
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
for file in files:
- tg.create_eager_task(self._file(scrape_item, file))
+ tg.create_task(self._file(scrape_item, file))
scrape_item.add_children()
await sleep()
diff --git a/cyberdrop_dl/crawlers/crawler.py b/cyberdrop_dl/crawlers/crawler.py
index 23cccbd1e..deb0bedb2 100644
--- a/cyberdrop_dl/crawlers/crawler.py
+++ b/cyberdrop_dl/crawlers/crawler.py
@@ -37,7 +37,6 @@ if TYPE_CHECKING:
import datetime as dt
import http.cookies
from collections.abc import (
- AsyncGenerator,
AsyncIterator,
Awaitable,
Callable,
@@ -420,6 +419,8 @@ class Crawler(HTTPMixin, HLSMixin, ABC):
"""Run this coro as soon as possible"""
_ = self._task_mngr.scrape.create_eager_task(coro)
+ new_task_group: Final = staticmethod(aio.non_cancelling_taskgroup)
+
@abstractmethod
async def fetch(self, scrape_item: ScrapeItem) -> None:
"""Here goes the main logic to parse URL paths.
@@ -963,39 +964,6 @@ class Crawler(HTTPMixin, HLSMixin, ABC):
filename, ext = self.get_filename_and_ext(url.name or url.parent.name, assume_ext=assume_ext)
await self.handle_file(url, scrape_item, filename, ext)
- @final
- @contextlib.asynccontextmanager
- async def new_task_group(self) -> AsyncGenerator[aio.EagerTaskGroup]:
- """A taskgroup that does not cancel its tasks if an exception is raised within its `async with` context
-
- Exceptions raised within a task will still cancel all tasks
-
- This is mostly just to catch `MaxChildrenError`"""
-
- context_exc = None
- task_exc = None
-
- try:
- async with aio.EagerTaskGroup() as tg:
- try:
- yield tg
- except Exception as e: # noqa: BLE001
- context_exc = e
- except ExceptionGroup as eg:
- if context_exc is None:
- raise
- task_exc = eg
-
- try:
- if task_exc is not None and context_exc is not None:
- raise ExceptionGroup(task_exc.message, (*task_exc.exceptions, context_exc)) from None
- if task_exc is not None:
- raise task_exc from None
- if context_exc is not None:
- raise context_exc from None
- finally:
- context_exc = task_exc = None
-
@final
@classmethod
def parse_date(cls, date_or_datetime: str, /, format: str) -> float: # noqa: A002
diff --git a/cyberdrop_dl/crawlers/filester.py b/cyberdrop_dl/crawlers/filester.py
index 71016cd24..bc9c40dfd 100644
--- a/cyberdrop_dl/crawlers/filester.py
+++ b/cyberdrop_dl/crawlers/filester.py
@@ -91,7 +91,7 @@ class FilesterCrawler(Crawler):
downloaded = await self.get_completed_by_album(album_id)
sleep = aio.periodic_sleep(10)
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
async for soup in pages:
for on_click in unique(css.iselect(soup, Selector.FILES, "onclick")):
web_url = self.parse_url(extr_text(on_click, "'", "'"), self.origin)
diff --git a/cyberdrop_dl/crawlers/goonbox.py b/cyberdrop_dl/crawlers/goonbox.py
index 48a5eeef6..10ea1c686 100644
--- a/cyberdrop_dl/crawlers/goonbox.py
+++ b/cyberdrop_dl/crawlers/goonbox.py
@@ -3,8 +3,9 @@ from __future__ import annotations
import dataclasses
from typing import TYPE_CHECKING, Any, ClassVar, Self
+from cyberdrop_dl import aio
from cyberdrop_dl.crawlers import Registry
-from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedDomains, SupportedPaths
+from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedDomains, SupportedPaths, auto_task_id
from cyberdrop_dl.url_objects import AbsoluteHttpURL
from cyberdrop_dl.utils import parse_url
from cyberdrop_dl.utils.dataclass import deserialize
@@ -110,43 +111,47 @@ class GoonBoxCrawler(Crawler):
@error_handling_wrapper
async def user_albums(self, scrape_item: ScrapeItem, user: str) -> None:
scrape_item.setup_as_profile(self.create_title(f"{user} [user]"))
-
+ sleep = aio.periodic_sleep(10)
async for albums in self.api.user_albums(user, scrape_item.url.query):
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
for album in albums:
- url = self.PRIMARY_URL / "a" / album.encoded_id
- new_item = scrape_item.create_child(url)
- tg.create_lazy_task(self._album(new_item, album))
+ new_item = scrape_item.create_child(self.PRIMARY_URL / "a" / album.encoded_id)
+ tg.create_lazy_task(self._album_task(new_item, album))
scrape_item.add_children()
+ await sleep()
@error_handling_wrapper
async def user_images(self, scrape_item: ScrapeItem, user: str) -> None:
scrape_item.setup_as_profile(self.create_title(f"{user} [user]"))
scrape_item.append_folders("images")
+ sleep = aio.periodic_sleep(10)
- async for images in self.api.user_images(user, scrape_item.url.query):
- for img in images:
- url = self.PRIMARY_URL / "img" / img.encoded_id
- new_item = scrape_item.create_child(url)
- self.create_eager_task(self._image(new_item, img))
- scrape_item.add_children()
+ async with aio.non_cancelling_taskgroup() as tg:
+ async for images in self.api.user_images(user, scrape_item.url.query):
+ for img in images:
+ new_item = scrape_item.create_child(self.PRIMARY_URL / "img" / img.encoded_id)
+ tg.create_task(self._image(new_item, img))
+ scrape_item.add_children()
+ await sleep()
- @error_handling_wrapper
async def _album(self, scrape_item: ScrapeItem, album: Album) -> None:
title = self.create_title(album.title, album.encoded_id)
scrape_item.setup_as_album(title, album_id=album.encoded_id)
-
downloaded = await self.get_completed_by_album(album.encoded_id)
+ sleep = aio.periodic_sleep(10)
+
+ async with aio.non_cancelling_taskgroup() as tg:
+ async for images in self.api.album_images(album.encoded_id, scrape_item.url.query):
+ for img in images:
+ if img.src in downloaded:
+ continue
- async for images in self.api.album_images(album.encoded_id, scrape_item.url.query):
- for img in images:
- if img.src in downloaded:
- continue
+ new_item = scrape_item.create_child(self.PRIMARY_URL / "img" / img.encoded_id)
+ tg.create_task(self._image(new_item, img))
+ scrape_item.add_children()
+ await sleep()
- url = self.PRIMARY_URL / "img" / img.encoded_id
- new_item = scrape_item.create_child(url)
- self.create_eager_task(self._image(new_item, img))
- scrape_item.add_children()
+ _album_task = auto_task_id(error_handling_wrapper(_album))
@dataclasses.dataclass(frozen=True, slots=True)
diff --git a/cyberdrop_dl/crawlers/imgbox.py b/cyberdrop_dl/crawlers/imgbox.py
index dafc06b71..cea2b4b7d 100644
--- a/cyberdrop_dl/crawlers/imgbox.py
+++ b/cyberdrop_dl/crawlers/imgbox.py
@@ -3,6 +3,7 @@ from __future__ import annotations
from http import HTTPStatus
from typing import ClassVar, final, override
+from cyberdrop_dl import aio
from cyberdrop_dl.clients import etag
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
from cyberdrop_dl.exceptions import ScrapeError
@@ -62,10 +63,12 @@ class ImgBoxCrawler(Crawler):
name = css.select_text(soup, Selector.ALBUM_TITLE).rsplit(" - ", 1)[0]
scrape_item.setup_as_album(self.create_title(name, album_id), album_id=album_id)
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
for src in map(_thumb_to_src, self.iter_urls(soup, Selector.IMAGES, "src")):
tg.create_task(self.direct_file(scrape_item, src))
scrape_item.add_children()
+ await sleep()
@error_handling_wrapper
async def image(self, scrape_item: ScrapeItem) -> None:
diff --git a/cyberdrop_dl/crawlers/kemono/kemono.py b/cyberdrop_dl/crawlers/kemono/kemono.py
index 0abfbf333..266fb5256 100644
--- a/cyberdrop_dl/crawlers/kemono/kemono.py
+++ b/cyberdrop_dl/crawlers/kemono/kemono.py
@@ -7,7 +7,8 @@ from collections.abc import Generator
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar, Literal
-from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
+from cyberdrop_dl import aio
+from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths, auto_task_id
from cyberdrop_dl.exceptions import NoExtensionError, ScrapeError
from cyberdrop_dl.utils import unique
from cyberdrop_dl.utils.errors import error_handling_wrapper
@@ -92,6 +93,8 @@ class KemonoBaseCrawler[T: KemonoAPI[Any]](Crawler, is_abc=True):
post = await self.api.post(service, creator_id, post_id)
await self._user_post(scrape_item, post)
+ _post_task = auto_task_id(post)
+
@error_handling_wrapper
async def favorites(self, scrape_item: ScrapeItem, type_: Literal["post", "artist"]) -> None:
session_cookie = self.cookies.get("session")
@@ -148,10 +151,12 @@ class KemonoBaseCrawler[T: KemonoAPI[Any]](Crawler, is_abc=True):
self._extract_urls_from_post_content(scrape_item, post)
async def _extract_post_files(self, scrape_item: ScrapeItem, post_files: FileFilterer) -> None:
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
for url in unique(map(self._compose_file_url, post_files)):
tg.create_task(self._direct_file(scrape_item, url))
scrape_item.add_children()
+ await sleep()
if embed := post_files.embed():
embed_url = self.parse_url(embed.url)
@@ -186,7 +191,8 @@ class KemonoBaseCrawler[T: KemonoAPI[Any]](Crawler, is_abc=True):
return url.update_query(f=file.name or url.name)
async def __iter_user_posts(self, scrape_item: ScrapeItem, posts: Iterable[UserPostModel]) -> None:
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
for post in posts:
self.__check_for_ads(post)
new_item = scrape_item.create_child(self.parse_url(post.web_path_qs))
@@ -196,8 +202,11 @@ class KemonoBaseCrawler[T: KemonoAPI[Any]](Crawler, is_abc=True):
if expand:
tg.create_task(self.post(new_item, post.service, post.user_id, post.id))
else:
- await self._user_post(new_item, post)
+ tg.create_task(self._user_post_task(new_item, post))
scrape_item.add_children()
+ await sleep()
+
+ _user_post_task = auto_task_id(_user_post)
def _thumbnail_to_src(og_url: AbsoluteHttpURL) -> AbsoluteHttpURL:
diff --git a/cyberdrop_dl/crawlers/kemono/only_haven.py b/cyberdrop_dl/crawlers/kemono/only_haven.py
index 9400e6b87..2c95dd690 100644
--- a/cyberdrop_dl/crawlers/kemono/only_haven.py
+++ b/cyberdrop_dl/crawlers/kemono/only_haven.py
@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Any, ClassVar, override
from pydantic import Field
from pydantic.aliases import AliasChoices
+from cyberdrop_dl import aio
from cyberdrop_dl.crawlers.kemono.api import KemonoAPI
from cyberdrop_dl.crawlers.kemono.kemono import KemonoBaseCrawler
from cyberdrop_dl.crawlers.kemono.models import User
@@ -171,10 +172,12 @@ class OnlyHavenCrawler(KemonoBaseCrawler[OnlyHavenAPI]):
@override
async def _extract_post_files(self, scrape_item: ScrapeItem, post_files: FileFilterer) -> None: # pyright: ignore[reportIncompatibleMethodOverride]
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
for url in unique(map(self._compose_file_url, post_files)):
tg.create_task(self._direct_file(scrape_item, url))
scrape_item.add_children()
+ await sleep()
@override
def _compose_file_url(self, file: File) -> AbsoluteHttpURL: # pyright: ignore[reportIncompatibleMethodOverride]
diff --git a/cyberdrop_dl/crawlers/kemono/pawchive.py b/cyberdrop_dl/crawlers/kemono/pawchive.py
index 7b5dffcec..df1ae1059 100644
--- a/cyberdrop_dl/crawlers/kemono/pawchive.py
+++ b/cyberdrop_dl/crawlers/kemono/pawchive.py
@@ -2,6 +2,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any, ClassVar, override
+from cyberdrop_dl import aio
from cyberdrop_dl.clients.http import HTTPConfig
from cyberdrop_dl.constants import CDL_USER_AGENT
from cyberdrop_dl.crawlers.crawler import DownloadConfig
@@ -85,13 +86,15 @@ class PawchiveCrawler(KemonoBaseCrawler[PawchiveAPI]):
return
self.log.info("Trying to get temp download URLs for deferred files in post %s", post_files.post.id)
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
for file in post_files.temp_dls:
src = file.temp_download_url or file.temp_url
if not src:
continue
self.log.info("Found temp deferred file '%s' (%s)", file.deferred, src)
tg.create_task(self._temp_file(scrape_item, self.parse_url(src), file.name))
+ await sleep()
async def _temp_file(
self, scrape_item: ScrapeItem, src: AbsoluteHttpURL | None = None, name: str | None = None
diff --git a/cyberdrop_dl/crawlers/kick.py b/cyberdrop_dl/crawlers/kick.py
index 4045cc17d..8bdaa58c5 100644
--- a/cyberdrop_dl/crawlers/kick.py
+++ b/cyberdrop_dl/crawlers/kick.py
@@ -4,7 +4,7 @@ import dataclasses
from typing import TYPE_CHECKING, Any, ClassVar, Final, Self, override
from cyberdrop_dl import aio
-from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedPaths
+from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedPaths, auto_task_id
from cyberdrop_dl.exceptions import ScrapeError
from cyberdrop_dl.models import type_adapter
from cyberdrop_dl.url_objects import AbsoluteHttpURL
@@ -102,13 +102,16 @@ class KickCrawler(Crawler):
async def clips(self, scrape_item: ScrapeItem, channel_name: str) -> None:
scrape_item.setup_as_profile("")
channel = await self.api.channel(channel_name)
- async for clips in self.api.channel.clips(channel.id, scrape_item.url.query):
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
+ async for clips in self.api.channel.clips(channel.id, scrape_item.url.query):
for clip in clips:
new_item = scrape_item.create_child(scrape_item.url / clip.id)
tg.create_task(self.clip_task(new_item, clip))
scrape_item.add_children()
+ await sleep()
+ @auto_task_id
@error_handling_wrapper
async def clip_task(self, scrape_item: ScrapeItem, clip: Clip) -> None:
if await self.check_complete_from_referer(scrape_item.url):
@@ -121,12 +124,15 @@ class KickCrawler(Crawler):
scrape_item.setup_as_profile("")
channel = await self.api.channel(channel_name)
videos = await self.api.channel.videos(channel.id)
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
for vod in videos:
new_item = scrape_item.create_child(scrape_item.url / vod.id)
tg.create_task(self.vod_task(new_item, vod))
scrape_item.add_children()
+ await sleep()
+ @auto_task_id
@error_handling_wrapper
async def vod_task(self, scrape_item: ScrapeItem, meta: VODMetadata) -> None:
if await self.check_complete_from_referer(scrape_item.url):
diff --git a/cyberdrop_dl/crawlers/koofr.py b/cyberdrop_dl/crawlers/koofr.py
index 3f8080353..e4a2254ab 100644
--- a/cyberdrop_dl/crawlers/koofr.py
+++ b/cyberdrop_dl/crawlers/koofr.py
@@ -1,9 +1,11 @@
from __future__ import annotations
+from collections import deque
from typing import Any, ClassVar, Literal
from pydantic import dataclasses
+from cyberdrop_dl import aio
from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedDomains, SupportedPaths
from cyberdrop_dl.exceptions import DownloadError, PasswordProtectedError, ScrapeError
from cyberdrop_dl.url_objects import AbsoluteHttpURL, ScrapeItem
@@ -61,19 +63,28 @@ class KooFrCrawler(Crawler):
scrape_item.setup_as_album(title, album_id=content_id)
await self._walk_folder(scrape_item, content_id, path)
- @error_handling_wrapper
- async def _walk_folder(self, scrape_item: ScrapeItem, content_id: str, path: str) -> None:
- children = await self.api.get_children(content_id, path, scrape_item.password)
- async with self.new_task_group() as tg:
- for node in children:
- if node.type == "file":
- tg.create_task(self._file(scrape_item, node))
- continue
-
- url = scrape_item.url.update_query(path=node.path)
- new_scrape_item = scrape_item.create_child(url)
- new_scrape_item.append_folders(node.name)
- tg.create_task(self._walk_folder(new_scrape_item, content_id, node.path))
+ async def _walk_folder(self, scrape_item: ScrapeItem, content_id: str, node_path: str) -> None:
+ subfolders: deque[tuple[tuple[str, ...], str]] = deque()
+ parents = ()
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
+ while True:
+ children = await self.api.get_children(content_id, node_path, scrape_item.password)
+ for node in children:
+ if node.type != "file":
+ subfolders.append(((*parents, node.name), node.path))
+ continue
+
+ url = scrape_item.url.update_query(path=node.path)
+ new_item = scrape_item.create_child(url)
+ new_item.append_folders(*parents)
+ tg.create_task(self._file(new_item, node))
+ await sleep()
+
+ if not subfolders:
+ break
+
+ parents, node_path = subfolders.popleft()
@error_handling_wrapper
async def _file(self, scrape_item: ScrapeItem, file: Node) -> None:
diff --git a/cyberdrop_dl/crawlers/multporn.py b/cyberdrop_dl/crawlers/multporn.py
index 68432bb52..c034a1881 100644
--- a/cyberdrop_dl/crawlers/multporn.py
+++ b/cyberdrop_dl/crawlers/multporn.py
@@ -44,10 +44,13 @@ class MultPornCrawler(Crawler):
name, date = await _extract_info(soup)
scrape_item.uploaded_at = self.parse_iso_date(date)
scrape_item.setup_as_album(self.create_title(name))
- async with self.new_task_group() as tg:
+
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
for img in _extract_images(soup):
tg.create_task(self.direct_file(scrape_item, img))
scrape_item.add_children()
+ await sleep()
@error_handling_wrapper
async def video(self, scrape_item: ScrapeItem) -> None:
diff --git a/cyberdrop_dl/crawlers/nudostartv.py b/cyberdrop_dl/crawlers/nudostartv.py
index c753e5895..185ce0579 100644
--- a/cyberdrop_dl/crawlers/nudostartv.py
+++ b/cyberdrop_dl/crawlers/nudostartv.py
@@ -3,7 +3,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar
from cyberdrop_dl import aio
-from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths, URLConfig
+from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths, URLConfig, auto_task_id
from cyberdrop_dl.url_objects import AbsoluteHttpURL
from cyberdrop_dl.utils import css
from cyberdrop_dl.utils.errors import error_handling_wrapper
@@ -43,10 +43,12 @@ class NudoStarTVCrawler(Crawler):
soup, pages = await aio.peek_first(self.web_pager(scrape_item.url))
scrape_item.setup_as_album("")
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
async for soup in pages:
for new_item in self.iter_children(scrape_item, soup, Selector.CONTENT):
- tg.create_task(self.image(new_item))
+ tg.create_task(self._image_task(new_item))
+ await sleep()
@error_handling_wrapper
async def image(self, scrape_item: ScrapeItem) -> None:
@@ -57,3 +59,5 @@ class NudoStarTVCrawler(Crawler):
scrape_item.setup_as_album(self.create_title(css.select_text(soup, ".headline").partition("/")[0]))
src = self.parse_url(css.select(soup, Selector.IMAGE, "src"))
await self.direct_file(scrape_item, src)
+
+ _image_task = auto_task_id(image)
diff --git a/cyberdrop_dl/crawlers/patreon.py b/cyberdrop_dl/crawlers/patreon.py
index eed266479..daa48143d 100644
--- a/cyberdrop_dl/crawlers/patreon.py
+++ b/cyberdrop_dl/crawlers/patreon.py
@@ -9,7 +9,7 @@ from typing_extensions import ReadOnly
from cyberdrop_dl import aio
from cyberdrop_dl.clients.http import HTTPConfig
-from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedPaths
+from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedPaths, auto_task_id
from cyberdrop_dl.exceptions import MaxChildrenError, NoExtensionError, ScrapeError
from cyberdrop_dl.url_objects import AbsoluteHttpURL
from cyberdrop_dl.utils import css, extr_text, next_js, traversal
@@ -152,7 +152,7 @@ class PatreonCrawler(Crawler):
scrape_item.add_children()
await sleep()
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
for media in medias:
if media.id in seen_media_ids:
continue
@@ -244,16 +244,18 @@ class PatreonCrawler(Crawler):
async def campaign(self, scrape_item: ScrapeItem, campaign_id: str) -> None:
scrape_item.setup_as_profile("")
sleep = aio.periodic_sleep(10)
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
async for resp in self.api.posts(campaign_id):
included = _flatten_included(resp["included"])
for post in resp["data"]:
post = _flatten_post(post)
new_item = scrape_item.create_child(self.parse_url(post["url"]))
- tg.create_task(self._post(new_item, post, included))
+ tg.create_task(self._post_task(new_item, post, included))
scrape_item.add_children()
await sleep()
+ _post_task = auto_task_id(_post)
+
class LazyLogMedia:
def __init__(self, media: tuple[Media, ...]) -> None:
diff --git a/cyberdrop_dl/crawlers/picdrop.py b/cyberdrop_dl/crawlers/picdrop.py
index 5d13167c7..22bec2c93 100644
--- a/cyberdrop_dl/crawlers/picdrop.py
+++ b/cyberdrop_dl/crawlers/picdrop.py
@@ -54,7 +54,8 @@ class PicDropCrawler(Crawler):
else:
files = self.api.files(gallery.path)
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
async for file in files:
url = scrape_item.url.with_query(file=file.key)
if url in downloaded:
@@ -63,6 +64,7 @@ class PicDropCrawler(Crawler):
new_item = scrape_item.create_child(scrape_item.url.with_query(file=file.key))
tg.create_task(self._file(new_item, file, gallery.path))
scrape_item.add_children()
+ await sleep()
@error_handling_wrapper
async def _file(self, scrape_item: ScrapeItem, file: File, path: str) -> None:
diff --git a/cyberdrop_dl/crawlers/pixeldrain.py b/cyberdrop_dl/crawlers/pixeldrain.py
index 332ddba17..963514722 100644
--- a/cyberdrop_dl/crawlers/pixeldrain.py
+++ b/cyberdrop_dl/crawlers/pixeldrain.py
@@ -193,7 +193,7 @@ class PixelDrainCrawler(Crawler):
assert scrape_item.album_id
downloaded = await self.get_completed_by_album(scrape_item.album_id)
sleep = aio.periodic_sleep(10)
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
for file in files:
if self.api.download(file) in downloaded:
continue
@@ -224,7 +224,7 @@ class PixelDrainCrawler(Crawler):
sleep = aio.periodic_sleep(10)
subfolders: deque[str] = deque()
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
while True:
for node in fs.children:
if node.name == ".search_index.gz":
diff --git a/cyberdrop_dl/crawlers/pornpics.py b/cyberdrop_dl/crawlers/pornpics.py
index dd18ba1a3..fcdd250c1 100644
--- a/cyberdrop_dl/crawlers/pornpics.py
+++ b/cyberdrop_dl/crawlers/pornpics.py
@@ -7,7 +7,7 @@ import itertools
from typing import TYPE_CHECKING, ClassVar
from cyberdrop_dl import aio
-from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths, URLConfig
+from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths, URLConfig, auto_task_id
from cyberdrop_dl.url_objects import AbsoluteHttpURL
from cyberdrop_dl.utils import css, extr_text
from cyberdrop_dl.utils.errors import error_handling_wrapper
@@ -87,14 +87,14 @@ class PornPicsCrawler(Crawler):
(self.PRIMARY_URL / "search/srch.php").with_query(q=query.replace("-", " ")) if query else scrape_item.url
)
- async for galleries in self._collection_pager(search_url):
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
+ async for galleries in self._collection_pager(search_url):
for gallery_id, gallery_url in galleries:
- if self.was_scrapped_before(gallery_url):
- continue
new_item = scrape_item.create_child(gallery_url)
- tg.create_task(self.gallery(new_item, gallery_id))
+ tg.create_task(self._gallery_task(new_item, gallery_id))
scrape_item.add_children()
+ await sleep()
@error_handling_wrapper
async def gallery(self, scrape_item: ScrapeItem, gallery_id: str) -> None:
@@ -103,12 +103,16 @@ class PornPicsCrawler(Crawler):
title = self.create_title(name, gallery_id)
scrape_item.setup_as_album(title, album_id=gallery_id)
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
for url in self.iter_urls(soup, "div#main a.rel-link"):
if url in completed:
continue
tg.create_task(self.direct_file(scrape_item, url))
+ await sleep()
+
+ _gallery_task = auto_task_id(gallery)
@error_handling_wrapper
async def video_preview(self, scrape_item: ScrapeItem, video_id: str) -> None:
diff --git a/cyberdrop_dl/crawlers/spankbang.py b/cyberdrop_dl/crawlers/spankbang.py
index 5ff829f66..582ad42a4 100644
--- a/cyberdrop_dl/crawlers/spankbang.py
+++ b/cyberdrop_dl/crawlers/spankbang.py
@@ -153,9 +153,8 @@ class SpankBangCrawler(Crawler):
await self._iter_videos(scrape_item, soup)
async def _iter_videos(self, scrape_item: ScrapeItem, soup: BeautifulSoup) -> None:
- async with self.new_task_group() as tg:
- for new_item in self.iter_children(scrape_item, soup, Selector.VIDEOS):
- tg.create_task(self.run(new_item, check_referer=True))
+ for new_item in self.iter_children(scrape_item, soup, Selector.VIDEOS):
+ self.create_task(self.run(new_item, check_referer=True))
@aio.to_thread
diff --git a/cyberdrop_dl/crawlers/tiktok.py b/cyberdrop_dl/crawlers/tiktok.py
index 951657e61..f380aaa2f 100644
--- a/cyberdrop_dl/crawlers/tiktok.py
+++ b/cyberdrop_dl/crawlers/tiktok.py
@@ -153,7 +153,7 @@ class TikTokCrawler(Crawler):
async def profile(self, scrape_item: ScrapeItem, unique_id: str) -> None:
scrape_item.setup_as_profile("")
sleep = aio.periodic_sleep(10)
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
async for posts in self._profile_post_pager(unique_id):
for post in posts:
new_item = scrape_item.create_child(post.canonical_url)
@@ -220,7 +220,7 @@ class TikTokCrawler(Crawler):
_post_task = auto_task_id(error_handling_wrapper(_post))
async def _handle_images(self, scrape_item: ScrapeItem, post: Post) -> None:
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
for index, url in enumerate(post.images):
link = self.parse_url(url, trim=False)
img_url = post.canonical_url / str(index)
diff --git a/cyberdrop_dl/crawlers/turbovid.py b/cyberdrop_dl/crawlers/turbovid.py
index a8f9774dc..747fa6700 100644
--- a/cyberdrop_dl/crawlers/turbovid.py
+++ b/cyberdrop_dl/crawlers/turbovid.py
@@ -4,8 +4,9 @@ import asyncio
import dataclasses
from typing import TYPE_CHECKING, Any, ClassVar, final, override
+from cyberdrop_dl import aio
from cyberdrop_dl.crawlers import Registry
-from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedPaths
+from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedPaths, auto_task_id
from cyberdrop_dl.url_objects import AbsoluteHttpURL
from cyberdrop_dl.utils import TextExtractor, css, extr_text
from cyberdrop_dl.utils.errors import error_handling_wrapper
@@ -78,10 +79,10 @@ class TurboVidCrawler(Crawler):
title = self.create_title(album.name, album_id)
scrape_item.setup_as_album(title, album_id=album_id)
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
for file_id in album.files:
new_item = scrape_item.create_child(self.PRIMARY_URL / "d" / file_id)
- tg.create_task(self.video(new_item, file_id))
+ tg.create_task(self._video_task(new_item, file_id))
scrape_item.add_children()
@error_handling_wrapper
@@ -99,6 +100,8 @@ class TurboVidCrawler(Crawler):
filename, ext = self.get_filename_and_ext(name)
await self.handle_file(dl_link, scrape_item, name, ext, custom_filename=filename)
+ _video_task = auto_task_id(video)
+
class TurboAPI(API):
async def metadata(self, file_id: str) -> tuple[str, str]:
diff --git a/cyberdrop_dl/crawlers/upfile.py b/cyberdrop_dl/crawlers/upfile.py
index add434ff0..f2d5b0af2 100644
--- a/cyberdrop_dl/crawlers/upfile.py
+++ b/cyberdrop_dl/crawlers/upfile.py
@@ -105,7 +105,7 @@ class UpFileCrawler(Crawler):
async def _walk_nodes(self, scrape_item: ScrapeItem, folder: Folder, path: str) -> None:
subfolders: deque[str] = deque()
sleep = aio.periodic_sleep(10)
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
while True:
nodes = folder.items
leafs = tuple(node.name for node in folder.breadcrumb[1:])
diff --git a/cyberdrop_dl/crawlers/vk/vk.py b/cyberdrop_dl/crawlers/vk/vk.py
index b9f85ed95..3203a8085 100644
--- a/cyberdrop_dl/crawlers/vk/vk.py
+++ b/cyberdrop_dl/crawlers/vk/vk.py
@@ -190,7 +190,7 @@ class VKVideoCrawler(VKBaseCrawler, wiki_site="VKVideo"):
async def _iter_videos(self, scrape_item: ScrapeItem, videos: AsyncIterable[Video]) -> None:
sleep = aio.periodic_sleep(10)
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
async for video in videos:
url = self.PRIMARY_URL / video.web_path
if video.access_key:
@@ -410,18 +410,20 @@ class VKCrawler(VKBaseCrawler, wiki_site="VK"):
return
scrape_item.setup_as_profile(self.create_title(owner.full_name))
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
async for post in self.api.get_wall(owner_id, filter_=self.config.crawlers.vk.wall_filter):
url = self.PRIMARY_URL / f"wall{post.owner_id}_{post.id}"
tg.create_task(self._post_task(scrape_item.create_child(url), post))
scrape_item.add_children()
+ await sleep()
@error_handling_wrapper
async def _post(self, scrape_item: ScrapeItem, post: Post) -> None: # noqa: C901
title = self.create_separate_post_title(None, str(post.slug), post.date)
scrape_item.setup_as_post(title)
- async with self.new_task_group() as tg:
- sleep = aio.periodic_sleep(10)
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
tg.create_task(self.write_metadata(scrape_item, f"wall{post.owner_id}_{post.id}", post))
for attach in post.attachments:
type_ = attach["type"]
@@ -531,7 +533,7 @@ class VKCrawler(VKBaseCrawler, wiki_site="VK"):
title = self.create_title(f"{play.title or play.slug} [playlist]", play.slug)
scrape_item.append_folders(title)
- async with self.new_task_group() as tg:
+ async with aio.non_cancelling_taskgroup() as tg:
tg.create_task(self.write_metadata(scrape_item, play.web_path, play))
if play.thumb:
tg.create_task(self.direct_file(scrape_item, play.thumb.best()))
@@ -568,11 +570,13 @@ class VKCrawler(VKBaseCrawler, wiki_site="VK"):
)
async def _iter_photos_legacy(self, scrape_item: ScrapeItem, list_id: str) -> None:
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
async for photo in self.api.legacy.get_photos(list_id):
new_item = scrape_item.create_child(self.PRIMARY_URL / photo.web_path)
tg.create_task(self._photo_task(new_item, photo))
scrape_item.add_children()
+ await sleep()
_file_task = auto_task_id(_file)
_post_task = auto_task_id(_post)
diff --git a/cyberdrop_dl/crawlers/xenforo/xenforo.py b/cyberdrop_dl/crawlers/xenforo/xenforo.py
index e2d17da87..320eb06d0 100644
--- a/cyberdrop_dl/crawlers/xenforo/xenforo.py
+++ b/cyberdrop_dl/crawlers/xenforo/xenforo.py
@@ -396,7 +396,8 @@ class XenforoCrawler(Crawler, is_abc=True):
scrape_item.append_folders(post_title)
stats: dict[str, int] = {}
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
for scraper in (
self._attachments,
self._images,
@@ -410,9 +411,10 @@ class XenforoCrawler(Crawler, is_abc=True):
stats[scraper_name] = stats.get(scraper_name, 0) + 1
tg.create_task(self.process_child(scrape_item, url, embeds="embeds" in scraper_name))
scrape_item.add_children()
+ await sleep()
if stats:
- self.log.info(f"post #{post.id} {stats = }")
+ self.log.info("post #%s stats = %s", post.id, stats)
@classmethod
def _external_links(cls, post: ForumPost) -> Iterable[str]:
diff --git a/cyberdrop_dl/crawlers/xhamster.py b/cyberdrop_dl/crawlers/xhamster.py
index 61b90429f..35774adb7 100644
--- a/cyberdrop_dl/crawlers/xhamster.py
+++ b/cyberdrop_dl/crawlers/xhamster.py
@@ -171,13 +171,15 @@ class XhamsterCrawler(Crawler):
for img in Gallery.parse(initials).images:
yield img
- async with self.new_task_group() as tg:
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
async for index, img in aio.aenumerate(images(), start=1):
if img.src in downloaded:
continue
tg.create_task(self._image(scrape_item.create_child(img.url), img, index))
scrape_item.add_children()
+ await sleep()
@error_handling_wrapper
async def _image(self, scrape_item: ScrapeItem, img: Image, index: int) -> None:
diff --git a/cyberdrop_dl/crawlers/yurivan.py b/cyberdrop_dl/crawlers/yurivan.py
index 3f936c437..a21f959c5 100644
--- a/cyberdrop_dl/crawlers/yurivan.py
+++ b/cyberdrop_dl/crawlers/yurivan.py
@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, Any, ClassVar
from pydantic import dataclasses
+from cyberdrop_dl import aio
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
from cyberdrop_dl.exceptions import ScrapeError
from cyberdrop_dl.url_objects import AbsoluteHttpURL
@@ -80,10 +81,13 @@ class YuriVanCrawler(Crawler):
chapter = story.chapters[chapter_idx]
scrape_item.append_folders(self.create_title(chapter.title))
- async with self.new_task_group() as tg:
+
+ sleep = aio.periodic_sleep(10)
+ async with aio.non_cancelling_taskgroup() as tg:
for page in chapter.pages:
tg.create_task(self.direct_file(scrape_item, page.url))
scrape_item.add_children()
+ await sleep()
@dataclasses.dataclass(slots=True)