Skip to content

Bulk asynchronous downloader for multiple file hosts

separate sql, add new flag.

Jules-WinnfieldX41e0e88c5903
diff --git a/CHANGELOG.txt b/CHANGELOG.txt
index a918b0a58..caa9a121e 100644
--- a/CHANGELOG.txt
+++ b/CHANGELOG.txt
@@ -16,4 +16,7 @@ Created scraper_helper.py
-> we now only create the scrapers as needed, and it allows me to pass backwards the thotsbay links, cleaning up the code.
2.16.5
-Removed title tags from thotsbay folder names.
\ No newline at end of file
+Removed title tags from thotsbay folder names.
+
+2.16.6
+Added --ignore-history flag and separated SQL into its own helper class.
\ No newline at end of file
diff --git a/cyberdrop_dl/__init__.py b/cyberdrop_dl/__init__.py
index ab9fae395..c4ed6cf8c 100644
--- a/cyberdrop_dl/__init__.py
+++ b/cyberdrop_dl/__init__.py
@@ -1 +1 @@
-__version__ = "2.16.5"
+__version__ = "2.16.6"
diff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.py
index 86303b617..7545f322e 100644
--- a/cyberdrop_dl/main.py
+++ b/cyberdrop_dl/main.py
@@ -7,9 +7,10 @@ from colorama import Fore
from yarl import URL
from . import __version__ as VERSION
-from .utils.base_functions import clear, log, logger, purge_dir, regex_links, sql_initialize
+from .utils.base_functions import clear, log, logger, purge_dir, regex_links
from .utils.downloaders import get_downloaders
from .utils.scraper import scrape
+from .utils.sql_helper import SQLHelper
def parse_args():
@@ -27,6 +28,7 @@ def parse_args():
parser.add_argument("--exclude-images", help="skip downloading of image files", action="store_true")
parser.add_argument("--exclude-audio", help="skip downloading of audio files", action="store_true")
parser.add_argument("--exclude-other", help="skip downloading of images", action="store_true")
+ parser.add_argument("--ignore-history", help="This ignores previous download history", action="store_true")
parser.add_argument("--thotsbay-username", type=str, help="username to login to thotsbay", default=None)
parser.add_argument("--thotsbay-password", type=str, help="password to login to thotsbay", default=None)
parser.add_argument("links", metavar="link", nargs="*", help="link to content to download (passing multiple links is supported)", default=[])
@@ -44,7 +46,8 @@ async def download_all(args: argparse.Namespace):
await log(f"{input_file} created. Populate it and retry.")
exit(1)
- conn, curr = await sql_initialize(args.db_file)
+ SQL_helper = SQLHelper(args.ignore_history, args.db_file)
+ await SQL_helper.sql_initialize()
links = args.links
links = list(map(URL, links))
@@ -62,7 +65,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, connection=conn, cursor=curr,)
+ exclude_other=args.exclude_other, SQL_helper=SQL_helper)
for downloader in downloaders:
await downloader.download_content()
diff --git a/cyberdrop_dl/utils/base_functions.py b/cyberdrop_dl/utils/base_functions.py
index f9819e9da..fe202767f 100644
--- a/cyberdrop_dl/utils/base_functions.py
+++ b/cyberdrop_dl/utils/base_functions.py
@@ -1,7 +1,6 @@
import logging
import os
import re
-import sqlite3
import ssl
import certifi
@@ -43,40 +42,6 @@ async def sanitize(input: str) -> str:
return re.sub(r'[<>:"/\\|?*\']', "", input)
-async def sql_initialize(download_history):
- conn = sqlite3.connect(download_history)
- curr = conn.cursor()
- create_table_query = """CREATE TABLE IF NOT EXISTS downloads (
- filename TEXT,
- size INTEGER NOT NULL,
- completed INTEGER NOT NULL,
- PRIMARY KEY (filename, size)
- );"""
- curr.execute(create_table_query)
-
- conn.commit()
- return conn, curr
-
-
-async def sql_check_existing(cursor: sqlite3.Cursor, filename, size):
- cursor.execute("""SELECT completed FROM downloads WHERE filename = '%s' and size = %d""" % (filename, size))
- sql_file_check = cursor.fetchone()
- if sql_file_check:
- if sql_file_check[0] == 1:
- return True
- return False
-
-
-async def sql_insert_file(connection: sqlite3.Connection, cursor: sqlite3.Cursor, filename, size, completed):
- cursor.execute("""INSERT OR IGNORE INTO downloads VALUES ('%s', %d, %d)""" % (filename, size, completed))
- connection.commit()
-
-
-async def sql_update_file(connection: sqlite3.Connection, cursor: sqlite3.Cursor, filename, size, completed):
- cursor.execute("""INSERT OR REPLACE INTO downloads VALUES ('%s', %d, %d)""" % (filename, size, completed))
- connection.commit()
-
-
async def log(text, style=Fore.WHITE) -> None:
"""Wrapper around print() to add color to text"""
logger.debug(text)
diff --git a/cyberdrop_dl/utils/crawlers/Thotsbay_Spider.py b/cyberdrop_dl/utils/crawlers/Thotsbay_Spider.py
index aef27e8ef..ab61b403d 100644
--- a/cyberdrop_dl/utils/crawlers/Thotsbay_Spider.py
+++ b/cyberdrop_dl/utils/crawlers/Thotsbay_Spider.py
@@ -93,7 +93,6 @@ class ThotsbayCrawler():
post_number = str(url).split("post-")
post_number = int(post_number[-1].strip("/")) if len(post_number) == 2 else None
-
posts = soup.select("div[class='message-main uix_messageContent js-quickEditTarget']")
for post in posts:
if post_number:
diff --git a/cyberdrop_dl/utils/downloaders.py b/cyberdrop_dl/utils/downloaders.py
index a53db0c65..c5a5071cb 100644
--- a/cyberdrop_dl/utils/downloaders.py
+++ b/cyberdrop_dl/utils/downloaders.py
@@ -15,8 +15,8 @@ from colorama import Fore
from tqdm import tqdm
from yarl import URL
-from .base_functions import FILE_FORMATS, MAX_FILENAME_LENGTH, log, logger, sanitize, sql_check_existing, \
- sql_insert_file, sql_update_file, ssl_context, user_agent
+from .base_functions import FILE_FORMATS, MAX_FILENAME_LENGTH, log, logger, sanitize, ssl_context, user_agent
+from .sql_helper import SQLHelper
from .data_classes import AlbumItem, CascadeItem
@@ -71,14 +71,13 @@ 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, connection: sqlite3.Connection, cursor: sqlite3.Cursor):
+ exclude_audio: bool, exclude_other: bool, SQL_helper: SQLHelper):
self.album_obj = album_obj
self.cookie_jar = cookie_jar
self.folder = folder
self.title = title
- self.connection = connection
- self.cursor = cursor
+ self.SQL_helper = SQL_helper
self.attempts = attempts
self.current_attempt = 0
@@ -155,13 +154,13 @@ class Downloader:
return
total = int(resp.headers.get('Content-Length', str(0))) + resume_point
- if await sql_check_existing(self.cursor, filename, total):
+ if await self.SQL_helper.sql_check_existing(filename, total):
logger.debug("%s Already Downloaded" % filename)
return
(self.folder / self.title).mkdir(parents=True, exist_ok=True)
- await sql_insert_file(self.connection, self.cursor, filename, total, 0)
+ await self.SQL_helper.sql_insert_file(filename, total, 0)
with tqdm(
total=total, unit_scale=True,
@@ -195,7 +194,7 @@ class Downloader:
await aiofiles.os.remove(temp_file)
else:
temp_file.rename(complete_file)
- await sql_update_file(self.connection, self.cursor, filename, complete_file.stat().st_size, 1)
+ await self.SQL_helper.sql_update_file(filename, complete_file.stat().st_size, 1)
logger.debug("Finished " + filename)
async def download_and_store(
@@ -217,7 +216,7 @@ class Downloader:
complete_file = (self.folder / self.title / filename)
if complete_file.exists():
- await sql_update_file(self.connection, self.cursor, filename, complete_file.stat().st_size, 1)
+ await self.SQL_helper.sql_update_file(filename, complete_file.stat().st_size, 1)
logger.debug(str(complete_file) + " Already Exists")
else:
logger.debug("Working on " + str(url))
@@ -244,11 +243,12 @@ class Downloader:
"""Download the content of all links and save them as files."""
async with aiohttp.ClientSession(cookie_jar=self.cookie_jar) as session:
await self.download_all(self.album_obj, session, show_progress=show_progress)
- self.connection.commit()
+ self.SQL_helper.conn.commit()
-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, connection:sqlite3.Connection, cursor: sqlite3.Cursor) -> List[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,
+ SQL_helper: SQLHelper) -> 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
@@ -269,6 +269,6 @@ def get_downloaders(Cascade: CascadeItem, folder: Path, attempts: int, disable_a
attempts=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, connection=connection, cursor=cursor)
+ exclude_other=exclude_other, SQL_helper=SQL_helper)
downloaders.append(downloader)
return downloaders
diff --git a/cyberdrop_dl/utils/sql_helper.py b/cyberdrop_dl/utils/sql_helper.py
new file mode 100644
index 000000000..30847f506
--- /dev/null
+++ b/cyberdrop_dl/utils/sql_helper.py
@@ -0,0 +1,39 @@
+import sqlite3
+
+
+class SQLHelper():
+ def __init__(self, ignore_history, download_history):
+ self.ignore_history = ignore_history
+ self.download_history = download_history
+ self.conn = None
+ self.curs = None
+
+ async def sql_initialize(self):
+ self.conn = sqlite3.connect(self.download_history)
+ self.curs = self.conn.cursor()
+ create_table_query = """CREATE TABLE IF NOT EXISTS downloads (
+ filename TEXT,
+ size INTEGER NOT NULL,
+ completed INTEGER NOT NULL,
+ PRIMARY KEY (filename, size)
+ );"""
+ self.curs.execute(create_table_query)
+ self.conn.commit()
+
+ async def sql_check_existing(self, filename, size):
+ if self.ignore_history:
+ return False
+ self.curs.execute("""SELECT completed FROM downloads WHERE filename = '%s' and size = %d""" % (filename, size))
+ sql_file_check = self.curs.fetchone()
+ if sql_file_check:
+ if sql_file_check[0] == 1:
+ return True
+ return False
+
+ async def sql_insert_file(self, filename, size, completed):
+ self.curs.execute("""INSERT OR IGNORE INTO downloads VALUES ('%s', %d, %d)""" % (filename, size, completed))
+ self.conn.commit()
+
+ async def sql_update_file(self, filename, size, completed):
+ self.curs.execute("""INSERT OR REPLACE INTO downloads VALUES ('%s', %d, %d)""" % (filename, size, completed))
+ self.conn.commit()