Files
nfoguard/bulk_update_movies.py
T
2025-09-09 08:36:25 -04:00

144 lines
5.0 KiB
Python

#!/usr/bin/env python3
"""
Bulk update all movies in NFOguard database with import dates from Radarr
Run this script to populate/update all movies at once
"""
import os
import sys
from pathlib import Path
from clients.radarr_db_client import RadarrDbClient
from core.database import NFOGuardDatabase
from core.logging import _log
def bulk_update_all_movies():
"""Update all movies in Radarr database"""
# Initialize database clients
radarr_db = RadarrDbClient.from_env()
if not radarr_db:
print("❌ Radarr database connection required")
return False
nfo_db = NFOGuardDatabase(Path(os.environ.get("DB_PATH", "/app/data/media_dates.db")))
print("🔍 Getting all movies from Radarr database...")
# Get all movies with IMDb IDs
query = """
SELECT
mm."ImdbId" as imdb_id,
m."Id" as movie_id,
mm."Title" as title,
mm."Year" as year,
m."Path" as path
FROM "Movies" m
JOIN "MovieMetadata" mm ON m."MovieMetadataId" = mm."Id"
WHERE mm."ImdbId" IS NOT NULL AND mm."ImdbId" != ''
ORDER BY mm."Title"
"""
try:
with radarr_db._get_connection() as conn:
if radarr_db.db_type == "postgresql":
import psycopg2.extras
cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
else:
cursor = conn.cursor()
cursor.execute(query)
movies = cursor.fetchall()
print(f"📽️ Found {len(movies)} movies with IMDb IDs")
updated_count = 0
skipped_count = 0
error_count = 0
for i, movie in enumerate(movies):
if radarr_db.db_type == "postgresql":
imdb_id, movie_id, title, year, path = movie['imdb_id'], movie['movie_id'], movie['title'], movie['year'], movie['path']
else:
imdb_id, movie_id, title, year, path = movie[0], movie[1], movie[2], movie[3], movie[4]
print(f"\n[{i+1}/{len(movies)}] Processing: {title} ({year}) - {imdb_id}")
try:
# Check if we already have this movie
existing_dates = nfo_db.get_movie_dates(imdb_id)
if existing_dates and existing_dates.get('dateadded'):
print(f" ⏭️ Already exists: {existing_dates['dateadded']} ({existing_dates['source']})")
skipped_count += 1
continue
# Get import date from Radarr database
import_date, source = radarr_db.get_movie_import_date_optimized(movie_id, fallback_to_file_date=True)
if import_date:
# Store in NFOGuard database
nfo_db.upsert_movie(imdb_id, path)
nfo_db.upsert_movie_dates(
imdb_id=imdb_id,
dateadded=import_date,
source=source,
has_video_file=True
)
print(f" ✅ Updated: {import_date} ({source})")
updated_count += 1
else:
print(f" ⚠️ No import date found")
error_count += 1
except Exception as e:
print(f" ❌ Error: {e}")
error_count += 1
print(f"\n🎯 Results:")
print(f" ✅ Updated: {updated_count}")
print(f" ⏭️ Skipped: {skipped_count}")
print(f" ❌ Errors: {error_count}")
print(f" 📊 Total: {len(movies)}")
return True
except Exception as e:
print(f"❌ Failed to get movies: {e}")
return False
def bulk_get_imdb_ids():
"""Get all IMDb IDs for bulk processing"""
radarr_db = RadarrDbClient.from_env()
if not radarr_db:
print("❌ Radarr database connection required")
return []
query = 'SELECT mm."ImdbId" FROM "Movies" m JOIN "MovieMetadata" mm ON m."MovieMetadataId" = mm."Id" WHERE mm."ImdbId" IS NOT NULL'
try:
with radarr_db._get_connection() as conn:
cursor = conn.cursor()
cursor.execute(query)
results = cursor.fetchall()
return [row[0] for row in results]
except Exception as e:
print(f"❌ Failed to get IMDb IDs: {e}")
return []
if __name__ == "__main__":
print("NFOGuard Bulk Movie Updater")
print("=" * 40)
if len(sys.argv) > 1 and sys.argv[1] == "--list-imdb":
imdb_ids = bulk_get_imdb_ids()
print(f"Found {len(imdb_ids)} movies:")
for imdb_id in imdb_ids[:20]: # Show first 20
print(f" {imdb_id}")
if len(imdb_ids) > 20:
print(f" ... and {len(imdb_ids) - 20} more")
else:
success = bulk_update_all_movies()
if success:
print("\n✅ Bulk update completed!")
else:
print("\n❌ Bulk update failed!")
sys.exit(1)