Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
Fixed thotsbay scraping, changed DB
Jules-WinnfieldX7fa73b293beb
diff --git a/cyberdrop_dl/__init__.py b/cyberdrop_dl/__init__.pyindex eb1d14dbb..7843237ad 100644--- a/cyberdrop_dl/__init__.py+++ b/cyberdrop_dl/__init__.py@@ -1 +1 @@-__version__ = "2.19.6"+__version__ = "2.20.1"diff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.pyindex 323f80696..0a6e23240 100644--- a/cyberdrop_dl/main.py+++ b/cyberdrop_dl/main.py@@ -2,6 +2,7 @@ import argparseimport asyncioimport loggingfrom pathlib import Path+from argparse import Namespacefrom colorama import Forefrom yarl import URL@@ -21,7 +22,7 @@ def parse_args():parser.add_argument("-o", "--output-folder", type=Path, help="folder to download files to", default="Downloads")parser.add_argument("--log-file", help="log file to write to", default="downloader.log")parser.add_argument("--db-file", help="history database file to write to",- default="download_history_size_based.sqlite")+ default="download_history.sqlite")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("--disable-attempt-limit", help="disables the attempt limitation", action="store_true")@@ -44,7 +45,7 @@ def parse_args():async def download_all(args: argparse.Namespace):await clear()await log(f"We are running version {VERSION} of Cyberdrop Downloader", Fore.WHITE)- print_args = args.__dict__+ print_args = Namespace(**vars(args)).__dict__print_args['thotsbay_password'] = '!REDACTED!'logging.debug(f"Starting downloader with args: {print_args}")input_file = args.input_filediff --git a/cyberdrop_dl/utils/downloaders.py b/cyberdrop_dl/utils/downloaders.pyindex 0b62ded6d..90a152853 100644--- a/cyberdrop_dl/utils/downloaders.py+++ b/cyberdrop_dl/utils/downloaders.py@@ -105,6 +105,10 @@ class Downloader:"""Download the content of given URL"""headers = {'Referer': str(referral), 'user-agent': user_agent}+ # return if completed already+ if await self.SQL_helper.sql_check_existing(url.path):+ return+try:async with self._semaphore:# If ext isn't allowable we likely have an invalid filename, lets go get it.@@ -114,8 +118,12 @@ class Downloader:if key in url.host:await throttle(self, value, key)async with session.get(url, headers=headers, ssl=ssl_context, raise_for_status=True) as resp:- filename = resp.content_disposition.filename- filename = await sanitize(filename)+ try:+ filename = resp.content_disposition.filename+ filename = await sanitize(filename)+ except:+ await log("Couldn't get filename for: " + str(url))+ return# Make suffix always lower caseext = '.' + filename.split('.')[-1].lower()@@ -144,54 +152,25 @@ class Downloader:await asyncio.sleep(gauss(1, 1.5))await self.File_Lock.add_lock(filename)- async with session.head(url, headers=headers, ssl=ssl_context, raise_for_status=True) as resp:- total_size = int(resp.headers.get('Content-Length', str(0)))-complete_file = (self.folder / self.title / filename)- if await self.SQL_helper.check_filename(filename) or complete_file.exists:- for key, value in self.delay.items():- if key in url.host:- await throttle(self, value, key)-- # check for exact file- if complete_file.exists():- if complete_file.stat().st_size == total_size:- await self.SQL_helper.sql_insert_file(original_filename, filename, total_size, 1)- logger.debug("%s Already Downloaded" % filename)- await self.File_Lock.remove_lock(original_filename)- return-- # check for file under different name (same filename with wildcard)- base_dir = (self.folder / self.title)- for path in base_dir.glob(filename.replace(ext, '') + ' (*)' + ext):- if path.stat().st_size == total_size:- await self.SQL_helper.sql_insert_file(original_filename, path.name, total_size, 1)- logger.debug("%s Already Downloaded" % filename)- await self.File_Lock.remove_lock(original_filename)- return-- # Check DB for already downloaded- if await self.SQL_helper.sql_check_existing(filename, total_size):- logger.debug("%s Already Downloaded" % filename)- await self.File_Lock.remove_lock(original_filename)- return+ partial_file = (self.folder / self.title / filename)+ if complete_file.exists() or partial_file.exists():+ download_name = await self.SQL_helper.get_download_filename(url.path)iterations = 1- downloaded_filename = await self.SQL_helper.get_download_filename(filename, total_size)- # if we didn't find a filename already associated with the file in the db, we make one.- if not downloaded_filename:+ if not download_name:while True:filename = complete_file.stem + " (%d)" % iterations + extiterations += 1temp_complete_file = (self.folder / self.title / filename)if not temp_complete_file.exists():- if not await self.SQL_helper.check_filename_for_downloaded(filename):+ if not await self.SQL_helper.check_filename(filename):breakelse:- filename = downloaded_filename+ filename = download_name- await self.SQL_helper.sql_insert_file(original_filename, filename, total_size, 0)+ await self.SQL_helper.sql_insert_file(url.path, filename, 0)complete_file = (self.folder / self.title / filename)resume_point = 0@@ -215,8 +194,6 @@ class Downloader:total = int(resp.headers.get('Content-Length', str(0))) + resume_point(self.folder / self.title).mkdir(parents=True, exist_ok=True)- await self.SQL_helper.sql_insert_file(original_filename, filename, total_size, 0)-with tqdm(total=total, unit_scale=True,unit='B', leave=False, initial=resume_point,@@ -227,7 +204,7 @@ class Downloader:await f.write(chunk)progress.update(len(chunk))resp.close()- await self.rename_file(filename, original_filename)+ await self.rename_file(filename, url)await self.File_Lock.remove_lock(original_filename)except (aiohttp.client_exceptions.ClientPayloadError, aiohttp.client_exceptions.ClientOSError,@@ -248,7 +225,7 @@ class Downloader:raise FailureException(e)- async def rename_file(self, filename: str, original_filename: str) -> None:+ async def rename_file(self, filename: str, url: URL) -> None:"""Rename complete file."""complete_file = (self.folder / self.title / filename)temp_file = complete_file.with_suffix(complete_file.suffix + '.part')@@ -257,7 +234,8 @@ class Downloader:await aiofiles.os.remove(temp_file)else:temp_file.rename(complete_file)- await self.SQL_helper.sql_update_file(original_filename, filename, complete_file.stat().st_size, 1)++ await self.SQL_helper.sql_update_file(url.path, filename, 1)logger.debug("Finished " + filename)async def download_and_store(diff --git a/cyberdrop_dl/utils/sql_helper.py b/cyberdrop_dl/utils/sql_helper.pyindex 5192bf733..8bad94552 100644--- a/cyberdrop_dl/utils/sql_helper.py+++ b/cyberdrop_dl/utils/sql_helper.py@@ -1,6 +1,7 @@import atexitimport loggingimport sqlite3+import osclass SQLHelper:@@ -13,65 +14,38 @@ class SQLHelper:atexit.register(self.exit_handler)async def sql_initialize(self):+ if os.path.exists("download_history_size_based.sqlite"):+ os.remove("download_history_size_based.sqlite")self.conn = sqlite3.connect(self.download_history)self.curs = self.conn.cursor()create_table_query = """CREATE TABLE IF NOT EXISTS downloads (- filename TEXT,+ path TEXT,downloaded_filename TEXT,- size INTEGER NOT NULL,completed INTEGER NOT NULL,- PRIMARY KEY (filename, size)+ PRIMARY KEY (path));"""self.curs.execute(create_table_query)self.conn.commit()- await self.check_columns()- async def check_columns(self):- self.curs.execute("""SELECT COUNT(*) AS CNTREC FROM pragma_table_info('downloads') WHERE- name='downloaded_filename'""")- sql_check = self.curs.fetchone()[0]- if sql_check == (0):- create_table_query = """CREATE TABLE IF NOT EXISTS downloads_temp (- filename TEXT,- downloaded_filename TEXT,- size INTEGER NOT NULL,- completed INTEGER NOT NULL,- PRIMARY KEY (filename, size)- );"""- self.curs.execute(create_table_query)- self.conn.commit()- self.curs.execute("""INSERT INTO downloads_temp SELECT filename, filename, size, completed from downloads""")- self.curs.execute("""DROP TABLE downloads""")- self.curs.execute("""ALTER TABLE downloads_temp RENAME TO downloads""")- self.conn.commit()-- async def sql_check_existing(self, filename, size):+ async def sql_check_existing(self, path):if self.ignore_history:return False- self.curs.execute("""SELECT completed FROM downloads WHERE filename = ? and size = ?""", (filename, size))+ self.curs.execute("""SELECT completed FROM downloads WHERE path = ?""", (path, ))sql_file_check = self.curs.fetchone()if sql_file_check:if sql_file_check[0] == 1:return Truereturn False- async def sql_insert_file(self, filename, downloaded_filename, size, completed):- self.curs.execute("""INSERT OR IGNORE INTO downloads VALUES (?, ?, ?, ?)""", (filename, downloaded_filename, size, completed))+ async def sql_insert_file(self, path, downloaded_filename, completed):+ self.curs.execute("""INSERT OR IGNORE INTO downloads VALUES (?, ?, ?)""", (path, downloaded_filename, completed, ))self.conn.commit()- async def sql_update_file(self, filename, downloaded_filename, size, completed):- self.curs.execute("""INSERT OR REPLACE INTO downloads VALUES (?, ?, ?, ?)""", (filename, downloaded_filename, size, completed))+ async def sql_update_file(self, path, downloaded_filename, completed):+ self.curs.execute("""INSERT OR REPLACE INTO downloads VALUES (?, ?, ?)""", (path, downloaded_filename, completed, ))self.conn.commit()async def check_filename(self, filename):- self.curs.execute("""SELECT EXISTS(SELECT 1 FROM downloads WHERE filename = ?)""", (filename, ))- sql_check = self.curs.fetchone()[0]- if sql_check == 1:- return True- else:- return False-- async def check_filename_for_downloaded(self, filename):self.curs.execute("""SELECT EXISTS(SELECT 1 FROM downloads WHERE downloaded_filename = ?)""", (filename, ))sql_check = self.curs.fetchone()[0]if sql_check == 1:@@ -79,8 +53,8 @@ class SQLHelper:else:return False- async def get_download_filename(self, filename, size):- self.curs.execute("""SELECT downloaded_filename FROM downloads WHERE filename = ? and size = ?""", (filename, size))+ async def get_download_filename(self, path):+ self.curs.execute("""SELECT downloaded_filename FROM downloads WHERE path = ?""", (path, ))filename = self.curs.fetchone()if filename:return filename[0]