Skip to content

Bulk asynchronous downloader for multiple file hosts

Rate limit jpg.church to 19 r/s.

Jules-WinnfieldX7baf8d1baac5
diff --git a/LICENSE-THIRD-PARTY b/LICENSE-THIRD-PARTY
index edfe46c32..32463f4de 100644
--- a/LICENSE-THIRD-PARTY
+++ b/LICENSE-THIRD-PARTY
@@ -1 +1,2 @@
-Forked downloaders.py from https://github.com/alexdotis/Chibisafe-Sharex-Scraper/tree/feadd9c14e3307d07b174abbda0c6f40b608a0a4
\ No newline at end of file
+Forked downloaders.py from https://github.com/alexdotis/Chibisafe-Sharex-Scraper/tree/feadd9c14e3307d07b174abbda0c6f40b608a0a4
+Forked AsyncRateLimiter class from https://github.com/top-gg/python-sdk/blob/40d0156ef7e824c9ab4b6cb79142ed9539e29ce2/topgg/ratelimiter.py
\ No newline at end of file
diff --git a/cyberdrop_dl/__init__.py b/cyberdrop_dl/__init__.py
index 5d6a3ee99..736365772 100644
--- a/cyberdrop_dl/__init__.py
+++ b/cyberdrop_dl/__init__.py
@@ -1 +1 @@
-__version__ = "2.21.3"
+__version__ = "2.21.4"
diff --git a/cyberdrop_dl/utils/data_classes.py b/cyberdrop_dl/utils/data_classes.py
index 9fcf7c346..be29dba0e 100644
--- a/cyberdrop_dl/utils/data_classes.py
+++ b/cyberdrop_dl/utils/data_classes.py
@@ -1,6 +1,10 @@
import asyncio
+import collections
+from collections import defaultdict
from dataclasses import dataclass
-from typing import Dict, List, Optional, Tuple
+from datetime import datetime
+from types import TracebackType
+from typing import Dict, List, Optional, Tuple, Callable, Awaitable, Any, Type
from random import gauss
import aiohttp
@@ -140,3 +144,60 @@ class AuthData:
"""Class for keeping username and password"""
username: str
password: str
+
+
+class AsyncRateLimiter:
+ """
+ Provides rate limiting for an operation with a configurable number of requests for a time period.
+ """
+
+ __lock: asyncio.Lock
+ callback: Optional[Callable[[float], Awaitable[Any]]]
+ max_calls: int
+ period: float
+ calls: collections.deque
+
+ def __init__(
+ self,
+ max_calls: int,
+ period: float = 1.0,
+ callback: Optional[Callable[[float], Awaitable[Any]]] = None,
+ ):
+ if period <= 0:
+ raise ValueError("Rate limiting period should be > 0")
+ if max_calls <= 0:
+ raise ValueError("Rate limiting number of calls should be > 0")
+ self.calls = collections.deque()
+
+ self.period = period
+ self.max_calls = max_calls
+ self.callback = callback
+ self.__lock = asyncio.Lock()
+
+ async def __aenter__(self) -> "AsyncRateLimiter":
+ async with self.__lock:
+ if len(self.calls) >= self.max_calls:
+ until = datetime.utcnow().timestamp() + self.period - self._timespan
+ if self.callback:
+ asyncio.ensure_future(self.callback(until))
+ sleep_time = until - datetime.utcnow().timestamp()
+ if sleep_time > 0:
+ await asyncio.sleep(sleep_time)
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: Type[BaseException],
+ exc_val: BaseException,
+ exc_tb: TracebackType,
+ ) -> None:
+ async with self.__lock:
+ # Store the last operation timestamp.
+ self.calls.append(datetime.utcnow().timestamp())
+
+ while self._timespan >= self.period:
+ self.calls.popleft()
+
+ @property
+ def _timespan(self) -> float:
+ return self.calls[-1] - self.calls[0]
diff --git a/cyberdrop_dl/utils/scraper_helper.py b/cyberdrop_dl/utils/scraper_helper.py
index b8b770a90..b9c45656a 100644
--- a/cyberdrop_dl/utils/scraper_helper.py
+++ b/cyberdrop_dl/utils/scraper_helper.py
@@ -15,7 +15,7 @@ from .crawlers.Redgifs_Spider import RedGifsCrawler
from .crawlers.ShareX_Spider import ShareXCrawler
from .crawlers.Thotsbay_Spider import ThotsbayCrawler
from .base_functions import log
-from .data_classes import CascadeItem
+from .data_classes import CascadeItem, AsyncRateLimiter
class ScrapeMapper():
@@ -39,7 +39,6 @@ class ScrapeMapper():
self.thotsbay_crawler = None
self.semaphore = asyncio.Semaphore(1)
- self.sharex_semaphore = asyncio.Semaphore(4)
self.mapping = {"anonfiles.com": self.Anonfiles, "bunkr.is": self.Chibisafe,
"bunkr.to": self.Chibisafe, "coomer.party": self.coomer,
"cyberdrop.cc": self.Chibisafe, "cyberdrop.me": self.Chibisafe,
@@ -138,7 +137,10 @@ class ScrapeMapper():
async def ShareX(self, url: URL, title=None):
if not self.sharex_crawler:
self.sharex_crawler = ShareXCrawler(include_id=self.include_id)
- async with self.sharex_semaphore:
+ if "jpg.church" in url.host:
+ async with AsyncRateLimiter(19):
+ domain_obj = await self.sharex_crawler.fetch(self.session, url)
+ else:
domain_obj = await self.sharex_crawler.fetch(self.session, url)
if title:
await domain_obj.append_title(title)