Skip to content

Bulk asynchronous downloader for multiple file hosts

Transitioned downloader to use dataclasses.

Jules-WinnfieldX6ad406c09c36
diff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.py
index b555d9363..c80035ded 100644
--- a/cyberdrop_dl/main.py
+++ b/cyberdrop_dl/main.py
@@ -23,7 +23,8 @@ def parse_args():
parser.add_argument("--threads", type=int, help="number of threads to use (0 = max)", default=0)
parser.add_argument("--attempts", type=int, help="number of attempts to download each file", default=10)
parser.add_argument("--include-id", help="include the ID in the download folder name", action="store_true")
- parser.add_argument("links", metavar="link", nargs="*", help="link to content to download (passing multiple links is supported)", default=[])
+ parser.add_argument("links", metavar="link", nargs="*",
+ help="link to content to download (passing multiple links is supported)", default=[])
args = parser.parse_args()
return args
@@ -64,12 +65,14 @@ async def download_all(args: argparse.Namespace):
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=content_object.cookies.cookies, folder=Path(args.output_folder), attempts=args.attempts, threads=args.threads)
+ downloaders = get_downloaders(content_object, folder=Path(args.output_folder),
+ attempts=args.attempts, threads=args.threads)
for downloader in downloaders:
await downloader.download_content()
- log('Finished scraping. Enjoy :)')
- log('If you have ".download" files remaining, rerun this program. You most likely ran into download attempts limit')
+ log('Finished downloading. Enjoy :)')
+ log('If you have ".download" files remaining, rerun this program. '
+ 'You most likely ran into download attempts limits')
def main():
diff --git a/cyberdrop_dl/utils/base_functions.py b/cyberdrop_dl/utils/base_functions.py
index 243d2a8a7..be145162c 100644
--- a/cyberdrop_dl/utils/base_functions.py
+++ b/cyberdrop_dl/utils/base_functions.py
@@ -26,6 +26,7 @@ mapping_GoFile = ["gofile.io"]
mapping_Pixeldrain = ["pixeldrain.com"]
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'
+MAX_FILENAME_LENGTH = 100
def make_title_safe(title: str):
diff --git a/cyberdrop_dl/utils/data_classes.py b/cyberdrop_dl/utils/data_classes.py
index a03596519..516a0c88c 100644
--- a/cyberdrop_dl/utils/data_classes.py
+++ b/cyberdrop_dl/utils/data_classes.py
@@ -13,6 +13,9 @@ class CookiesItem:
else:
self.cookies.extend(x for x in passed_cookies if x not in self.cookies)
+ def get_cookies(self):
+ return self.cookies
+
@dataclass
class AlbumItem:
@@ -30,6 +33,9 @@ class AlbumItem:
def get_title(self):
return self.title
+ def get_link_pairs(self):
+ return self.link_pairs
+
@dataclass
class DomainItem:
@@ -50,6 +56,9 @@ class DomainItem:
album.set_new_title(title)
self.albums[title] = album
+ def get_albums(self):
+ return self.albums
+
@dataclass
class CascadeItem:
@@ -75,11 +84,17 @@ class CascadeItem:
else:
self.domains[domain] = DomainItem(domain, {title: album})
+ def add_cookie(self, cookie: List[Dict]):
+ self.cookies.add_cookies(cookie)
+
def get_albums(self, domain: str):
if domain in self.domains.keys():
return self.domains[domain].albums
else:
return {}
- def add_cookie(self, cookie: List[Dict]):
- self.cookies.add_cookies(cookie)
+ def get_cookies(self):
+ return self.cookies.get_cookies()
+
+ def get_domains(self):
+ return self.domains
diff --git a/cyberdrop_dl/utils/downloaders.py b/cyberdrop_dl/utils/downloaders.py
index f47a334f3..7c4544e5a 100644
--- a/cyberdrop_dl/utils/downloaders.py
+++ b/cyberdrop_dl/utils/downloaders.py
@@ -7,7 +7,6 @@ from pathlib import Path
import ssl
import time
import traceback
-from typing import Iterable, Optional, List
import aiofiles
import aiofiles.os
@@ -19,29 +18,11 @@ from sanitize_filename import sanitize
from tqdm import tqdm
import yarl
+from .base_functions import *
+from .data_classes import *
-asyncio.get_event_loop()
logger = logging.getLogger(__name__)
-MAX_FILENAME_LENGTH = 100
-FILE_FORMATS = {
- 'Images': {
- '.jpg', '.jpeg', '.png', '.gif',
- '.gif', '.webp', '.jpe', '.svg',
- '.tif', '.tiff', '.jif',
- },
- 'Videos': {
- '.mpeg', '.avchd', '.webm', '.mpv',
- '.swf', '.avi', '.m4p', '.wmv',
- '.mp2', '.m4v', '.qt', '.mpe',
- '.mp4', '.flv', '.mov', '.mpg',
- '.ogg',
- },
- 'Audio': {
- '.mp3', '.flac', '.wav', '.m4a'
- }
-}
-
def log(text, style):
# Log function for printing to command line
@@ -95,8 +76,8 @@ async def throttle(self, url: yarl.URL) -> None:
class Downloader:
- def __init__(self, links: List[List[str]], morsels, folder: Path, title: str, attempts: int, max_workers: int):
- self.links = links
+ def __init__(self, album_obj: AlbumItem, morsels, folder: Path, title: str, attempts: int, max_workers: int):
+ self.album_obj = album_obj
self.morsels = morsels
self.folder = folder
self.title = title
@@ -118,7 +99,6 @@ class Downloader:
show_progress: bool = True
) -> None:
"""Download the content of given URL"""
- 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'
headers = {'Referer': referral, 'user-agent': user_agent}
ssl_context = ssl.create_default_context(cafile=certifi.where())
@@ -151,7 +131,7 @@ class Downloader:
log(f"\nServer for {url} is either down or the file no longer exists", Fore.RED)
return
- total = int(resp.headers.get('Content-Length', 0)) + resume_point
+ total = int(resp.headers.get('Content-Length', str(0))) + resume_point
with tqdm(
total=total, unit_scale=True,
unit='B', leave=False, initial=resume_point,
@@ -179,13 +159,12 @@ class Downloader:
async def download_and_store(
self,
- url_object: List,
+ url_tuple: Tuple,
session: aiohttp.ClientSession,
show_progress: bool = True
) -> None:
"""Download the content of given URL and store it in a file."""
- url = url_object[0]
- referral = url_object[1]
+ url, referral = url_tuple
filename = url.split("/")[-1]
filename = sanitize(sanitize(filename))
@@ -200,7 +179,8 @@ class Downloader:
else:
logger.debug("Working on " + url)
try:
- await self.download_file(url, referral=referral, filename=filename, session=session, show_progress=show_progress)
+ await self.download_file(url, referral=referral, filename=filename,
+ session=session, show_progress=show_progress)
except Exception:
logger.debug(traceback.format_exc())
log(f"\nSkipping {filename}: likely exceeded download attempts (or ran into an error)\nRe-run program "
@@ -208,12 +188,13 @@ class Downloader:
async def download_all(
self,
- links: Iterable[List[str]],
+ album_obj: AlbumItem,
session: aiohttp.ClientSession,
show_progress: bool = True
) -> None:
"""Download the data from all given links and store them into corresponding files."""
- coros = [self.download_and_store(link, session, show_progress) for link in links]
+ coros = [self.download_and_store(url_object, session, show_progress)
+ for url_object in album_obj.get_link_pairs()]
for func in tqdm(asyncio.as_completed(coros), total=len(coros), desc=self.title, unit='FILES'):
await func
@@ -225,7 +206,7 @@ class Downloader:
(self.folder / self.title).mkdir(parents=True, exist_ok=True)
async with aiohttp.ClientSession() as session:
session.cookie_jar.update_cookies(self.morsels)
- await self.download_all(self.links, session, show_progress=show_progress)
+ await self.download_all(self.album_obj, session, show_progress=show_progress)
def simple_cookies(cookies):
@@ -247,7 +228,7 @@ def simple_cookies(cookies):
return morsels
-def get_downloaders(urls: dict[str, dict[str, list[str]]], cookies: Iterable[str], folder: Path, attempts: int, threads: int) -> list[Downloader]:
+def get_downloaders(Cascade: CascadeItem, folder: Path, attempts: int, threads: int) -> 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
@@ -256,13 +237,14 @@ def get_downloaders(urls: dict[str, dict[str, list[str]]], cookies: Iterable[str
"""
downloaders = []
- morsels = simple_cookies(cookies)
+ morsels = simple_cookies(Cascade.get_cookies())
- for domain, url_object in urls.items():
+ for domain, domain_obj in Cascade.get_domains().items():
max_workers = threads if threads != 0 else multiprocessing.cpu_count()
- for title, urls in url_object.items():
- if 'bunkr' in domain:
- max_workers = 2 if (max_workers > 2) else max_workers
- downloader = Downloader(urls, morsels=morsels, title=title, folder=folder, attempts=attempts, max_workers=max_workers)
+ if 'bunkr' in domain:
+ max_workers = 2 if (max_workers > 2) else max_workers
+ for title, album_obj in domain_obj.get_albums().items():
+ downloader = Downloader(album_obj, morsels=morsels, title=title, folder=folder,
+ attempts=attempts, max_workers=max_workers)
downloaders.append(downloader)
return downloaders