Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: modifications to transfer to new hash table process => create backups and simplify (#341)

datawhores0e4e888edab5
diff --git a/cyberdrop_dl/managers/manager.py b/cyberdrop_dl/managers/manager.py
index 132e05756..fe9d833b0 100644
--- a/cyberdrop_dl/managers/manager.py
+++ b/cyberdrop_dl/managers/manager.py
@@ -21,7 +21,7 @@ from cyberdrop_dl.managers.realdebrid_manager import RealDebridManager
from cyberdrop_dl.utils.args import ParsedArgs
from cyberdrop_dl.utils.data_enums_classes.supported_domains import SupportedForums
from cyberdrop_dl.utils.logger import log
-from cyberdrop_dl.utils.transfer.first_time_setup import TransitionManager
+from cyberdrop_dl.utils.transfer.db_setup import TransitionManager
if TYPE_CHECKING:
from asyncio import TaskGroup
@@ -66,10 +66,12 @@ class Manager:
self.parsed_args = ParsedArgs.parse_args()
if not self.parsed_args.cli_only_args.appdata_folder:
- self.first_time_setup.startup()
+ self.first_time_setup.transfer_v4_to_v5()
self.path_manager = PathManager(self)
self.path_manager.pre_startup()
+ # need pathmanager to get proper appdata location
+ self.first_time_setup.transfer_v5_to_new_hashtable()
self.cache_manager.startup(self.path_manager.cache_folder / "cache.yaml")
self.config_manager = ConfigManager(self)
diff --git a/cyberdrop_dl/utils/database/tables/hash_table.py b/cyberdrop_dl/utils/database/tables/hash_table.py
index 675162789..56ac73d67 100644
--- a/cyberdrop_dl/utils/database/tables/hash_table.py
+++ b/cyberdrop_dl/utils/database/tables/hash_table.py
@@ -1,14 +1,12 @@
from __future__ import annotations
-from datetime import datetime
from pathlib import Path
from sqlite3 import IntegrityError
from typing import TYPE_CHECKING
from rich.console import Console
-from cyberdrop_dl.utils.database.table_definitions import create_files, create_hash, create_temp_hash
-from cyberdrop_dl.utils.logger import log
+from cyberdrop_dl.utils.database.table_definitions import create_files, create_hash
if TYPE_CHECKING:
import aiosqlite
@@ -23,54 +21,13 @@ class HashTable:
async def startup(self) -> None:
"""Startup process for the HistoryTable."""
- await self.transer_old_hash_table()
await self.create_hash_tables()
- pass
async def create_hash_tables(self):
await self.db_conn.execute(create_files)
await self.db_conn.execute(create_hash)
await self.db_conn.commit()
- async def transer_old_hash_table(self):
- cursor = await self.db_conn.cursor()
- results = await cursor.execute("""pragma table_info(hash)""")
- results = await results.fetchall()
- if len(results) == 0:
- return
- if len(list(filter(lambda x: x[1] == "hash_type", results))) == 0:
- log("Migrating history database to new schema..")
- await cursor.execute(create_files)
- await cursor.execute(create_temp_hash)
- old_table_results = await cursor.execute(
- "SELECT * FROM hash",
- (),
- )
- for old_result in await old_table_results.fetchall():
- folder = old_result[0]
- dl_name = old_result[1]
- original_filename = old_result[2]
- size = old_result[3]
- hash = old_result[4]
- referer = old_result[5]
- hash_type = "md5"
- file_date = (
- int(Path(folder, dl_name).stat().st_mtime)
- if Path(folder, dl_name).exists()
- else int(int(datetime.now().timestamp()))
- )
- await cursor.execute(
- "INSERT OR IGNORE INTO files (folder, download_filename, original_filename, file_size, referer,date) VALUES (?,?,?,?,?,?);",
- (folder, dl_name, original_filename, size, referer, file_date),
- )
- await cursor.execute(
- "INSERT OR IGNORE INTO temp_hash (folder, download_filename, hash_type, hash) VALUES (?,?,?,?);",
- (folder, dl_name, hash_type, hash),
- )
- await cursor.execute("""DROP TABLE IF EXISTS hash""")
- await cursor.execute("ALTER TABLE temp_hash RENAME TO hash")
- await self.db_conn.commit()
-
async def get_file_hash_exists(self, full_path: Path | str, hash_type: str) -> str | None:
"""gets the hash from a complete file path
@@ -81,7 +38,7 @@ class HashTable:
hash if exists
"""
try:
- # Extract folder, filename, and size from the full path
+ # Extract folder, filename, and size from the full pathg
path = Path(full_path).absolute()
folder = str(path.parent)
filename = str(path.name)
diff --git a/cyberdrop_dl/utils/transfer/backup.py b/cyberdrop_dl/utils/transfer/backup.py
new file mode 100644
index 000000000..f70720693
--- /dev/null
+++ b/cyberdrop_dl/utils/transfer/backup.py
@@ -0,0 +1,8 @@
+from datetime import datetime
+from pathlib import Path
+from shutil import copy2
+
+
+def db_backup(db_file):
+ new_file = Path(db_file.parent, f"cyberdrop_v5_{datetime.now().strftime('%Y%m%d_%H%M%S')}.bak.db")
+ copy2(db_file, new_file)
diff --git a/cyberdrop_dl/utils/transfer/first_time_setup.py b/cyberdrop_dl/utils/transfer/db_setup.py
similarity index 95%
rename from cyberdrop_dl/utils/transfer/first_time_setup.py
rename to cyberdrop_dl/utils/transfer/db_setup.py
index d8b2000d1..c93ca4336 100644
--- a/cyberdrop_dl/utils/transfer/first_time_setup.py
+++ b/cyberdrop_dl/utils/transfer/db_setup.py
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING
import platformdirs
from cyberdrop_dl.utils import constants, yaml
+from cyberdrop_dl.utils.transfer.transfer_hash_db import transfer_from_old_hash_table
from cyberdrop_dl.utils.transfer.transfer_v4_db import transfer_v4_db
if TYPE_CHECKING:
@@ -17,8 +18,19 @@ class TransitionManager:
def __init__(self, manager: Manager) -> None:
self.manager = manager
- def startup(self) -> None:
- """Startup."""
+ def transfer_v5_to_new_hashtable(self):
+ """
+ transfers from old v5 hash table to new v5 hash table, that supports multiple hash types per file
+ """
+ db_path = constants.APP_STORAGE / "Cache" / "cyberdrop.db"
+ if db_path.exists():
+ transfer_from_old_hash_table(db_path)
+
+ def transfer_v4_to_v5(self):
+ """
+ Makes some changes for transfer from v4 to v5
+
+ """
OLD_APP_STORAGE = Path(platformdirs.user_config_dir("Cyberdrop-DL"))
OLD_DOWNLOAD_STORAGE = Path(platformdirs.user_downloads_path()) / "Cyberdrop-DL Downloads"
diff --git a/cyberdrop_dl/utils/transfer/transfer_hash_db.py b/cyberdrop_dl/utils/transfer/transfer_hash_db.py
new file mode 100644
index 000000000..2b7ff8945
--- /dev/null
+++ b/cyberdrop_dl/utils/transfer/transfer_hash_db.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import arrow
+from rich.console import Console
+
+from cyberdrop_dl.utils.database.table_definitions import create_files, create_temp_hash
+from cyberdrop_dl.utils.transfer.backup import db_backup
+from cyberdrop_dl.utils.transfer.wrapper import db_transfer_context
+
+console = Console()
+
+
+def transfer_from_old_hash_table(db_path):
+ """Transfers data from the old 'hash' table to new 'files' and 'temp_hash' tables, handling potential schema differences and errors.
+
+ Args:
+ self: The instance of the class containing this method.
+
+ Raises:
+ Exception: If a critical error
+ """
+
+ with db_transfer_context(db_path) as cursor:
+ # Check if the 'hash_type' column exists in the 'hash' table
+ cursor.execute("SELECT COUNT(*) FROM pragma_table_info('hash') WHERE name='hash_type'")
+ has_hash_type_column = (cursor.fetchone())[0] > 0
+ if has_hash_type_column:
+ return
+ db_backup(db_path)
+
+ # Fetch data from the old 'hash' table
+ cursor.execute("""
+ SELECT folder, download_filename, file_size, hash, original_filename, referer
+ FROM hash
+ """)
+ old_hash_data = cursor.fetchall()
+ # Drop existing 'files' and 'temp_hash' tables if they exist
+ cursor.execute("DROP TABLE IF EXISTS files")
+ cursor.execute("DROP TABLE IF EXISTS temp_hash")
+
+ # Create the 'temp_hash' table with the required schema
+ cursor.execute(create_temp_hash)
+ cursor.execute(create_files)
+
+ # Prepare data for insertion into 'files' and 'temp_hash' tables
+ data_to_insert_files = []
+ data_to_insert_hash = []
+ for row in old_hash_data:
+ folder, download_filename, file_size, hash, original_filename, referer = row
+
+ file_path = Path(folder, download_filename)
+ if file_path.exists():
+ file_date = int(file_path.stat().st_mtime)
+ else:
+ file_date = int(arrow.now().float_timestamp)
+
+ data_to_insert_files.append((folder, download_filename, original_filename, file_size, referer, file_date))
+ data_to_insert_hash.append((folder, download_filename, "md5", hash))
+
+ # Insert data into 'files' and 'temp_hash' tables
+ cursor.executemany(
+ "INSERT INTO files (folder, download_filename, original_filename, file_size, referer, date) VALUES (?, ?, ?, ?, ?, ?);",
+ data_to_insert_files,
+ )
+
+ cursor.executemany(
+ "INSERT INTO temp_hash (folder, download_filename, hash_type, hash) VALUES (?, ?, ?, ?);",
+ data_to_insert_hash,
+ )
+
+ # Drop the old 'hash' table
+ cursor.execute("DROP TABLE hash")
+
+ # Rename the 'temp_hash' table to 'hash'
+ cursor.execute("ALTER TABLE temp_hash RENAME TO hash")
diff --git a/cyberdrop_dl/utils/transfer/wrapper.py b/cyberdrop_dl/utils/transfer/wrapper.py
new file mode 100644
index 000000000..6e6842d92
--- /dev/null
+++ b/cyberdrop_dl/utils/transfer/wrapper.py
@@ -0,0 +1,17 @@
+import contextlib
+import sqlite3
+
+
+def db_transfer_context(db_file):
+ conn = sqlite3.connect(db_file)
+ cursor = conn.cursor()
+ try:
+ yield cursor
+ conn.commit() # commit changes if no exception occurs
+ except Exception as e:
+ conn.rollback()
+ raise e
+ finally:
+ cursor.close()
+ conn.close()