From 5adc596077f867502c4c3fd3fdfb43a271057097 Mon Sep 17 00:00:00 2001 From: SBCrumb Date: Thu, 25 Sep 2025 15:32:51 -0400 Subject: [PATCH] refactor: Extract models, config, and main app setup - Create modular directory structure - Extract Pydantic models to api/models.py - Move configuration to config/settings.py - Create clean main.py with FastAPI app setup WIP: Routes and processor classes still need extraction --- api/__init__.py | 0 api/models.py | 49 +++++++++++++++++++ config/__init__.py | 0 config/settings.py | 62 ++++++++++++++++++++++++ main.py | 107 +++++++++++++++++++++++++++++++++++++++++ processors/__init__.py | 0 utils/__init__.py | 0 webhooks/__init__.py | 0 8 files changed, 218 insertions(+) create mode 100644 api/__init__.py create mode 100644 api/models.py create mode 100644 config/__init__.py create mode 100644 config/settings.py create mode 100644 main.py create mode 100644 processors/__init__.py create mode 100644 utils/__init__.py create mode 100644 webhooks/__init__.py diff --git a/api/__init__.py b/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/api/models.py b/api/models.py new file mode 100644 index 0000000..a504757 --- /dev/null +++ b/api/models.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +""" +Pydantic models for NFOGuard API requests and responses +""" +from pydantic import BaseModel +from typing import Optional, Dict, Any, List + + +class SonarrWebhook(BaseModel): + eventType: str + series: Optional[Dict[str, Any]] = None + episodes: Optional[list] = [] + episodeFile: Optional[Dict[str, Any]] = None + isUpgrade: Optional[bool] = False + + class Config: + extra = "allow" + + +class RadarrWebhook(BaseModel): + eventType: str + movie: Optional[Dict[str, Any]] = None + movieFile: Optional[Dict[str, Any]] = None + isUpgrade: Optional[bool] = False + deletedFiles: Optional[list] = [] + remoteMovie: Optional[Dict[str, Any]] = None + renamedMovieFiles: Optional[List[Dict[str, Any]]] = None + + class Config: + extra = "allow" + + +class HealthResponse(BaseModel): + status: str + version: str + uptime: str + database_status: str + radarr_database: Optional[Dict[str, Any]] = None + + +class TVSeasonRequest(BaseModel): + series_path: str + season_name: str + + +class TVEpisodeRequest(BaseModel): + series_path: str + season_name: str + episode_name: str \ No newline at end of file diff --git a/config/__init__.py b/config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/config/settings.py b/config/settings.py new file mode 100644 index 0000000..a7e1b2c --- /dev/null +++ b/config/settings.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +""" +NFOGuard configuration management +""" +import os +from pathlib import Path + + +def _bool_env(name: str, default: bool) -> bool: + """Convert environment variable to boolean""" + v = os.environ.get(name) + if v is None: + return default + return v.lower() in ("1", "true", "yes", "y", "on") + + +class NFOGuardConfig: + def __init__(self): + # Paths - No hardcoded defaults, must be configured via environment + tv_paths_env = os.environ.get("TV_PATHS", "") + movie_paths_env = os.environ.get("MOVIE_PATHS", "") + + if not tv_paths_env: + raise ValueError("TV_PATHS environment variable is required but not set") + if not movie_paths_env: + raise ValueError("MOVIE_PATHS environment variable is required but not set") + + self.tv_paths = [Path(p.strip()) for p in tv_paths_env.split(",") if p.strip()] + self.movie_paths = [Path(p.strip()) for p in movie_paths_env.split(",") if p.strip()] + + # Core settings + self.manage_nfo = _bool_env("MANAGE_NFO", True) + self.fix_dir_mtimes = _bool_env("FIX_DIR_MTIMES", True) + self.lock_metadata = _bool_env("LOCK_METADATA", True) + self.debug = _bool_env("DEBUG", False) + self.manager_brand = os.environ.get("MANAGER_BRAND", "NFOGuard") + + # Batching + self.batch_delay = float(os.environ.get("BATCH_DELAY", "5.0")) + self.max_concurrent = int(os.environ.get("MAX_CONCURRENT_SERIES", "3")) + + # Database + self.db_path = Path(os.environ.get("DB_PATH", "/app/data/media_dates.db")) + + # Movie processing + self.movie_priority = os.environ.get("MOVIE_PRIORITY", "import_then_digital").lower() + self.prefer_release_dates_over_file_dates = _bool_env("PREFER_RELEASE_DATES_OVER_FILE_DATES", True) + self.allow_file_date_fallback = _bool_env("ALLOW_FILE_DATE_FALLBACK", False) + self.release_date_priority = [p.strip() for p in os.environ.get("RELEASE_DATE_PRIORITY", "digital,physical,theatrical").split(",")] + self.enable_smart_date_validation = _bool_env("ENABLE_SMART_DATE_VALIDATION", True) + self.max_release_date_gap_years = int(os.environ.get("MAX_RELEASE_DATE_GAP_YEARS", "10")) + self.movie_poll_mode = os.environ.get("MOVIE_POLL_MODE", "always").lower() + self.movie_update_mode = os.environ.get("MOVIE_DATE_UPDATE_MODE", "backfill_only").lower() + + # TV processing + self.tv_season_dir_format = os.environ.get("TV_SEASON_DIR_FORMAT", "Season {season:02d}") + self.tv_season_dir_pattern = os.environ.get("TV_SEASON_DIR_PATTERN", "season ").lower() + self.tv_webhook_processing_mode = os.environ.get("TV_WEBHOOK_PROCESSING_MODE", "targeted").lower() + + +# Global configuration instance +config = NFOGuardConfig() \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..9255193 --- /dev/null +++ b/main.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +""" +NFOGuard - Main application entry point +Automated NFO file management for Radarr and Sonarr +""" +import os +import signal +import sys +import uvicorn +from datetime import datetime, timezone +from fastapi import FastAPI + +# Import configuration first +from config.settings import config + +# Import other components +from core.database import NFOGuardDatabase +from core.nfo_manager import NFOManager +from core.path_mapper import PathMapper +from processors.tv_processor import TVProcessor +from processors.movie_processor import MovieProcessor +from webhooks.webhook_batcher import WebhookBatcher + + +# --------------------------- +# Version and Build Info +# --------------------------- +def get_version() -> str: + """Get version from VERSION file with build information""" + try: + with open("VERSION", "r", encoding="utf-8") as f: + version = f.read().strip() + except FileNotFoundError: + version = "development" + + # Add build source suffix for identification + build_source = os.environ.get("BUILD_SOURCE", "") + if build_source == "gitea": + if "gitea" not in version: # Don't double-add gitea suffix + version = f"{version}-gitea" + + return version + + +# --------------------------- +# Application Setup +# --------------------------- +version = get_version() + +app = FastAPI( + title="NFOGuard", + description="Webhook server for preserving media import dates", + version=version +) + +start_time = datetime.now(timezone.utc) + +# Initialize components +db = NFOGuardDatabase(config.db_path) +nfo_manager = NFOManager(config.manager_brand, config.debug) +path_mapper = PathMapper(config) +tv_processor = TVProcessor(db, nfo_manager, path_mapper) +movie_processor = MovieProcessor(db, nfo_manager, path_mapper) +batcher = WebhookBatcher(nfo_manager) + +# Import and register routes +from api.routes import register_routes +register_routes(app, tv_processor, movie_processor, batcher, db, start_time, version) + + +# --------------------------- +# Signal Handlers +# --------------------------- +def signal_handler(signum, frame): + """Handle shutdown signals gracefully""" + print(f"Received signal {signum}, shutting down gracefully...") + sys.exit(0) + + +# --------------------------- +# Main Entry Point +# --------------------------- +if __name__ == "__main__": + # Register signal handlers for graceful shutdown + signal.signal(signal.SIGTERM, signal_handler) + signal.signal(signal.SIGINT, signal_handler) + + print("Starting NFOGuard") + print(f"Version: {version}") + print(f"TV paths: {[str(p) for p in config.tv_paths]}") + print(f"Movie paths: {[str(p) for p in config.movie_paths]}") + print(f"Database: {config.db_path}") + print(f"Config: manage_nfo={config.manage_nfo}, fix_mtimes={config.fix_dir_mtimes}") + print(f"Movie priority: {config.movie_priority}") + + try: + uvicorn.run( + app, + host="0.0.0.0", + port=int(os.environ.get("PORT", "8080")), + reload=False + ) + except KeyboardInterrupt: + print("NFOGuard stopped by user") + except Exception as e: + print(f"NFOGuard crashed: {e}") + sys.exit(1) \ No newline at end of file diff --git a/processors/__init__.py b/processors/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/utils/__init__.py b/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/webhooks/__init__.py b/webhooks/__init__.py new file mode 100644 index 0000000..e69de29