Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: cleanup database logic (#1280)

NTFSvolume4b7c1ac54e38
diff --git a/cyberdrop_dl/managers/db_manager.py b/cyberdrop_dl/managers/db_manager.py
index 6cf16b0a4..0250d9fe2 100644
--- a/cyberdrop_dl/managers/db_manager.py
+++ b/cyberdrop_dl/managers/db_manager.py
@@ -30,18 +30,15 @@ class DBManager:
async def startup(self) -> None:
"""Startup process for the DBManager."""
self._db_conn = await aiosqlite.connect(self._db_path)
+ self._db_conn.row_factory = aiosqlite.Row
self.ignore_history = self.manager.config_manager.settings_data.runtime_options.ignore_history
- self.history_table = HistoryTable(self._db_conn)
- self.hash_table = HashTable(self._db_conn)
- self.temp_referer_table = TempRefererTable(self._db_conn)
-
- self.history_table.ignore_history = self.ignore_history
- self.temp_referer_table.ignore_history = self.ignore_history
+ self.history_table = HistoryTable(self)
+ self.hash_table = HashTable(self)
+ self.temp_referer_table = TempRefererTable(self)
await self._pre_allocate()
-
await self.history_table.startup()
await self.hash_table.startup()
await self.temp_referer_table.startup()
@@ -59,19 +56,17 @@ class DBManager:
async def _pre_allocate(self) -> None:
"""We pre-allocate 100MB of space to the SQL file just in case the user runs out of disk space."""
- create_pre_allocation_table = "CREATE TABLE IF NOT EXISTS t(x);"
- drop_pre_allocation_table = "DROP TABLE t;"
- fill_pre_allocation = "INSERT INTO t VALUES(zeroblob(100*1024*1024));" # 100 mb
- check_pre_allocation = "PRAGMA freelist_count;"
+ pre_allocate_script = (
+ "CREATE TABLE IF NOT EXISTS t(x);"
+ "INSERT INTO t VALUES(zeroblob(100*1024*1024));" # 100 MB
+ "DROP TABLE t;"
+ )
- result = await self._db_conn.execute(check_pre_allocation)
- free_space = await result.fetchone()
+ free_pages_query = "PRAGMA freelist_count;"
+ cursor = await self._db_conn.execute(free_pages_query)
+ free_space = await cursor.fetchone()
if free_space and free_space[0] <= 1024:
- await self._db_conn.execute(create_pre_allocation_table)
- await self._db_conn.commit()
- await self._db_conn.execute(fill_pre_allocation)
- await self._db_conn.commit()
- await self._db_conn.execute(drop_pre_allocation_table)
+ await self._db_conn.executescript(pre_allocate_script)
await self._db_conn.commit()
diff --git a/cyberdrop_dl/ui/program_ui.py b/cyberdrop_dl/ui/program_ui.py
index 6051efe32..a22b0cd94 100644
--- a/cyberdrop_dl/ui/program_ui.py
+++ b/cyberdrop_dl/ui/program_ui.py
@@ -305,8 +305,7 @@ def vacuum_database(db_path: Path) -> None:
conn = None
try:
conn = sqlite3.connect(db_path)
- cursor = conn.cursor()
- cursor.execute("VACUUM")
+ conn.execute("VACUUM")
conn.commit()
finally:
if conn:
diff --git a/cyberdrop_dl/utils/database/tables/hash_table.py b/cyberdrop_dl/utils/database/tables/hash_table.py
index 3fcdee0b6..d4c1baab1 100644
--- a/cyberdrop_dl/utils/database/tables/hash_table.py
+++ b/cyberdrop_dl/utils/database/tables/hash_table.py
@@ -3,31 +3,31 @@ from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING, cast
-from rich.console import Console
-
from cyberdrop_dl.utils.database.table_definitions import create_files, create_hash
+from cyberdrop_dl.utils.logger import log
if TYPE_CHECKING:
import aiosqlite
from yarl import URL
-console = Console()
+ from cyberdrop_dl.managers.db_manager import DBManager
class HashTable:
- def __init__(self, db_conn: aiosqlite.Connection) -> None:
- self.db_conn: aiosqlite.Connection = db_conn
+ def __init__(self, database: DBManager) -> None:
+ self._database = database
+
+ @property
+ def db_conn(self) -> aiosqlite.Connection:
+ return self._database._db_conn
async def startup(self) -> None:
"""Startup process for the HistoryTable."""
- await self.create_hash_tables()
-
- async def create_hash_tables(self) -> None:
await self.db_conn.execute(create_files)
await self.db_conn.execute(create_hash)
await self.db_conn.commit()
- async def get_file_hash_exists(self, full_path: Path | str, hash_type: str) -> str | None:
+ async def get_file_hash_exists(self, path: Path | str, hash_type: str) -> str | None:
"""gets the hash from a complete file path
Args:
@@ -36,26 +36,21 @@ class HashTable:
Returns:
hash if exists
"""
+ query = "SELECT hash FROM hash WHERE folder=? AND download_filename=? AND hash_type=? AND hash IS NOT NULL"
try:
- # Extract folder, filename, and size from the full pathg
- path = Path(full_path).absolute()
+ path = Path(path)
+ if not path.is_absolute():
+ path = path.absolute()
folder = str(path.parent)
- filename = str(path.name)
-
- # Connect to the database
- cursor = await self.db_conn.cursor()
+ filename = path.name
# Check if the file exists with matching folder, filename, and size
- await cursor.execute(
- "SELECT hash FROM hash WHERE folder=? AND download_filename=? AND hash_type=? AND hash IS NOT NULL",
- (folder, filename, hash_type),
- )
- result = await cursor.fetchone()
- if result:
- return result[0]
+ cursor = await self.db_conn.execute(query, (folder, filename, hash_type))
+ if row := await cursor.fetchone():
+ return row[0]
+
except Exception as e:
- console.print(f"Error checking file: {e}")
- return None
+ log(f"Error checking file: {e}", 40, exc_info=e)
async def get_files_with_hash_matches(
self, hash_value: str, size: int, hash_type: str | None = None
@@ -69,19 +64,26 @@ class HashTable:
Returns:
A list of (folder, filename) tuples, or an empty list if no matches found.
"""
+ if hash_type:
+ query = """
+ SELECT files.folder, files.download_filename,files.date
+ FROM hash JOIN files ON hash.folder = files.folder AND hash.download_filename = files.download_filename
+ WHERE hash.hash = ? AND files.file_size = ? AND hash.hash_type = ?;
+ """
- try:
- cursor = await self.db_conn.cursor()
- if hash_type:
- query = "SELECT files.folder, files.download_filename,files.date FROM hash JOIN files ON hash.folder = files.folder AND hash.download_filename = files.download_filename WHERE hash.hash = ? AND files.file_size = ? AND hash.hash_type = ?;"
+ else:
+ query = """
+ SELECT files.folder, files.download_filename FROM hash JOIN files
+ ON hash.folder = files.folder AND hash.download_filename = files.download_filename
+ WHERE hash.hash = ? AND files.file_size = ? AND hash.hash_type = ?;
+ """
- else:
- query = "SELECT files.folder, files.download_filename FROM hash JOIN files ON hash.folder = files.folder AND hash.download_filename = files.download_filename WHERE hash.hash = ? AND files.file_size = ? AND hash.hash_type = ?;"
- await cursor.execute(query, (hash_value, size, hash_type))
+ try:
+ cursor = await self.db_conn.execute(query, (hash_value, size, hash_type))
return cast("list[aiosqlite.Row]", await cursor.fetchall())
except Exception as e:
- console.print(f"Error retrieving folder and filename: {e}")
+ log(f"Error retrieving folder and filename: {e}", 40, exc_info=e)
return []
async def insert_or_update_hash_db(
@@ -105,57 +107,60 @@ class HashTable:
return file_ and hash
async def insert_or_update_hashes(self, hash_value: str, hash_type: str, file: Path | str) -> bool:
+ query = """
+ INSERT INTO hash (hash, hash_type, folder, download_filename)
+ VALUES (?, ?, ?, ?) ON CONFLICT(download_filename, folder, hash_type) DO UPDATE SET hash = ?;
+ """
+
try:
- full_path = Path(file).absolute()
- download_filename = str(full_path.name)
+ full_path = Path(file)
+ if not full_path.is_absolute():
+ full_path = full_path.absolute()
+ download_filename = full_path.name
folder = str(full_path.parent)
- cursor = await self.db_conn.cursor()
- insert_query = """INSERT INTO hash (hash, hash_type, folder, download_filename)
- VALUES (?, ?, ?, ?)
- ON CONFLICT(download_filename, folder, hash_type) DO UPDATE SET hash = ?"""
- await cursor.execute(insert_query, (hash_value, hash_type, folder, download_filename, hash_value))
+ await self.db_conn.execute(query, (hash_value, hash_type, folder, download_filename, hash_value))
await self.db_conn.commit()
except Exception as e:
- console.print(f"Error inserting/updating record: {e}")
+ log(f"Error inserting/updating record: {e}", 40, exc_info=e)
return False
return True
async def insert_or_update_file(
self, original_filename: str | None, referer: URL | str | None, file: Path | str
) -> bool:
+ query = """
+ INSERT INTO files (folder, original_filename, download_filename, file_size, referer, date)
+ VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(download_filename, folder)
+ DO UPDATE SET original_filename = ?, file_size = ?, referer = ?, date = ?;
+ """
+ referer_ = str(referer) if referer else None
try:
- referer = str(referer) if referer else None
- full_path = Path(file).absolute()
- file_size = int(full_path.stat().st_size)
- file_date = int(full_path.stat().st_mtime)
- download_filename = str(full_path.name)
+ full_path = Path(file)
+ if not full_path.is_absolute():
+ full_path = full_path.absolute()
+ download_filename = full_path.name
folder = str(full_path.parent)
-
- cursor = await self.db_conn.cursor()
- insert_query = """INSERT INTO files (folder, original_filename, download_filename, file_size, referer, date)
- VALUES (?, ?, ?, ?, ?, ?)
- ON CONFLICT(download_filename, folder) DO UPDATE
- SET original_filename = ?, file_size = ?, referer = ?, date = ?
- """
-
- await cursor.execute(
- insert_query,
+ stat = full_path.stat()
+ file_size = stat.st_size
+ file_date = int(stat.st_mtime)
+ await self.db_conn.execute(
+ query,
(
folder,
original_filename,
download_filename,
file_size,
- referer,
+ referer_,
file_date,
original_filename,
file_size,
- referer,
+ referer_,
file_date,
),
)
await self.db_conn.commit()
except Exception as e:
- console.print(f"Error inserting/updating record: {e}")
+ log(f"Error inserting/updating record: {e}", 40, exc_info=e)
return False
return True
@@ -169,18 +174,15 @@ class HashTable:
Returns:
A list of (folder, filename) tuples, or an empty list if no matches found.
"""
+ if hash_type:
+ query, params = "SELECT DISTINCT hash FROM hash WHERE hash_type =?", (hash_type,)
+
+ else:
+ query, params = "SELECT DISTINCT hash FROM hash", ()
try:
- cursor = await self.db_conn.cursor()
-
- if hash_type:
- await cursor.execute(
- "SELECT DISTINCT hash FROM hash WHERE hash_type =?",
- (hash_type,),
- )
- else:
- await cursor.execute("SELECT DISTINCT hash FROM hash")
- results = await cursor.fetchall()
- return [x[0] for x in results]
+ cursor = await self.db_conn.execute(query, params)
+ rows = await cursor.fetchall()
+ return [row[0] for row in rows]
except Exception as e:
- console.print(f"Error retrieving folder and filename: {e}")
+ log(f"Error retrieving folder and filename: {e}", 40, exc_info=e)
return []
diff --git a/cyberdrop_dl/utils/database/tables/history_table.py b/cyberdrop_dl/utils/database/tables/history_table.py
index e9a0a0a36..9646354ba 100644
--- a/cyberdrop_dl/utils/database/tables/history_table.py
+++ b/cyberdrop_dl/utils/database/tables/history_table.py
@@ -1,28 +1,20 @@
from __future__ import annotations
-import pathlib
from sqlite3 import IntegrityError, Row
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, cast
from cyberdrop_dl.utils.database.table_definitions import create_fixed_history, create_history
from cyberdrop_dl.utils.utilities import log
if TYPE_CHECKING:
import datetime
- from collections.abc import Iterable
import aiosqlite
from yarl import URL
from cyberdrop_dl.crawlers import Crawler
from cyberdrop_dl.data_structures.url_objects import MediaItem
-
-DB_UPDATES = (
- "UPDATE OR REPLACE media SET domain = 'jpg5.su' WHERE domain = 'sharex'",
- "UPDATE OR REPLACE media SET domain = 'nudostar.tv' WHERE domain = 'nudostartv'",
- "UPDATE OR REPLACE media SET referer = FIX_REDGIFS_REFERER(referer) WHERE domain = 'redgifs';",
- "UPDATE OR REPLACE media SET referer = FIX_JPG5_REFERER(referer) WHERE domain = 'jpg5.su';",
-)
+ from cyberdrop_dl.managers.db_manager import DBManager
def get_db_path(url: URL, domain: str = "") -> str:
@@ -44,9 +36,12 @@ def get_db_path(url: URL, domain: str = "") -> str:
class HistoryTable:
- def __init__(self, db_conn: aiosqlite.Connection) -> None:
- self.db_conn: aiosqlite.Connection = db_conn
- self.ignore_history: bool = False
+ def __init__(self, database: DBManager) -> None:
+ self._database = database
+
+ @property
+ def db_conn(self) -> aiosqlite.Connection:
+ return self._database._db_conn
async def startup(self) -> None:
"""Startup process for the HistoryTable."""
@@ -62,110 +57,124 @@ class HistoryTable:
async def update_previously_unsupported(self, crawlers: dict[str, Crawler]) -> None:
"""Update old `no_crawler` entries that are now supported."""
- domains_to_update = [
- (c.DOMAIN, f"http%{c.PRIMARY_URL.host}%") for c in crawlers.values() if c.UPDATE_UNSUPPORTED
- ]
+ domains_to_update = {
+ crawler.DOMAIN: f"http%{crawler.PRIMARY_URL.host}%"
+ for crawler in crawlers.values()
+ if crawler.UPDATE_UNSUPPORTED
+ }
if not domains_to_update:
return
- referers = [(d[1],) for d in domains_to_update]
- cursor = await self.db_conn.cursor()
+
query = "UPDATE OR IGNORE media SET domain = ? WHERE domain = 'no_crawler' AND referer LIKE ?"
- await cursor.executemany(query, domains_to_update)
+ cursor = await self.db_conn.executemany(query, domains_to_update.items())
query = "DELETE FROM media WHERE domain = 'no_crawler' AND referer LIKE ?"
- await cursor.executemany(query, referers)
+ await cursor.executemany(query, [[x] for x in domains_to_update.values()])
await self.db_conn.commit()
async def run_updates(self) -> None:
- cursor = await self.db_conn.cursor()
- for query in DB_UPDATES:
- await cursor.execute(query)
+ updates = (
+ "UPDATE OR REPLACE media SET domain = 'jpg5.su' WHERE domain = 'sharex';"
+ "UPDATE OR REPLACE media SET domain = 'nudostar.tv' WHERE domain = 'nudostartv';"
+ "UPDATE OR REPLACE media SET referer = FIX_REDGIFS_REFERER(referer) WHERE domain = 'redgifs';"
+ "UPDATE OR REPLACE media SET referer = FIX_JPG5_REFERER(referer) WHERE domain = 'jpg5.su';"
+ )
+
+ await self.db_conn.executescript(updates)
await self.db_conn.commit()
async def delete_invalid_rows(self) -> None:
- query = """DELETE FROM media WHERE download_filename = '' """
- cursor = await self.db_conn.cursor()
- await cursor.execute(query)
+ query = "DELETE FROM media WHERE download_filename = '' "
+ await self.db_conn.execute(query)
await self.db_conn.commit()
async def check_complete(self, domain: str, url: URL, referer: URL) -> bool:
"""Checks whether an individual file has completed given its domain and url path."""
- if self.ignore_history:
+ if self._database.ignore_history:
return False
url_path = get_db_path(url, domain)
- cursor = await self.db_conn.cursor()
- query = """SELECT referer, completed FROM media WHERE domain = ? and url_path = ?"""
- result = await cursor.execute(query, (domain, url_path))
- sql_file_check = await result.fetchone()
- if sql_file_check and sql_file_check[1] != 0:
+
+ async def select_referer_and_completed() -> tuple[str, bool]:
+ query = "SELECT referer, completed FROM media WHERE domain = ? and url_path = ?"
+ cursor = await self.db_conn.execute(query, (domain, url_path))
+ if row := await cursor.fetchone():
+ return row[0], row[1]
+ return "", False
+
+ async def update_referer() -> None:
+ query = "UPDATE media SET referer = ? WHERE domain = ? and url_path = ?"
+ await self.db_conn.execute(query, (str(referer), domain, url_path))
+ await self.db_conn.commit()
+
+ current_referer, completed = await select_referer_and_completed()
+ if completed and url != referer and str(referer) != current_referer:
# Update the referer if it has changed so that check_complete_by_referer can work
- if str(referer) != sql_file_check[0] and url != referer:
- log(f"Updating referer of {url} from {sql_file_check[0]} to {referer}")
- query = """UPDATE media SET referer = ? WHERE domain = ? and url_path = ?"""
- await cursor.execute(query, (str(referer), domain, url_path))
- await self.db_conn.commit()
+ log(f"Updating referer of {url} from {current_referer} to {referer}")
+ await update_referer()
- return True
- return False
+ return completed
async def check_album(self, domain: str, album_id: str) -> dict[str, int]:
"""Checks whether an album has completed given its domain and album id."""
- if self.ignore_history:
+ if self._database.ignore_history:
return {}
- cursor = await self.db_conn.cursor()
- result = await cursor.execute(
- """SELECT url_path, completed FROM media WHERE domain = ? and album_id = ?""",
- (domain, album_id),
- )
- result = await result.fetchall()
- return {row[0]: row[1] for row in result}
+ query = "SELECT url_path, completed FROM media WHERE domain = ? and album_id = ?"
+ cursor = await self.db_conn.execute(query, (domain, album_id))
+ rows = await cursor.fetchall()
+ return {row[0]: row[1] for row in rows}
async def set_album_id(self, domain: str, media_item: MediaItem) -> None:
"""Sets an album_id in the database."""
url_path = get_db_path(media_item.url, str(media_item.referer))
- await self.db_conn.execute(
- """UPDATE media SET album_id = ? WHERE domain = ? and url_path = ?""",
- (media_item.album_id, domain, url_path),
- )
+ query = "UPDATE media SET album_id = ? WHERE domain = ? and url_path = ?"
+ await self.db_conn.execute(query, (media_item.album_id, domain, url_path))
await self.db_conn.commit()
async def check_complete_by_referer(self, domain: str | None, referer: URL) -> bool:
"""Checks whether an individual file has completed given its domain and url path."""
- if self.ignore_history:
+ if self._database.ignore_history:
return False
+
if domain is None:
- query, *params = "SELECT completed FROM media WHERE referer = ?", str(referer)
+ query = "SELECT completed FROM media WHERE referer = ?"
+ params = (str(referer),)
else:
- query, *params = "SELECT completed FROM media WHERE referer = ? and domain = ?", str(referer), domain
+ query = "SELECT completed FROM media WHERE referer = ? and domain = ?"
+ params = str(referer), domain
- cursor = await self.db_conn.cursor()
- result = await cursor.execute(query, params)
+ cursor = await self.db_conn.execute(query, params)
if domain is None:
- results = await result.fetchall()
+ rows = await cursor.fetchall()
else:
- row = await result.fetchone()
- results = [row] if row is not None else []
- return bool(results and any(row[0] != 0 for row in results))
+ row = await cursor.fetchone()
+ if row is None:
+ return False
+ rows = [row]
+ return bool(rows and any(row[0] != 0 for row in rows))
async def insert_incompleted(self, domain: str, media_item: MediaItem) -> None:
"""Inserts an uncompleted file into the database."""
url_path = get_db_path(media_item.url, str(media_item.referer))
download_filename = media_item.download_filename or ""
+ cursor = await self.db_conn.cursor()
+ query = "UPDATE media SET domain = ?, album_id = ? WHERE domain = 'no_crawler' and url_path = ? and referer = ?"
try:
- await self.db_conn.execute(
- """UPDATE media SET domain = ?, album_id = ? WHERE domain = 'no_crawler' and url_path = ? and referer = ?""",
- (domain, media_item.album_id, url_path, str(media_item.referer)),
- )
+ await cursor.execute(query, (domain, media_item.album_id, url_path, str(media_item.referer)))
except IntegrityError:
- await self.db_conn.execute(
- """DELETE FROM media WHERE domain = 'no_crawler' and url_path = ?""",
- (url_path,),
- )
- await self.db_conn.execute(
- """INSERT OR IGNORE INTO media (domain, url_path, referer, album_id, download_path, download_filename, original_filename, completed, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)""",
+ delete_query = "DELETE FROM media WHERE domain = 'no_crawler' and url_path = ?"
+ await cursor.execute(delete_query, (url_path,))
+
+ insert_query = """
+ INSERT OR IGNORE INTO media (domain, url_path, referer, album_id, download_path,
+ download_filename, original_filename, completed, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP);
+ """
+
+ await cursor.execute(
+ insert_query,
(
domain,
url_path,
@@ -178,181 +187,165 @@ class HistoryTable:
),
)
if download_filename:
- await self.db_conn.execute(
- """UPDATE media SET download_filename = ? WHERE domain = ? and url_path = ?""",
- (download_filename, domain, url_path),
- )
+ query = "UPDATE media SET download_filename = ? WHERE domain = ? and url_path = ?"
+ await cursor.execute(query, (download_filename, domain, url_path))
await self.db_conn.commit()
async def mark_complete(self, domain: str, media_item: MediaItem) -> None:
"""Mark a download as completed in the database."""
url_path = get_db_path(media_item.url, str(media_item.referer))
- await self.db_conn.execute(
- """UPDATE media SET completed = 1, completed_at = CURRENT_TIMESTAMP WHERE domain = ? and url_path = ?""",
- (domain, url_path),
- )
+ query = "UPDATE media SET completed = 1, completed_at = CURRENT_TIMESTAMP WHERE domain = ? and url_path = ?"
+ await self.db_conn.execute(query, (domain, url_path))
await self.db_conn.commit()
async def add_filesize(self, domain: str, media_item: MediaItem) -> None:
- """Add the file size to the db."""
+ """Adds the file size to the db."""
url_path = get_db_path(media_item.url, str(media_item.referer))
- file_size = pathlib.Path(media_item.complete_file).stat().st_size
- await self.db_conn.execute(
- """UPDATE media SET file_size=? WHERE domain = ? and url_path = ?""",
- (file_size, domain, url_path),
- )
+ file_size = media_item.complete_file.stat().st_size
+ query = """UPDATE media SET file_size=? WHERE domain = ? and url_path = ?"""
+ await self.db_conn.execute(query, (file_size, domain, url_path))
await self.db_conn.commit()
async def add_duration(self, domain: str, media_item: MediaItem) -> None:
- """Add the file size to the db."""
+ """Adds the duration to the db."""
url_path = get_db_path(media_item.url, str(media_item.referer))
- duration = media_item.duration
- await self.db_conn.execute(
- """UPDATE media SET duration=? WHERE domain = ? and url_path = ?""",
- (duration, domain, url_path),
- )
+ query = "UPDATE media SET duration=? WHERE domain = ? and url_path = ?"
+ await self.db_conn.execute(query, (media_item.duration, domain, url_path))
await self.db_conn.commit()
async def get_duration(self, domain: str, media_item: MediaItem) -> float | None:
"""Returns the duration from the database."""
if media_item.is_segment:
return
+
url_path = get_db_path(media_item.url, str(media_item.referer))
- cursor = await self.db_conn.cursor()
- result = await cursor.execute(
- """SELECT duration FROM media WHERE domain = ? and url_path = ?""",
- (domain, url_path),
- )
- sql_duration = await result.fetchone()
- return sql_duration[0] if sql_duration else None
+ query = "SELECT duration FROM media WHERE domain = ? and url_path = ?"
+ cursor = await self.db_conn.execute(query, (domain, url_path))
+ if row := await cursor.fetchone():
+ return row[0]
async def add_download_filename(self, domain: str, media_item: MediaItem) -> None:
"""Add the download_filename to the db."""
url_path = get_db_path(media_item.url, str(media_item.referer))
- query = """UPDATE media SET download_filename=? WHERE domain = ? and url_path = ? and download_filename = '' """
+ query = "UPDATE media SET download_filename=? WHERE domain = ? and url_path = ? and download_filename = ''"
await self.db_conn.execute(query, (media_item.download_filename, domain, url_path))
await self.db_conn.commit()
async def check_filename_exists(self, filename: str) -> bool:
"""Checks whether a downloaded filename exists in the database."""
- cursor = await self.db_conn.cursor()
- result = await cursor.execute("""SELECT EXISTS(SELECT 1 FROM media WHERE download_filename = ?)""", (filename,))
- sql_file_check = await result.fetchone()
- return sql_file_check == 1
+ query = "SELECT EXISTS(SELECT 1 FROM media WHERE download_filename = ?)"
+ cursor = await self.db_conn.execute(query, (filename,))
+ row = await cursor.fetchone()
+ # TODO: this is a bug. It should check the first index
+ return row == 1
async def get_downloaded_filename(self, domain: str, media_item: MediaItem) -> str | None:
"""Returns the downloaded filename from the database."""
if media_item.is_segment:
return media_item.filename
+
url_path = get_db_path(media_item.url, str(media_item.referer))
- cursor = await self.db_conn.cursor()
- result = await cursor.execute(
- """SELECT download_filename FROM media WHERE domain = ? and url_path = ?""",
- (domain, url_path),
- )
- sql_file_check = await result.fetchone()
- return sql_file_check[0] if sql_file_check else None
+ query = "SELECT download_filename FROM media WHERE domain = ? and url_path = ?"
+ cursor = await self.db_conn.execute(query, (domain, url_path))
+ if row := await cursor.fetchone():
+ return row[0]
- async def get_failed_items(self) -> Iterable[Row]:
+ async def get_failed_items(self) -> list[Row]:
"""Returns a list of failed items."""
- cursor = await self.db_conn.cursor()
- result = await cursor.execute(
- """SELECT referer, download_path,completed_at,created_at FROM media WHERE completed = 0""",
- )
- return await result.fetchall()
+ query = "SELECT referer, download_path,completed_at,created_at FROM media WHERE completed = 0"
+ cursor = await self.db_conn.execute(query)
+ return cast("list[Row]", await cursor.fetchall())
- async def get_all_items(self, after: datetime.date, before: datetime.date) -> Iterable[Row]:
+ async def get_all_items(self, after: datetime.date, before: datetime.date) -> list[Row]:
"""Returns a list of all items."""
- cursor = await self.db_conn.cursor()
- result = await cursor.execute(
- """
- SELECT referer, download_path,completed_at,created_at
- FROM media
- WHERE COALESCE(completed_at, '1970-01-01') BETWEEN ? AND ?
- ORDER BY completed_at DESC;""",
- (after.strftime("%Y-%m-%d"), before.strftime("%Y-%m-%d")),
- )
- return await result.fetchall()
-
- async def get_unique_download_paths(self) -> Iterable[Row]:
+ query = """
+ SELECT referer,download_path,completed_at,created_at
+ FROM media WHERE COALESCE(completed_at, '1970-01-01') BETWEEN ? AND ?
+ ORDER BY completed_at DESC;
+ """
+ cursor = await self.db_conn.execute(query, (after.isoformat(), before.isoformat()))
+ return cast("list[Row]", await cursor.fetchall())
+
+ async def get_unique_download_paths(self) -> list[Row]:
"""Returns a list of unique download paths."""
- cursor = await self.db_conn.cursor()
- result = await cursor.execute("""SELECT DISTINCT download_path FROM media""")
- return await result.fetchall()
+ query = "SELECT DISTINCT download_path FROM media"
+ cursor = await self.db_conn.execute(query)
+ return cast("list[Row]", await cursor.fetchall())
- async def get_all_bunkr_failed(self) -> list:
+ async def get_all_bunkr_failed(self) -> list[Row]:
+ # TODO: Make this one a generator instead of combining both lists.
+ # These lists can be huge
hash_list = await self.get_all_bunkr_failed_via_hash()
size_list = await self.get_all_bunkr_failed_via_size()
return hash_list + size_list
async def get_all_bunkr_failed_via_size(self) -> list:
+ query = "SELECT referer,download_path,completed_at,created_at from media WHERE file_size=322509;"
try:
- """Returns a list of all items"""
- cursor = await self.db_conn.cursor()
- result = await cursor.execute("""
- SELECT referer,download_path,completed_at,created_at
- from media
- where file_size=322509
- ;
- """)
- all_files = await result.fetchall()
- return list(all_files)
+ cursor = await self.db_conn.execute(query)
+ return cast("list[Row]", await cursor.fetchall())
+
except Exception as e:
log(f"Error getting bunkr failed via size: {e}", 40, exc_info=e)
return []
async def get_all_bunkr_failed_via_hash(self) -> list:
+ query = """
+ SELECT m.referer,download_path,completed_at,created_at
+ FROM hash h INNER JOIN media m ON h.download_filename= m.download_filename
+ WHERE h.hash = 'eb669b6362e031fa2b0f1215480c4e30';
+ """
+
try:
- """Returns a list of all items"""
- cursor = await self.db_conn.cursor()
- result = await cursor.execute("""
- SELECT m.referer,download_path,completed_at,created_at
- FROM hash h
- INNER JOIN media m ON h.download_filename= m.download_filename
- WHERE h.hash = 'eb669b6362e031fa2b0f1215480c4e30';
- """)
- all_files = await result.fetchall()
- return list(all_files)
+ cursor = await self.db_conn.execute(query)
+ return cast("list[Row]", await cursor.fetchall())
except Exception as e:
log(f"Error getting bunkr failed via hash: {e}", 40, exc_info=e)
return []
async def fix_primary_keys(self) -> None:
- cursor = await self.db_conn.cursor()
- result = await cursor.execute("""pragma table_info(media)""")
- result = await result.fetchall()
- if result[0][5] == 0: # type: ignore
- await self.db_conn.execute(create_fixed_history)
- await self.db_conn.commit()
+ domain_column, *_ = await self._get_media_table_columns()
+ domain_is_primary_key: bool = domain_column["pk"] != 0
+ if domain_is_primary_key:
+ return
- await self.db_conn.execute(
- """INSERT INTO media_copy (domain, url_path, referer, download_path, download_filename, original_filename, completed) SELECT * FROM media GROUP BY domain, url_path, original_filename;""",
- )
- await self.db_conn.commit()
+ await self.db_conn.execute(create_fixed_history)
+ await self.db_conn.commit()
+ script = """
+ INSERT INTO media_copy (domain, url_path, referer, download_path,
+ download_filename, original_filename, completed)
+ SELECT * FROM media GROUP BY domain, url_path, original_filename;
+ DROP TABLE media;
+ ALTER TABLE media_copy RENAME TO media;
+ """
+ await self.db_conn.executescript(script)
+ await self.db_conn.commit()
- await self.db_conn.execute("""DROP TABLE media""")
- await self.db_conn.commit()
-
- await self.db_conn.execute("""ALTER TABLE media_copy RENAME TO media""")
- await self.db_conn.commit()
+ async def _get_media_table_columns(self) -> list[Row]:
+ query = "pragma table_info(media)"
+ cursor = await self.db_conn.execute(query)
+ return cast("list[Row]", await cursor.fetchall())
async def add_columns_media(self) -> None:
- cursor = await self.db_conn.cursor()
- result = await cursor.execute("""pragma table_info(media)""")
- result = await result.fetchall()
- current_cols = [col[1] for col in result]
-
- async def add_column(name: str, type_: str) -> None:
- if name not in current_cols:
- await self.db_conn.execute(f"ALTER TABLE media ADD COLUMN {name} {type_}")
- await self.db_conn.commit()
-
- await add_column("album_id", "TEXT")
- await add_column("created_at", "TIMESTAMP")
- await add_column("completed_at", "TIMESTAMP")
- await add_column("file_size", "INT")
- await add_column("duration", "FLOAT")
+ columns = await self._get_media_table_columns()
+ current_column_names: tuple[str, ...] = tuple(col["name"] for col in columns)
+ new_columns = (
+ ("album_id", "TEXT"),
+ ("created_at", "TIMESTAMP"),
+ ("completed_at", "TIMESTAMP"),
+ ("file_size", "INT"),
+ ("duration", "FLOAT"),
+ )
+
+ script = ""
+ for name, type_ in new_columns:
+ if name not in current_column_names:
+ script += f"ALTER TABLE media ADD COLUMN {name} {type_};"
+
+ if script:
+ await self.db_conn.executescript(script)
+ await self.db_conn.commit()
diff --git a/cyberdrop_dl/utils/database/tables/temp_referer_table.py b/cyberdrop_dl/utils/database/tables/temp_referer_table.py
index 33a7d0a4f..54ed09f5d 100644
--- a/cyberdrop_dl/utils/database/tables/temp_referer_table.py
+++ b/cyberdrop_dl/utils/database/tables/temp_referer_table.py
@@ -9,12 +9,16 @@ if TYPE_CHECKING:
from yarl import URL
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
+ from cyberdrop_dl.managers.db_manager import DBManager
class TempRefererTable:
- def __init__(self, db_conn: aiosqlite.Connection) -> None:
- self.db_conn: aiosqlite.Connection = db_conn
- self.ignore_history: bool = False
+ def __init__(self, database: DBManager) -> None:
+ self._database = database
+
+ @property
+ def db_conn(self) -> aiosqlite.Connection:
+ return self._database._db_conn
async def startup(self) -> None:
"""Startup process for the TempRefererTable."""
@@ -23,49 +27,52 @@ class TempRefererTable:
async def get_temp_referers(self) -> list[str]:
"""Gets the list of temp referers."""
- cursor = await self.db_conn.cursor()
- await cursor.execute("SELECT referer FROM temp_referer;")
- referers = await cursor.fetchall()
- referers = [list(referer) for referer in referers]
- return list(sum(referers, ()))
+ query = "SELECT referer FROM temp_referer;"
+ cursor = await self.db_conn.execute(query)
+ rows = await cursor.fetchall()
+ return [row[0] for row in rows]
async def sql_insert_temp_referer(self, referer: str) -> None:
"""Inserts a temp referer into the temp_referers table."""
- await self.db_conn.execute("""INSERT OR IGNORE INTO temp_referer VALUES (?)""", (referer,))
+ query = "INSERT OR IGNORE INTO temp_referer VALUES (?)"
+ await self.db_conn.execute(query, (referer,))
await self.db_conn.commit()
async def sql_purge_temp_referers(self) -> None:
"""Delete all records in temp_referers table."""
- await self.db_conn.execute("""DELETE FROM temp_referer;""")
+ query = "DELETE FROM temp_referer;"
+ await self.db_conn.execute(query)
await self.db_conn.commit()
async def sql_drop_temp_referers(self) -> None:
"""Delete temp_referers table."""
- await self.db_conn.execute("""DROP TABLE IF EXISTS temp_referer""")
+ query = "DROP TABLE IF EXISTS temp_referer"
+ await self.db_conn.execute(query)
await self.db_conn.commit()
async def check_referer(self, referer: AbsoluteHttpURL) -> bool:
"""Checks whether an individual referer url has already been recorded in the database."""
- if self.ignore_history:
+ if self._database.ignore_history:
return False
referer_str = str(referer)
- cursor = await self.db_conn.cursor()
- result = await cursor.execute("""SELECT url_path FROM media WHERE referer = ? """, (referer_str,))
- sql_referer_check = await result.fetchone()
- sql_referer_check_current_run = await self._check_temp_referer(referer)
- if not sql_referer_check:
+ # TODO: This logic is broken
+ query = "SELECT url_path FROM media WHERE referer = ?"
+ cursor = await self.db_conn.execute(query, (referer_str,))
+ in_media_table = await cursor.fetchone()
+ in_temp_referer = await self._check_temp_referer(referer)
+ if not in_media_table:
await self.sql_insert_temp_referer(referer_str)
return False
- return not sql_referer_check_current_run
+
+ return not in_temp_referer
async def _check_temp_referer(self, referer: URL) -> bool:
"""Checks whether an individual referer url has already been recorded in this session."""
- if self.ignore_history:
+ if self._database.ignore_history:
return False
- cursor = await self.db_conn.cursor()
- result = await cursor.execute("""SELECT referer FROM temp_referer WHERE referer = ? """, (str(referer),))
- sql_referer_check = await result.fetchone()
- return bool(sql_referer_check)
+ query = "SELECT referer FROM temp_referer WHERE referer = ?"
+ cursor = await self.db_conn.execute(query, (str(referer),))
+ return bool(await cursor.fetchone())