refactor: Extract models, config, and main app setup
Local Docker Build (Dev) / build-dev (push) Successful in 33s
Local Docker Build (Dev) / build-dev (push) Successful in 33s
- 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
This commit is contained in:
@@ -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
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user