Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
Cleanup sql_helper a little
Arkadiy Illarionov803c6f97bb64
diff --git a/cyberdrop_dl/base_functions/sql_helper.py b/cyberdrop_dl/base_functions/sql_helper.pyindex eed93e100..d672d1f61 100644--- a/cyberdrop_dl/base_functions/sql_helper.py+++ b/cyberdrop_dl/base_functions/sql_helper.py@@ -2,6 +2,7 @@ import atexitimport loggingimport sqlite3from pathlib import Path+from typing import List, Optionalfrom cyberdrop_dl.base_functions.base_functions import get_db_pathfrom cyberdrop_dl.base_functions.data_classes import AlbumItem, CascadeItem, DomainItem@@ -9,7 +10,7 @@ from cyberdrop_dl.base_functions.data_classes import AlbumItem, CascadeItem, Domclass SQLHelper:"""This class is responsible for handling SQL operations"""- def __init__(self, ignore_history, ignore_cache, download_history):+ def __init__(self, ignore_history: bool, ignore_cache: bool, download_history: str):self.ignore_history = ignore_historyself.ignore_cache = ignore_cacheself.download_history = download_history@@ -18,20 +19,20 @@ class SQLHelper:self.old_history = False# Close the sql connection when the program exits- atexit.register(self.exit_handler)+ atexit.register(self._exit_handler)- async def sql_initialize(self):+ async def sql_initialize(self) -> None:"""Initializes the SQL connection, and makes sure necessary tables exist"""self.conn = sqlite3.connect(self.download_history)self.curs = self.conn.cursor()- await self.check_old_history()+ await self._check_old_history()- await self.pre_allocate()- await self.create_media_history()- await self.create_coomeno_history()+ await self._pre_allocate()+ await self._create_media_history()+ await self._create_coomeno_history()- async def check_old_history(self):+ async def _check_old_history(self) -> None:"""Checks whether V3 history exists"""try:self.curs.execute("""SELECT name FROM sqlite_schema WHERE type='table' AND name='downloads'""")@@ -42,7 +43,7 @@ class SQLHelper:if sql_file_check:self.old_history = True- async def create_media_history(self):+ async def _create_media_history(self) -> None:"""We create the download history tables here"""create_table_query = """CREATE TABLE IF NOT EXISTS media (domain TEXT,@@ -67,7 +68,7 @@ class SQLHelper:self.curs.execute(temp_truncate_query)self.conn.commit()- async def create_coomeno_history(self):+ async def _create_coomeno_history(self) -> None:"""Creates the cache table for coomeno"""create_table_query = """CREATE TABLE IF NOT EXISTS coomeno (url_path TEXT,@@ -77,7 +78,7 @@ class SQLHelper:self.curs.execute(create_table_query)self.conn.commit()- async def pre_allocate(self):+ async def _pre_allocate(self) -> None:"""We pre-allocate 50MB of space to the SQL file just in case the user runs out of disk space"""pre_alloc = "CREATE TABLE IF NOT EXISTS t(x);"pre_alloc2 = "INSERT INTO t VALUES(zeroblob(50*1024*1024));" # 50 mb@@ -96,26 +97,25 @@ class SQLHelper:"""Temp Table Operations"""- async def get_temp_names(self):+ async def get_temp_names(self) -> List[str]:"""Gets the list of temp filenames"""self.curs.execute("SELECT downloaded_filename FROM downloads_temp;")filenames = self.curs.fetchall()- filenames = list(sum(filenames, ()))- return filenames+ return list(sum(filenames, ()))- async def sql_insert_temp(self, downloaded_filename):+ async def sql_insert_temp(self, downloaded_filename: str) -> None:"""Inserts a temp filename into the downloads_temp table"""self.curs.execute("""INSERT OR IGNORE INTO downloads_temp VALUES (?)""", (downloaded_filename,))self.conn.commit()"""Coomeno Table Operations"""- async def insert_blob(self, blob: str, url_path: str):+ async def insert_blob(self, blob: str, url_path: str) -> None:"""Inserts the post content into coomeno"""- self.curs.execute("""INSERT OR IGNORE INTO coomeno VALUES (?, ?)""", (url_path, blob,))+ self.curs.execute("""INSERT OR IGNORE INTO coomeno VALUES (?, ?)""", (url_path, blob))self.conn.commit()- async def get_blob(self, url_path: str):+ async def get_blob(self, url_path: str) -> Optional[str]:"""returns the post content for a given coomeno post url"""if self.ignore_cache:return None@@ -128,94 +128,90 @@ class SQLHelper:"""Download Table Operations"""async def insert_media(self, domain: str, url_path: str, album_path: str, referer: str, download_path: str,- download_filename: str, original_filename: str, completed: int):+ download_filename: str, original_filename: str, completed: int) -> None:"""Inserts a media entry into the media table"""self.curs.execute("""INSERT OR IGNORE INTO media VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",- (domain, url_path, album_path, referer, download_path, download_filename, original_filename, completed,))+ (domain, url_path, album_path, referer, download_path, download_filename, original_filename, completed))self.conn.commit()- async def insert_album(self, domain: str, album_path: str, album: AlbumItem):+ async def insert_album(self, domain: str, album_path: str, album: AlbumItem) -> None:"""Inserts an albums media into the media table"""if album.media:for media in album.media:url_path = await get_db_path(media.url, domain)self.curs.execute("""INSERT OR IGNORE INTO media VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",- (domain, url_path, album_path, str(media.referer), "", "", media.original_filename, 0,))+ (domain, url_path, album_path, str(media.referer), "", "", media.original_filename, 0))self.conn.commit()- async def insert_domain(self, domain_name: str, album_path: str, domain: DomainItem):+ async def insert_domain(self, domain_name: str, album_path: str, domain: DomainItem) -> None:"""Inserts a domains media into the media table"""if domain.albums:- for title, album in domain.albums.items():+ for _, album in domain.albums.items():for media in album.media:url_path = await get_db_path(media.url, domain_name)self.curs.execute("""INSERT OR IGNORE INTO media VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",(domain_name, url_path, album_path, str(media.referer), "", "",- media.original_filename, 0,))+ media.original_filename, 0))self.conn.commit()- async def insert_cascade(self, cascade: CascadeItem):+ async def insert_cascade(self, cascade: CascadeItem) -> None:"""Inserts a cascades media into the media table"""if not await cascade.is_empty():for domain, domain_obj in cascade.domains.items():- for title, album_obj in domain_obj.albums.items():+ for _, album_obj in domain_obj.albums.items():for media in album_obj.media:url_path = await get_db_path(media.url, domain)self.curs.execute("""INSERT OR IGNORE INTO media VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",(domain, url_path, media.referer.path, str(media.referer), "",- "", media.original_filename, 0,))+ "", media.original_filename, 0))self.conn.commit()- async def get_downloaded_filename(self, url_path, filename):+ async def get_downloaded_filename(self, url_path: str, filename: str) -> Optional[str]:"""Gets downloaded filename given the url path and original filename"""self.curs.execute("""SELECT download_filename FROM media WHERE url_path = ? and original_filename = ?""",- (url_path, filename,))+ (url_path, filename))sql_file_check = self.curs.fetchone()if sql_file_check:return sql_file_check[0]return None- async def sql_check_old_existing(self, url_path):+ async def sql_check_old_existing(self, url_path: str) -> bool:"""Checks the V3 history table for completed if it exists"""- if not self.old_history:- return False- if self.ignore_history:+ if not self.old_history or self.ignore_history:return Falseself.curs.execute("""SELECT completed FROM downloads WHERE path = ?""", (url_path,))sql_file_check = self.curs.fetchone()return sql_file_check and sql_file_check[0] == 1- async def check_complete_singular(self, domain, url_path):+ async def check_complete_singular(self, domain: str, url_path: str) -> bool:"""Checks whether an individual file has completed given its domain and url path"""if self.ignore_history:return False- self.curs.execute("""SELECT completed FROM media WHERE domain = ? and url_path = ?""", (domain, url_path,))+ self.curs.execute("""SELECT completed FROM media WHERE domain = ? and url_path = ?""", (domain, url_path))sql_file_check = self.curs.fetchone()- if not sql_file_check:- return False- return sql_file_check[0] != 0+ return sql_file_check and sql_file_check[0] != 0"""Downloader Operations"""- async def check_filename(self, filename):+ async def check_filename(self, filename: str) -> bool:"""Checks whether an individual exists in the DB given its filename"""self.curs.execute("""SELECT EXISTS(SELECT 1 FROM media WHERE download_filename = ?)""", (filename, ))sql_check = self.curs.fetchone()[0]return sql_check == 1- async def update_pre_download(self, path: Path, filename: str, url_path: str, original_filename: str):+ async def update_pre_download(self, path: Path, filename: str, url_path: str, original_filename: str) -> None:"""Update the media entry pre-download"""self.curs.execute("""UPDATE media SET download_path = ?, download_filename = ? WHERE url_path = ?- AND original_filename = ?""", (str(path), filename, url_path, original_filename,))+ AND original_filename = ?""", (str(path), filename, url_path, original_filename))self.conn.commit()- async def mark_complete(self, url_path: str, original_filename: str):+ async def mark_complete(self, url_path: str, original_filename: str) -> None:"""Update the media entry post-download"""- self.curs.execute("""UPDATE media SET completed = 1 WHERE url_path = ? AND original_filename = ?""", (url_path, original_filename,))+ self.curs.execute("""UPDATE media SET completed = 1 WHERE url_path = ? AND original_filename = ?""", (url_path, original_filename))self.conn.commit()"""DB Fixes"""- async def fix_bunkr_entries(self, url_path: str, original_filename: str):+ async def fix_bunkr_entries(self, url_path: str, original_filename: str) -> None:complete_row = Noneself.curs.execute("""SELECT * FROM media WHERE url_path = ?""", (url_path,))sql_res = self.curs.fetchall()@@ -224,28 +220,27 @@ class SQLHelper:complete_row = rowelse:if len(sql_res) < 2:- await self.update_row_original_filename(url_path, original_filename)+ await self._update_row_original_filename(url_path, original_filename)break- await self.remove_entry(url_path, row[6])- if complete_row:- if complete_row[6] != original_filename:- await self.update_row_original_filename(url_path, original_filename)+ await self._remove_entry(url_path, row[6])+ if complete_row and complete_row[6] != original_filename:+ await self._update_row_original_filename(url_path, original_filename)self.conn.commit()- async def update_row_original_filename(self, url_path: str, original_filename: str):- self.curs.execute("""UPDATE media SET original_filename = ? WHERE url_path = ?""", (original_filename, url_path,))+ async def _update_row_original_filename(self, url_path: str, original_filename: str) -> None:+ self.curs.execute("""UPDATE media SET original_filename = ? WHERE url_path = ?""", (original_filename, url_path))self.conn.commit()- async def remove_entry(self, url_path: str, original_filename: str):- self.curs.execute("""DELETE FROM media WHERE url_path = ? AND original_filename = ?""", (url_path, original_filename,))+ async def _remove_entry(self, url_path: str, original_filename: str) -> None:+ self.curs.execute("""DELETE FROM media WHERE url_path = ? AND original_filename = ?""", (url_path, original_filename))self.conn.commit()- def exit_handler(self):+ def _exit_handler(self) -> None:"""Exit handler on unexpected exits"""try:self.conn.commit()self.conn.close()except Exception as e:- logging.debug(f"Failed to close sqlite database connection: {str(e)}")+ logging.debug("Failed to close sqlite database connection: %s", str(e))else:logging.debug("Successfully closed sqlite database connection")