Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
Work on download process
Jules-WinnfieldX77048498edcd
diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.pyindex dc9e01861..f977bcf04 100644--- a/cyberdrop_dl/clients/download_client.py+++ b/cyberdrop_dl/clients/download_client.py@@ -2,15 +2,14 @@ from __future__ import annotationsimport asyncioimport copy-import functools-from enum import IntEnumfrom http import HTTPStatus+from functools import wraps, partialfrom typing import TYPE_CHECKINGimport aiofilesimport aiohttp-from aiolimiter import AsyncLimiter-from yarl import URL+from aiohttp import ClientSession+from rich.progress import TaskIDfrom cyberdrop_dl.clients.errors import DownloadFailurefrom cyberdrop_dl.utils.utilities import FILE_FORMATS@@ -19,21 +18,32 @@ if TYPE_CHECKING:from pathlib import Pathfrom typing import Dict, Callable, Coroutine, Any- from cyberdrop_dl.managers.client_manager import ClientManager+ from cyberdrop_dl.managers.client_manager import ClientManager, CustomHTTPStatusfrom cyberdrop_dl.managers.manager import Managerfrom cyberdrop_dl.utils.dataclasses.url_objects import MediaItem-class CustomHTTPStatus(IntEnum):- WEB_SERVER_IS_DOWN = 521- IM_A_TEAPOT = 418--async def is_4xx_client_error(status_code: int) -> bool:"""Checks whether the HTTP status code is 4xx client error"""return HTTPStatus.BAD_REQUEST <= status_code < HTTPStatus.INTERNAL_SERVER_ERROR+def limiter(func):+ """Wrapper handles limits for download session"""+ @wraps(func)+ async def wrapper(self, *args, **kwargs):+ domain_limiter = await self.client_manager.get_rate_limiter(args[0])+ async with self.client_manager.session_limit:+ await self.global_limiter.aquire()+ await domain_limiter.aquire()++ async with aiohttp.ClientSession(headers=self.headers, raise_for_status=False,+ cookie_jar=self.client_manager.cookies, timeout=self.timeouts) as client:+ kwargs['client_session'] = client+ return await func(self, *args, **kwargs)+ return wrapper++class DownloadClient:"""AIOHTTP operations for downloading"""def __init__(self, client_manager: ClientManager):@@ -41,70 +51,60 @@ class DownloadClient:self.headers = {"user-agent": client_manager.user_agent}self.timeouts = aiohttp.ClientTimeout(total=client_manager.read_timeout + client_manager.connection_timeout,connect=client_manager.connection_timeout)- self.client_session = aiohttp.ClientSession(headers=self.headers, raise_for_status=True,- cookie_jar=client_manager.cookies, timeout=self.timeouts)- self.throttle_times: Dict[str, float] = {"user_agent": client_manager.user_agent}- self.bunkr_maintenance = [URL("https://bnkr.b-cdn.net/maintenance-vid.mp4"),- URL("https://bnkr.b-cdn.net/maintenance.mp4")]+ self.global_limiter = self.client_manager.global_rate_limiter- async def get_filesize(self, media_item: MediaItem) -> int:+ @limiter+ async def get_filesize(self, media_item: MediaItem, client_session: ClientSession) -> int:"""Returns the file size of the media item"""headers = copy.deepcopy(self.headers)headers['Referer'] = media_item.referer- async with self.client_session.get(media_item.url, headers=headers, ssl=self.client_manager.ssl_context,- raise_for_status=False) as resp:- if resp.status > 206:- if "Server" in resp.headers:- if resp.headers["Server"] == "ddos-guard":- raise DownloadFailure(status=CustomHTTPStatus.IM_A_TEAPOT,- message="DDoS-Guard detected, unable to download")- raise DownloadFailure(status=resp.status, message=f"Unexpected status code {resp.status} from {media_item.url}")+ async with client_session.get(media_item.url, headers=headers, ssl=self.client_manager.ssl_context,+ proxy=self.client_manager.proxy) as resp:+ await self.client_manager.check_http_status(resp.status, resp.headers, resp.url)return int(resp.headers.get('Content-Length', '0'))"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""- async def _download(self, media_item: MediaItem, headers_inc: Dict,- save_content: Callable[[aiohttp.StreamReader], Coroutine[Any, Any, None]], file: Path) -> None:+ @limiter+ async def _download(self, domain: str, manager: Manager, media_item: MediaItem, headers_inc: Dict,+ save_content: Callable[[aiohttp.StreamReader], Coroutine[Any, Any, None]], file: Path,+ file_task: TaskID, client_session: ClientSession) -> None:headers = copy.deepcopy(self.headers)headers['Referer'] = media_item.refererheaders.update(headers_inc)- async with self.client_session.get(media_item.url, headers=headers, ssl=self.client_manager.ssl_context,- raise_for_status=True, proxy=self.client_manager.proxy) as resp:+ async with client_session.get(media_item.url, headers=headers, ssl=self.client_manager.ssl_context,+ proxy=self.client_manager.proxy) as resp:+ await self.client_manager.check_http_status(resp.status, resp.headers, resp.url, download=True)content_type = resp.headers.get('Content-Type')- if not content_type:- raise DownloadFailure(status=CustomHTTPStatus.IM_A_TEAPOT, message="No content-type in response header")- if resp.url in self.bunkr_maintenance:- raise DownloadFailure(status=HTTPStatus.SERVICE_UNAVAILABLE, message="Bunkr under maintenance")- if "imgur.com/removed" in str(resp.url):- raise DownloadFailure(status=HTTPStatus.NOT_FOUND, message="Imgur image has been removed")-ext = Path(media_item.filename).suffix.lower()if any(s in content_type.lower() for s in ('html', 'text')) and ext not in FILE_FORMATS['Text']:raise DownloadFailure(status=CustomHTTPStatus.IM_A_TEAPOT, message="Unexpectedly got text as response")if resp.status != HTTPStatus.PARTIAL_CONTENT:if file.is_file():+ await manager.progress_manager.file_progress.advance_file(file_task, -file.stat().st_size)file.unlink()await save_content(resp.content)- async def _append_content(self, file: Path, content: aiohttp.StreamReader, update_progress: functools.partial) -> None:+ async def _append_content(self, file: Path, content: aiohttp.StreamReader,+ update_progress: partial) -> None:file.parent.mkdir(parents=True, exist_ok=True)async with aiofiles.open(file, mode='ab') as f:async for chunk, _ in content.iter_chunks():await asyncio.sleep(0)await f.write(chunk)- if isinstance(update_progress, functools.partial):- await update_progress(len(chunk))- else:- update_progress(len(chunk))-- async def download_file(self, manager: Manager, media_item: MediaItem, partial_file: Path, headers: Dict) -> None:+ await update_progress(len(chunk))+ async def download_file(self, manager: Manager, domain: str, media_item: MediaItem, partial_file: Path,+ headers: Dict, file_task: TaskID) -> None:+ """Downloads a file"""async def save_content(content: aiohttp.StreamReader) -> None:- await self._append_content(partial_file, content, functools.partial())+ await self._append_content(partial_file, content,+ partial(manager.progress_manager.file_progress.advance_file,+ file_task))- await self._download(media_item, headers, save_content, partial_file)+ await self._download(self, domain, manager, media_item, headers, save_content, partial_file, file_task)diff --git a/cyberdrop_dl/clients/errors.py b/cyberdrop_dl/clients/errors.pyindex 18a730641..fcb980dfa 100644--- a/cyberdrop_dl/clients/errors.py+++ b/cyberdrop_dl/clients/errors.py@@ -14,7 +14,7 @@ class NoExtensionFailure(Exception):class DownloadFailure(Exception):- """This error will be thrown when a download fails"""+ """This error will be thrown when a request fails"""def __init__(self, status: int, message: str = "Something went wrong"):self.status = statusself.message = messagediff --git a/cyberdrop_dl/clients/scraper_client.py b/cyberdrop_dl/clients/scraper_client.pyindex de81240f2..c9ce8351e 100644--- a/cyberdrop_dl/clients/scraper_client.py+++ b/cyberdrop_dl/clients/scraper_client.py@@ -1,9 +1,10 @@from __future__ import annotationsimport aiohttp+from functools import wrapsfrom typing import TYPE_CHECKING-from aiolimiter import AsyncLimiter+from aiohttp import ClientSessionfrom bs4 import BeautifulSoupfrom cyberdrop_dl.clients.errors import InvalidContentTypeFailure@@ -14,14 +15,19 @@ if TYPE_CHECKING:from cyberdrop_dl.managers.client_manager import ClientManager-def scrape_limit(func):+def limiter(func):"""Wrapper handles limits for scrape session"""-+ @wraps(func)async def wrapper(self, *args, **kwargs):- async with self.client.simultaneous_session_limit:- async with self.rate_limiter:+ domain_limiter = await self.client_manager.get_rate_limiter(args[0])+ async with self.client_manager.session_limit:+ await self.global_limiter.aquire()+ await domain_limiter.aquire()++ async with aiohttp.ClientSession(headers=self.headers, raise_for_status=False,+ cookie_jar=self.client_manager.cookies, timeout=self.timeouts) as client:+ kwargs['client_session'] = clientreturn await func(self, *args, **kwargs)-return wrapper@@ -29,16 +35,17 @@ class ScraperClient:"""AIOHTTP operations for scraping"""def __init__(self, client_manager: ClientManager) -> None:self.client_manager = client_manager- self.rate_limiter = AsyncLimiter(client_manager.rate_limit, 1)self.headers = {"user-agent": client_manager.user_agent}self.timeouts = aiohttp.ClientTimeout(total=client_manager.connection_timeout + 60,connect=client_manager.connection_timeout)- self.client_session = aiohttp.ClientSession(headers=self.headers, raise_for_status=True,- cookie_jar=client_manager.cookies, timeout=self.timeouts)-- @scrape_limit- async def get_BS4(self, url: URL) -> BeautifulSoup:- async with self.client_session.get(url, ssl=self.client_manager.ssl_context) as response:+ self.global_limiter = self.client_manager.global_rate_limiter++ @limiter+ async def get_BS4(self, domain: str, url: URL, client_session: ClientSession) -> BeautifulSoup:+ """Returns a BeautifulSoup object from the given URL"""+ async with client_session.get(url, headers=self.headers, ssl=self.client_manager.ssl_context,+ proxy=self.client_manager.proxy) as response:+ await self.client_manager.check_http_status(response.status, response.headers, response.url)content_type = response.headers.get('Content-Type')assert content_type is not Noneif not any(s in content_type.lower() for s in ("html", "text")):diff --git a/cyberdrop_dl/downloader/downloader.py b/cyberdrop_dl/downloader/downloader.pyindex 82466af1f..2831cdf87 100644--- a/cyberdrop_dl/downloader/downloader.py+++ b/cyberdrop_dl/downloader/downloader.py@@ -42,15 +42,15 @@ class FileLock:def __init__(self):self.locked_files = []- async def check_lock(self, filename: str):+ async def check_lock(self, filename: str) -> bool:"""Checks if the file is locked"""return filename in self.locked_files- async def add_lock(self, filename: str):+ async def add_lock(self, filename: str) -> None:"""Adds a lock to the file"""self.locked_files.append(filename)- async def remove_lock(self, filename: str):+ async def remove_lock(self, filename: str) -> None:"""Removes a lock from the file"""self.locked_files.remove(filename)@@ -69,12 +69,14 @@ class Downloader:self.current_attempt_filesize = {}- async def startup(self):+ async def startup(self) -> None:+ """Starts the downloader"""self.download_queue = await self.manager.queue_manager.get_download_queue(self.domain, 0)self.client = await self.manager.client_manager.get_downloader_session(self.domain)await self.set_additional_headers()- async def run_loop(self):+ async def run_loop(self) -> None:+ """Runs the download loop"""while True:media_item: MediaItem = await self.download_queue.get()self.complete = False@@ -88,7 +90,7 @@ class Downloader:"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""- async def check_file_can_download(self, media_item: MediaItem):+ async def check_file_can_download(self, media_item: MediaItem) -> bool:"""Checks if the file can be downloaded"""if not await self.manager.download_manager.check_free_space():return False@@ -100,6 +102,7 @@ class Downloader:return Trueasync def check_filesize_limits(self, media: MediaItem) -> bool:+ """Checks if the file size is within the limits"""max_video_filesize = self.manager.config_manager.settings_data['File_Size_Limits']['maximum_video_size']min_video_filesize = self.manager.config_manager.settings_data['File_Size_Limits']['minimum_video_size']max_image_filesize = self.manager.config_manager.settings_data['File_Size_Limits']['maximum_image_size']@@ -133,7 +136,7 @@ class Downloader:return Falsereturn True- async def get_download_dir(self, media_item: MediaItem):+ async def get_download_dir(self, media_item: MediaItem) -> Path:"""Returns the download directory for the media item"""download_folder = media_item.download_folderif self.manager.config_manager.settings_data['Download_Options']['block_download_sub_folders']:@@ -141,20 +144,21 @@ class Downloader:download_folder = download_folder.parentreturn download_folder- async def mark_incomplete(self, media_item: MediaItem):+ async def mark_incomplete(self, media_item: MediaItem) -> None:"""Marks the media item as incomplete in the database"""await self.manager.db_manager.history_table.insert_uncompleted(self.domain, media_item)- async def mark_completed(self, media_item: MediaItem):+ async def mark_completed(self, media_item: MediaItem) -> None:"""Marks the media item as completed in the database"""await self.manager.db_manager.history_table.mark_complete(self.domain, media_item)- async def set_additional_headers(self):+ async def set_additional_headers(self) -> None:"""Sets additional headers for the download session"""if self.manager.config_manager.authentication_data['PixelDrain']['pixeldrain_api_key']:self.client.headers["Authorization"] = await self.manager.download_manager.basic_auth("Cyberdrop-DL", self.manager.config_manager.authentication_data['PixelDrain']['pixeldrain_api_key'])- async def get_final_file_info(self, complete_file: Path, partial_file: Path, media_item: MediaItem) -> tuple[Path, Path, bool]:+ async def get_final_file_info(self, complete_file: Path, partial_file: Path,+ media_item: MediaItem) -> tuple[Path, Path, bool]:"""Complicated checker for if a file already exists, and was already downloaded"""expected_size = media_item.filesize if isinstance(media_item.filesize, int) else Noneproceed = True@@ -197,6 +201,7 @@ class Downloader:return complete_file, partial_file, proceedasync def iterate_filename(self, complete_file: Path, media_item: MediaItem) -> Tuple[Path, Path]:+ """Iterates the filename until it is unique"""partial_file = Nonefor iteration in itertools.count(1):filename = f"{complete_file.stem} ({iteration}){media_item.ext}"@@ -211,7 +216,7 @@ class Downloader:"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""@retry- async def download(self, media_item: MediaItem, url_path: str):+ async def download(self, media_item: MediaItem) -> None:"""Downloads the media item"""if media_item.current_attempt == self.manager.config_manager.global_settings_data['Rate_Limiting_Options']['download_attempts']:return@@ -243,7 +248,10 @@ class Downloader:resume_point = partial_file.stat().st_size if partial_file.exists() else 0headers = {'Range': f'bytes={resume_point}-'}- await self.client.download_file(self.manager, media_item, complete_file, partial_file, headers)+ file_task = await self.manager.progress_manager.file_progress.add_task(media_item.filename, media_item.filesize)+ await self.manager.progress_manager.file_progress.advance_file(file_task, resume_point)++ await self.client.download_file(self.manager, self.domain, media_item, partial_file, headers, file_task)partial_file.rename(complete_file)await self.mark_completed(media_item)diff --git a/cyberdrop_dl/managers/client_manager.py b/cyberdrop_dl/managers/client_manager.pyindex 2825983da..5bdadf207 100644--- a/cyberdrop_dl/managers/client_manager.py+++ b/cyberdrop_dl/managers/client_manager.py@@ -1,17 +1,30 @@from __future__ import annotations+import asyncioimport ssl+from enum import IntEnum+from http import HTTPStatusfrom typing import TYPE_CHECKINGimport aiohttpimport certifi+from aiolimiter import AsyncLimiter+from multidict import CIMultiDictProxy+from yarl import URL+from cyberdrop_dl.clients.errors import DownloadFailurefrom cyberdrop_dl.clients.scraper_client import ScraperClientif TYPE_CHECKING:from cyberdrop_dl.managers.manager import Manager+class CustomHTTPStatus(IntEnum):+ WEB_SERVER_IS_DOWN = 521+ IM_A_TEAPOT = 418+ DDOS_GUARD = 429++class ClientManager:"""Creates a 'client' that can be referenced by scraping or download sessions"""def __init__(self, manager: Manager):@@ -27,6 +40,14 @@ class ClientManager:self.cookies = aiohttp.CookieJar(quote_cookie=False)self.proxy = manager.config_manager.global_settings_data['General']['proxy']+ self.domain_rate_limits = {+ "bunkr": AsyncLimiter(10, 1),++ "other": AsyncLimiter(100, 1)+ }+ self.global_rate_limiter = AsyncLimiter(self.rate_limit, 1)+ self.session_limit = asyncio.Semaphore(50)+self.scraper_sessions = {}self.downloader_sessions = {}@@ -50,3 +71,32 @@ class ClientManager:await session.client_session.close()for session in self.downloader_sessions.values():await session.client_session.close()++ """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""++ async def get_rate_limiter(self, domain: str):+ """Get a rate limiter for a domain"""+ if domain in self.domain_rate_limits:+ return self.domain_rate_limits[domain]+ return self.domain_rate_limits["other"]++ """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""++ async def check_http_status(self, status: int, headers: CIMultiDictProxy, response_url: URL, download: bool = False):+ """Checks the HTTP status code and raises an exception if it's not acceptable"""+ if headers.get("Server") == "ddos-guard":+ raise DownloadFailure(status=CustomHTTPStatus.DDOS_GUARD, message="DDoS-Guard detected, unable to continue")+ if not headers.get('Content-Type'):+ raise DownloadFailure(status=CustomHTTPStatus.IM_A_TEAPOT, message="No content-type in response header")++ if download:+ if response_url in [URL("https://bnkr.b-cdn.net/maintenance-vid.mp4"),+ URL("https://bnkr.b-cdn.net/maintenance.mp4")]:+ raise DownloadFailure(status=HTTPStatus.SERVICE_UNAVAILABLE, message="Bunkr under maintenance")+ if "imgur.com/removed" in str(response_url):+ raise DownloadFailure(status=HTTPStatus.NOT_FOUND, message="Imgur image has been removed")++ if HTTPStatus.OK <= status < HTTPStatus.BAD_REQUEST:+ return++ raise DownloadFailure(status=status, message=f"HTTP status code {status}: {HTTPStatus(status).phrase}")