Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
Add basic db file that tracks already downloaded files.
Jules-WinnfieldXcf37c6d68ca9
diff --git a/.gitignore b/.gitignoreindex 2720998b8..6e9024252 100644--- a/.gitignore+++ b/.gitignore@@ -1,6 +1,7 @@# project stuffDownloads/*.log+*.sqlite# Python stuff.venv/diff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.pyindex 7fa893d79..32006d92c 100644--- a/cyberdrop_dl/main.py+++ b/cyberdrop_dl/main.py@@ -1,8 +1,10 @@import argparseimport asyncioimport pathlib+import sqlite3from pathlib import Path+from . import __version__ as VERSIONfrom .utils.scraper import scrapefrom .utils.downloaders import get_downloaders@@ -40,6 +42,8 @@ async def download_all(args: argparse.Namespace):log(f"{input_file} created. Populate it and retry.")exit(1)+ conn, curr = sql_initialize()+links = args.linkswith open(input_file, "r") as f:links += regex_links(f.read())@@ -55,7 +59,7 @@ async def download_all(args: argparse.Namespace):disable_attempt_limit=args.disable_attempt_limit,threads=args.threads, exclude_videos=args.exclude_videos,exclude_images=args.exclude_images, exclude_audio=args.exclude_audio,- exclude_other=args.exclude_other)+ exclude_other=args.exclude_other, connection=conn, cursor=curr)for downloader in downloaders:await downloader.download_content()diff --git a/cyberdrop_dl/utils/base_functions.py b/cyberdrop_dl/utils/base_functions.pyindex a79acce14..c30962564 100644--- a/cyberdrop_dl/utils/base_functions.py+++ b/cyberdrop_dl/utils/base_functions.py@@ -1,6 +1,7 @@import loggingimport osimport re+import sqlite3import sslimport certifi@@ -52,6 +53,43 @@ def sanitize(input: str) -> str:return re.sub(r'[<>:"/\\|?*]', "", input)+def sql_initialize():+ download_history = "download_history.sqlite"+ if not os.path.isfile(download_history):+ conn = sqlite3.connect(download_history)+ curr = conn.cursor()+ create_table_query = """CREATE TABLE downloads (+ direct_url TEXT PRIMARY KEY,+ filename TEXT NOT NULL,+ completed INTEGER NOT NULL+ );"""+ curr.execute(create_table_query)+ conn.commit()+ else:+ conn = sqlite3.connect(download_history)+ curr = conn.cursor()+ return conn, curr+++async def sql_check_existing(cursor: sqlite3.Cursor, url):+ cursor.execute("""SELECT completed FROM downloads WHERE direct_url = '%s'""" % str(url))+ sql_file_check = cursor.fetchone()+ if sql_file_check[0] == 0 or not sql_file_check:+ return False+ return True+++async def sql_insert_file(connection: sqlite3.Connection, cursor: sqlite3.Cursor, url, filename, completed):+ cursor.execute("""INSERT OR IGNORE INTO downloads VALUES ('%s', '%s', %d)""" % (url, filename, completed))+ connection.commit()+++async def sql_update_file(connection: sqlite3.Connection, cursor: sqlite3.Cursor, url, filename, completed):+ cursor.execute("""UPDATE downloads SET completed = %d WHERE+ direct_url = '%s' AND filename = '%s'""" % (completed, url, filename))+ connection.commit()++def log(text, style=Fore.WHITE) -> None:"""Wrapper around print() to add color to text"""print(style + str(text) + Style.RESET_ALL)@@ -99,7 +137,8 @@ def pixeldrain_parse(url: URL, title: str) -> URL:def check_direct(url: URL):mapping_direct = ['i.pixl.is', r's..putmega.com', r's..putme.ga', r'img-...cyberdrop...', r'f.cyberdrop...',- r'fs-...cyberdrop...', r'cdn.bunkr...', r'media-files.bunkr...', r'jpg.church/images/...', r'stream.bunkr...']+ r'fs-...cyberdrop...', r'cdn.bunkr...', r'media-files.bunkr...', r'jpg.church/images/...',+ r'stream.bunkr...', r'simp..jpg.church']for domain in mapping_direct:if re.search(domain, url.host):return Truediff --git a/cyberdrop_dl/utils/downloaders.py b/cyberdrop_dl/utils/downloaders.pyindex 8ae18dd9e..32e284f06 100644--- a/cyberdrop_dl/utils/downloaders.py+++ b/cyberdrop_dl/utils/downloaders.py@@ -63,8 +63,9 @@ async def throttle(self, url: URL) -> None:class Downloader:- def __init__(self, album_obj: AlbumItem, cookie_jar, folder: Path, title: str, attempts: int, disable_attempt_limit: bool, max_workers: int,- exclude_videos: bool, exclude_images: bool, exclude_audio: bool, exclude_other: bool):+ def __init__(self, album_obj: AlbumItem, cookie_jar, folder: Path, title: str, attempts: int,+ disable_attempt_limit: bool, max_workers: int, exclude_videos: bool, exclude_images: bool,+ exclude_audio: bool, exclude_other: bool, connection: sqlite3.Connection, cursor: sqlite3.Cursor):self.album_obj = album_objself.cookie_jar = cookie_jarself.folder = folder@@ -80,6 +81,8 @@ class Downloader:self._semaphore = asyncio.Semaphore(max_workers)self.delay = {'media-files.bunkr.is': 2}self.throttle_times = {}+ self.connection = connection+ self.cursor = cursor"""Changed from aiohttp exceptions caught to FailureException to allow for partial downloads."""@@ -128,6 +131,13 @@ class Downloader:logging.debug("Skipping " + filename)return+ if await sql_check_existing(self.cursor, str(url)):+ log("\n%s Already Downloaded" % filename)+ logger.debug("%s was found in db file (already downloaded)" % filename)+ return++ await sql_insert_file(self.connection, self.cursor, url, filename, 0)+resume_point = 0complete_file = (self.folder / self.title / filename)temp_file = complete_file.with_suffix(complete_file.suffix + '.part')@@ -153,6 +163,7 @@ class Downloader:async for chunk, _ in resp.content.iter_chunks():await f.write(chunk)progress.update(len(chunk))+ await sql_update_file(self.connection, self.cursor, url, filename, 1)await self.rename_file(filename)except (aiohttp.client_exceptions.ClientPayloadError, aiohttp.client_exceptions.ClientOSError,aiohttp.client_exceptions.ServerDisconnectedError, asyncio.TimeoutError,@@ -189,6 +200,7 @@ class Downloader:if (self.folder / self.title / filename).exists():logger.debug(str(self.folder / self.title / filename) + " Already Exists")+ await sql_update_file(self.connection, self.cursor, url, filename, 1)else:logger.debug("Working on " + str(url))try:@@ -221,7 +233,7 @@ class Downloader:def get_downloaders(Cascade: CascadeItem, folder: Path, attempts: int, disable_attempt_limit: bool, threads: int, exclude_videos: bool,- exclude_images: bool, exclude_audio: bool, exclude_other: bool) -> List[Downloader]:+ exclude_images: bool, exclude_audio: bool, exclude_other: bool, connection:sqlite3.Connection, cursor: sqlite3.Cursor) -> 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 asthe first one, so we need to classify them one by one, sort them to@@ -242,6 +254,6 @@ def get_downloaders(Cascade: CascadeItem, folder: Path, attempts: int, disable_aattempts=attempts, disable_attempt_limit=disable_attempt_limit,max_workers=max_workers, exclude_videos=exclude_videos,exclude_images=exclude_images, exclude_audio=exclude_audio,- exclude_other=exclude_other)+ exclude_other=exclude_other, connection=connection, cursor=cursor)downloaders.append(downloader)return downloaders