import sqlite3 import csv import os from datetime import datetime # Function to convert Linux path to Windows path and replace specific substring def convert_path(path): return path.replace("/", "\\").replace("\\data\\", "\\\\truenas\\isolation\\videos\\") # Fileshare path fileshare_path = r"\\truenas\isolation\stashapp\generated\transcodes" # SQLite database path db_path = r"\\servervm\main\appdata\stashapp\config\stash-go.sqlite" # Create a folder for the attempt with current date and time folder_name = "Attempt_" + datetime.now().strftime("%Y%m%d_%H%M%S") os.makedirs(folder_name) # Connect to SQLite database conn = sqlite3.connect(db_path) cursor = conn.cursor() # Error handling for gathering basenames try: # List all file basenames (without extensions) from fileshare path basenames = [os.path.splitext(name)[0] for name in os.listdir(fileshare_path)] except FileNotFoundError: print(f"Error: Fileshare path '{fileshare_path}' not found.") exit() except PermissionError: print(f"Error: Permission denied accessing fileshare path '{fileshare_path}'.") exit() # Check if there are no basenames if not basenames: print("Error: No basenames found in the fileshare path.") exit() # Construct the IN clause for the query placeholders = ",".join(['"{}"'.format(b) for b in basenames]) # Construct the query query_template = """ SELECT f.*, ff.*, fo.path FROM files AS f INNER JOIN files_fingerprints AS ff ON f.id = ff.file_id INNER JOIN folders AS fo ON f.parent_folder_id = fo.id WHERE ff.fingerprint IN ({}); """ # Execute query cursor.execute(query_template.format(placeholders)) rows = cursor.fetchall() # Check if there are any results if len(rows) == 0: print("No results found.") exit() # Export result to CSV csv_path = os.path.join(folder_name, "result.csv") with open(csv_path, "w", newline="", encoding="utf-8") as csv_file: csv_writer = csv.writer(csv_file) csv_writer.writerow([i[0] for i in cursor.description]) # Write header csv_writer.writerows(rows) # Create new CSV with additional columns new_rows = [] for row in rows: converted_path = convert_path(row[-1]) full_file_path_video = os.path.join(converted_path, row[1]) # Construct full file path for videos # Original filename from transcodes directory original_filename = os.path.join(fileshare_path, str(row[10])) # Assuming the fingerprint ID is in the 11th column (index 10) new_rows.append((full_file_path_video, original_filename + ".mp4")) # Append ".mp4" to the second column # Write new CSV new_csv_path = os.path.join(folder_name, "new_result.csv") with open(new_csv_path, "w", newline="", encoding="utf-8") as csv_file: csv_writer = csv.writer(csv_file) csv_writer.writerow(["Full File Path (Videos)", "Original File Path (Transcodes)"]) csv_writer.writerows(new_rows) # Confirm with the user print("CSV files created successfully in folder:", folder_name) print("Do you want to proceed to replace the files in column 1 with the files in column 2?") user_input = input("Enter 'yes' to proceed, or any other key to cancel: ") if user_input.lower() == 'yes': print("Proceeding to replace the files...") # Prepare to replace files for original_file, new_file in new_rows: original_basename = os.path.basename(original_file) original_dirname = os.path.dirname(original_file) new_basename = os.path.basename(new_file) new_dirname = os.path.dirname(new_file) # Remove existing file if exists if os.path.exists(original_file): os.remove(original_file) # Move the new file to replace the original file try: os.rename(new_file, os.path.join(original_dirname, original_basename)) print(f"Replaced '{original_basename}' with '{new_basename}'.") except FileNotFoundError: print(f"Error: '{new_basename}' not found. Skipped replacement.") print("Replacement completed.") else: print("Replacement canceled.")