Skip to content

Bulk asynchronous downloader for multiple file hosts

Introduce throttle func for bunkr instead of slave class.

Jules-WinnfieldXa7b0ad244037
diff --git a/main.py b/main.py
index b5f007c1c..755754f0a 100644
--- a/main.py
+++ b/main.py
@@ -18,7 +18,6 @@ import os
import re
import warnings
import readchar
-import multiprocessing
logging.basicConfig(level=logging.DEBUG, filename='logs.log',
format='%(asctime)s:%(levelname)s:%(module)s:%(filename)s:%(lineno)d:%(message)s',
@@ -26,7 +25,6 @@ logging.basicConfig(level=logging.DEBUG, filename='logs.log',
warnings.filterwarnings("ignore", category=DeprecationWarning)
DOWNLOAD_FOLDER = settings.download_folder
-CPU_COUNT = settings.threads if settings.threads != 0 else multiprocessing.cpu_count()
def log(text, style):
@@ -75,7 +73,7 @@ async def main():
logging.error(f'ValueError No links: {content_object}')
raise ValueError('No links found, check the URL.txt\nIf the link works in your web browser, please open an issue ticket with me.')
clear()
- downloaders = get_downloaders(content_object, cookies=cookies, folder=Path(DOWNLOAD_FOLDER), max_workers=CPU_COUNT)
+ downloaders = get_downloaders(content_object, cookies=cookies, folder=Path(DOWNLOAD_FOLDER))
for downloader in downloaders:
await downloader.download_content()
@@ -85,4 +83,4 @@ async def main():
if __name__ == '__main__':
- asyncio.get_event_loop().run_until_complete(main())
+ asyncio.get_event_loop().run_until_complete(main())
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
index 1dd31a6ad..eab9c02e9 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -9,4 +9,6 @@ readchar~=3.0.4
certifi~=2021.10.8
selenium~=4.1.0
chromedriver_autoinstaller~=0.3.1
-nest-asyncio~=1.5.4
\ No newline at end of file
+nest-asyncio~=1.5.4
+asyncio~=3.4.3
+yarl~=1.7.2
\ No newline at end of file
diff --git a/utils/downloaders.py b/utils/downloaders.py
index 274088983..b6cec1f99 100644
--- a/utils/downloaders.py
+++ b/utils/downloaders.py
@@ -1,5 +1,7 @@
import asyncio
import http
+import time
+import typing
from functools import wraps
from pathlib import Path
from typing import Any, Callable, Iterable, List, Optional, Type, TypeVar, Union, cast, Dict
@@ -17,6 +19,8 @@ import ssl
import certifi
from http.cookies import SimpleCookie
import settings
+import multiprocessing
+import yarl
asyncio.get_event_loop()
@@ -25,7 +29,6 @@ logger = logging.getLogger(__name__)
T = TypeVar("T")
T_Func = TypeVar("T_Func", bound=Callable)
-
MAX_FILENAME_LENGTH = 100
FILE_FORMATS = {
'Images': {
@@ -81,6 +84,37 @@ def retry(
return inner
+async def throttle(self, url: yarl.URL) -> None:
+ host = url.host
+ if host is None:
+ return
+
+ key: typing.Optional[str] = None
+ while True:
+ delay = self.delay.get(host)
+ if delay is None:
+ return
+
+ if key is None:
+ key = 'throttle:{}'.format(host)
+
+ now = time.time()
+ last = self.state.get(key)
+ if not isinstance(last, float):
+ last = 0.0
+ elapsed = now - last
+
+ if elapsed >= delay:
+ self.state[key] = now
+ return
+
+ remaining = delay - elapsed
+
+ # log_string = '\nDelaying request to %s for %.2f seconds.' % (host, remaining)
+ # log(log_string, Fore.WHITE)
+ await asyncio.sleep(remaining)
+
+
class Downloader:
def __init__(self, links: List[List[str]], morsels, folder: Path, title: str, max_workers: int):
self.links = links
@@ -89,6 +123,21 @@ class Downloader:
self.title = title
self.max_workers = max_workers
self._semaphore = asyncio.Semaphore(max_workers)
+ self.delay = {'media-files.bunkr.is': 2}
+ self.state = {}
+
+ @staticmethod
+ def bunkr_parse(url: str) -> str:
+ """Fix the URL for bunkr.is and construct the headers."""
+ extension = '.' + url.split('.')[-1]
+ if extension.lower() in FILE_FORMATS['Videos']:
+ changed_url = url.replace('cdn.bunkr', 'media-files.bunkr').split('/')
+ changed_url = ''.join(map(lambda x: urljoin('/', x), changed_url))
+ return changed_url
+ if extension.lower() in FILE_FORMATS['Images']:
+ changed_url = url.replace('i.bunkr', 'cdn.bunkr')
+ return changed_url
+ return url
"""Changed from aiohttp exceptions caught to FailureException to allow for partial downloads."""
@retry(attempts=settings.download_attempts, timeout=4, exceptions=FailureException)
@@ -106,7 +155,10 @@ class Downloader:
resume_point = 0
downloaded = bytearray()
ssl_context = ssl.create_default_context(cafile=certifi.where())
- user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
+ user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36'
+
+ if 'bunkr' in url:
+ url = self.bunkr_parse(url)
headers = {'Referer': referal, 'user-agent': user_agent}
@@ -116,6 +168,7 @@ class Downloader:
try:
async with self._semaphore:
+ await throttle(self, yarl.URL(url))
resp = await session.get(url, headers=headers, ssl=ssl_context, raise_for_status=True)
total = int(resp.headers.get('Content-Length', 0)) + resume_point
with tqdm(
@@ -166,6 +219,7 @@ class Downloader:
if len(filename) > MAX_FILENAME_LENGTH:
fileext = filename.split('.')[-1]
filename = filename[:MAX_FILENAME_LENGTH]+'.'+fileext
+
if (self.folder / self.title / filename).exists():
logger.debug(str(self.folder / self.title / filename) + " Already Exists")
else:
@@ -173,7 +227,7 @@ class Downloader:
try:
await self.download_file(url, referal=referal, filename=filename, session=session, headers=headers, show_progress=show_progress)
await self.rename_file(filename)
- except:
+ except Exception as e:
log(f"\nSkipping {filename}: likely exceeded download attempts\nRe-run program after exit to continue download.", Fore.WHITE)
async def download_all(
@@ -201,55 +255,6 @@ class Downloader:
await self.download_all(self.links, session, headers=headers, show_progress=show_progress)
-class LimitDownloader(Downloader):
- @staticmethod
- def bunkr_parse(url: str) -> str:
- """Fix the URL for bunkr.is and construct the headers."""
- extension = '.' + url.split('.')[-1]
- if extension.lower() in FILE_FORMATS['Videos']:
- changed_url = url.replace('cdn.bunkr', 'media-files.bunkr').split('/')
- changed_url = ''.join(map(lambda x: urljoin('/', x), changed_url))
- return changed_url
- if extension.lower() in FILE_FORMATS['Images']:
- changed_url = url.replace('i.bunkr', 'cdn.bunkr')
- return changed_url
- return url
-
- @staticmethod
- def pairwise_skipping(it: List[T], chunk_size: int):
- """Iterate over tuples of the iterable of size `chunk_size` at a time."""
- split_it = [it[i:i+chunk_size] for i in range(0, len(it), chunk_size)]
- return map(tuple, split_it)
-
- async def download_file(
- self,
- url: str,
- referal: str,
- filename: str,
- session: aiohttp.ClientSession,
- headers: Optional[CaseInsensitiveDict] = None,
- show_progress: bool = True
- ):
- if 'bunkr' in url:
- url = self.bunkr_parse(url)
- await super().download_file(url, referal=referal, filename=filename, session=session, headers=headers, show_progress=show_progress)
-
- async def download_all(
- self,
- links: Iterable[List[str]],
- session: aiohttp.ClientSession,
- headers: Optional[CaseInsensitiveDict] = None,
- show_progress: bool = True
- ) -> None:
- """Download the data from all given links and store them into corresponding files.
- We override this method to only make requests to 2 links at a time,
- since bunkr.is can't handle more traffic and causes errors.
- """
- chunked_links = self.pairwise_skipping(self.links, chunk_size=2)
- for links in chunked_links:
- await super().download_all(links, session, headers=headers, show_progress=show_progress)
-
-
def simple_cookies(cookies):
morsels = {}
for cookie in cookies:
@@ -265,37 +270,22 @@ def simple_cookies(cookies):
return morsels
-def get_downloaders(urls: Dict[str, Dict[str, List[str]]], cookies: Iterable[str], folder: Path, max_workers: int) -> List[Downloader]:
+def get_downloaders(urls: Dict[str, Dict[str, List[str]]], cookies: Iterable[str], folder: Path) -> List[Downloader]:
"""Get a list of downloaders for each supported type of URLs.
We shouldn't just assume that each URL will have the same netloc as
the first one, so we need to classify them one by one, sort them to
corresponding netloc URLs and create downloaders separately for individual
netloc URLs they support.
"""
- mapping = {
- 'cyberdrop.me': Downloader,
- 'cyberdrop.cc': Downloader,
- 'cyberdrop.to': Downloader,
- 'cyberdrop.nl': Downloader,
- 'bunkr.is': LimitDownloader,
- 'bunkr.to': LimitDownloader,
- 'pixl.is': Downloader,
- 'rpcs0112.b-cdn.net': Downloader,
- 'putme.ga': Downloader,
- 'putmega.com': Downloader,
- 'jpg.church': Downloader,
- 'erome.com': Downloader,
- 'gofile.io': Downloader
- }
downloaders = []
morsels = simple_cookies(cookies)
for domain, url_object in urls.items():
- if domain not in mapping:
- logging.error('Invalid domain '+domain)
- raise ValueError('Invalid domain '+domain)
+ max_workers = settings.threads if settings.threads != 0 else multiprocessing.cpu_count()
+ if 'bunkr' in domain:
+ max_workers = 2 if (max_workers > 2) else max_workers
for title, urls in url_object.items():
- downloader = mapping[domain](urls, morsels=morsels, title=title, folder=folder, max_workers=max_workers)
+ downloader = Downloader(urls, morsels=morsels, title=title, folder=folder, max_workers=max_workers)
downloaders.append(downloader)
return downloaders
\ No newline at end of file