//! Momentry Core - Digital asset management system with video analysis and RAG //! //! This is the main entry point for the CLI application. use anyhow::Result; use clap::Parser; // Local modules mod cli; mod processing; fn init_tracing() { tracing_subscriber::fmt() .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) .with_target(true) .with_writer(|| std::io::LineWriter::new(std::io::stdout())) .init(); } fn load_env() { // Resolve .env at runtime so the binary is portable across machines. // Order: MOMENTRY_ENV_FILE -> ./.env -> /config/.env -> /.env -> $HOME/.env if let Ok(p) = std::env::var("MOMENTRY_ENV_FILE") { let _ = dotenv::from_filename(p); return; } if dotenv::from_filename(".env").is_ok() { return; } if let Ok(exe) = std::env::current_exe() { // /bin/momentry -> if let Some(install_root) = exe .parent() .and_then(|p| p.parent()) { // Package installs .env at /config/.env let config_env = install_root.join("config").join(".env"); if config_env.exists() { let _ = dotenv::from_filename(&config_env); return; } // Fallback: /.env if dotenv::from_filename(install_root.join(".env")).is_ok() { return; } } // Legacy fallback: $HOME/.env if let Some(home) = exe .parent() .and_then(|p| p.parent()) .and_then(|p| p.parent()) { let _ = dotenv::from_filename(home.join(".env")); } } } use cli::*; use processing::handlers::*; /// Main entry point #[tokio::main] async fn main() -> Result<()> { load_env(); init_tracing(); let cli = Cli::parse(); match cli.command { Commands::Register { path } => { handle_register(&path).await?; } Commands::Process { target, modules, cloud, force, resume, } => { handle_process(&target, modules, cloud, force, resume).await?; } Commands::Chunk { uuid } => { handle_chunk(&uuid).await?; } Commands::StoreAsrx { uuid } => { handle_store_asrx(&uuid).await?; } Commands::TkgBackfill { file_uuid } => { handle_tkg_backfill(&file_uuid).await?; } Commands::Vectorize { uuid } => { handle_vectorize(&uuid).await?; } Commands::Phase1 { uuid } => { handle_phase1(&uuid).await?; } Commands::Complete { uuid } => { handle_complete(&uuid).await?; } Commands::Play { target } => { handle_play(&target).await?; } Commands::Watch { directories } => { handle_watch(directories).await?; } Commands::System { gpu } => { handle_system(gpu).await?; } Commands::Server { host, port } => { handle_server(&host, port).await?; } Commands::Worker { max_concurrent, poll_interval, batch_size, } => { handle_worker(max_concurrent, poll_interval, batch_size).await?; } Commands::Query { query } => { handle_query(&query).await?; } Commands::Lookup { path } => { handle_lookup(&path).await?; } Commands::Resolve { uuid } => { handle_resolve(&uuid).await?; } Commands::Thumbnails { uuid, count } => { handle_thumbnails(uuid, count).await?; } Commands::Status { uuid } => { handle_status(uuid).await?; } Commands::Backup { action, days } => { handle_backup(&action, days).await?; } Commands::ApiKey { action, name, key_type, ttl, key, } => { handle_api_key(&action, name, key_type, ttl.map(|i| i as u64), key, None).await?; } Commands::Gitea { action, username, password, token_name, scopes, } => { handle_gitea(action, username, password, token_name, scopes).await?; } Commands::Agent { tool, args } => { cli::agent::handle_agent(&tool, &args).await?; } Commands::Init { skip_db, skip_deps, force, scan_dir, quiet } => { let opts = momentry_core::core::init::InitOptions { skip_db, skip_deps, force, scan_dir: scan_dir.map(std::path::PathBuf::from), quiet, }; momentry_core::core::init::run(opts).await?; } Commands::Detect { image, objects, cascade, threshold, } => { cli::vision::handle_detect_command(image, objects, cascade, threshold).await?; } Commands::Vision(cmd) => { cli::vision::handle_vision_command(cmd).await?; } } Ok(()) } /// Handle register command async fn handle_register(path: &str) -> Result<()> { use momentry_core::core::db::postgres_db::StorageStatus; use momentry_core::core::db::{Database, PostgresDb, VideoRecord, VideoStatus}; use momentry_core::core::probe::probe_video; use std::path::Path; use uuid::Uuid; println!("Registering video: {}", path); // 檔案存在性檢查 let file_path = Path::new(path); if !file_path.exists() { anyhow::bail!("File not found: {}", path); } // 產生 file_uuid (Uuid::new_v4(),simple format,32 chars,符合 schema varchar(32)) let file_uuid = Uuid::new_v4().simple().to_string(); println!("Generated UUID: {}", file_uuid); // ffprobe 提取 metadata let probe_result = probe_video(path)?; let duration = probe_result .format .duration .as_ref() .and_then(|s| s.parse::().ok()) .unwrap_or(0.0); let mut width = 0u32; let mut height = 0u32; let mut fps = 0.0; for stream in &probe_result.streams { if stream.codec_type.as_deref() == Some("video") { width = stream.width.unwrap_or(0); height = stream.height.unwrap_or(0); if let Some(fps_str) = &stream.r_frame_rate { if let Some((num, den)) = fps_str.split_once('/') { if let (Ok(n), Ok(d)) = (num.parse::(), den.parse::()) { if d > 0.0 { fps = n / d; } } } } break; } } println!(" Duration: {}s", duration); println!(" Video: {}x{}", width, height); println!(" FPS: {}", fps); // 準備 VideoRecord let file_path_abs = file_path .canonicalize() .map(|p| p.to_string_lossy().to_string()) .unwrap_or_else(|_| path.to_string()); let file_name = file_path .file_name() .map(|n| n.to_string_lossy().to_string()) .unwrap_or_default(); let probe_json = serde_json::to_value(&probe_result).ok(); let record = VideoRecord { id: 0, file_uuid: file_uuid.clone(), file_path: file_path_abs, file_name, file_type: Some("video".to_string()), duration, width, height, fps, probe_json, storage: StorageStatus::default(), status: VideoStatus::Pending, processing_status: Some(serde_json::json!({"phase": "REGISTERED"})), birth_registration: None, user_id: None, job_id: None, created_at: String::new(), registration_time: None, total_frames: 0, parent_uuid: None, cut_done: false, cut_count: 0, cut_max_duration: 0.0, scene_done: false, audio_tracks: None, proxy_path: None, audio_track: None, }; // 寫入資料庫 let db = PostgresDb::init().await?; let video_id = db.register_video(&record).await?; println!("\n✅ Video registered successfully!"); println!(" Video ID: {}", video_id); println!(" File UUID: {}", file_uuid); println!(" Status: pending"); Ok(()) } /// Handle process command async fn handle_process( target: &str, modules: Option>, cloud: Option>, force: bool, resume: bool, ) -> Result<()> { println!("Processing video: {}", target); println!("Modules: {:?}", modules); println!("Cloud modules: {:?}", cloud); println!("Force: {}, Resume: {}", force, resume); // TODO: Implement processing logic Ok(()) } /// Handle chunk command async fn handle_chunk(uuid: &str) -> Result<()> { println!("Generating chunks for: {}", uuid); // TODO: Implement chunk logic Ok(()) } /// Handle story command /// Handle vectorize command async fn handle_vectorize(uuid: &str) -> Result<()> { println!("Vectorizing chunks for: {}", uuid); // TODO: Implement vectorize logic Ok(()) } /// Handle play command async fn handle_play(target: &str) -> Result<()> { println!("Playing video: {}", target); // TODO: Implement play logic Ok(()) } /// Handle watch command async fn handle_watch(directories: Option) -> Result<()> { println!("Watching directories: {:?}", directories); // TODO: Implement watch logic Ok(()) } /// Handle system command async fn handle_system(gpu: bool) -> Result<()> { println!("Checking system resources..."); // TODO: Implement proper system resource checking println!("System Information:"); println!(" CPU: (would show CPU info)"); println!(" Memory: (would show memory info)"); if gpu { println!("GPU details: (would show GPU info if available)"); } println!("(System resource checking would be implemented here)"); Ok(()) } /// Handle server command async fn handle_server(host: &str, port: Option) -> Result<()> { let port = port.unwrap_or(3002); println!("Starting API server on {}:{}", host, port); // Start the actual API server momentry_core::api::start_server(host, port).await?; Ok(()) } /// Handle worker command async fn handle_worker( max_concurrent: Option, poll_interval: Option, batch_size: Option, ) -> Result<()> { use momentry_core::core::db::{Database, PostgresDb, RedisClient}; use momentry_core::worker::{JobWorker, WorkerConfig}; println!("Starting job worker"); println!("Max concurrent: {:?}", max_concurrent); println!("Poll interval: {:?}", poll_interval); println!("Batch size: {:?}", batch_size); let config = WorkerConfig { max_concurrent: max_concurrent.unwrap_or(2), poll_interval_secs: poll_interval.unwrap_or(5), enabled: true, batch_size: batch_size.unwrap_or(10), processor_timeout_secs: 3600, }; let db = PostgresDb::init().await?; let redis = RedisClient::new()?; // Run migrations on worker startup println!("Running database migrations..."); PostgresDb::run_migrations(db.pool()).await?; println!("Migrations completed"); // ── Execute Redis Health Check ───────────────────────────────────────── { use momentry_core::worker::redis_health_check::RedisHealthChecker; use momentry_core::core::config::REDIS_KEY_PREFIX; let redis_url = std::env::var("REDIS_URL") .unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string()); let health_checker = RedisHealthChecker::new(redis_url, 86400); println!("Running Redis health check on startup..."); match health_checker.check(REDIS_KEY_PREFIX.as_str()).await { Ok(report) => { println!( "✅ Health check completed: {} orphans cleaned, {} TTLs fixed, {} stale jobs marked", report.orphan_processors_cleaned, report.ttls_fixed, report.stale_jobs_marked ); } Err(e) => { eprintln!("⚠️ Health check failed (continuing anyway): {}", e); } } } // ────────────────────────────────────────────────────────────────────── let worker = JobWorker::new( std::sync::Arc::new(db), std::sync::Arc::new(redis), config.clone(), ); println!( "Starting worker with max_concurrent={}, poll_interval={}s", config.max_concurrent, config.poll_interval_secs ); worker.run().await?; Ok(()) } /// Handle query command async fn handle_query(query: &str) -> Result<()> { println!("Querying: {}", query); // TODO: Implement query logic Ok(()) } /// Handle lookup command async fn handle_lookup(path: &str) -> Result<()> { println!("Looking up UUID for path: {}", path); // TODO: Implement lookup logic Ok(()) } /// Handle resolve command async fn handle_resolve(uuid: &str) -> Result<()> { println!("Resolving path for UUID: {}", uuid); // TODO: Implement resolve logic Ok(()) } /// Handle thumbnails command async fn handle_thumbnails(uuid: Option, count: u32) -> Result<()> { println!("Generating thumbnails"); println!("UUID: {:?}", uuid); println!("Count: {}", count); // TODO: Implement thumbnails logic Ok(()) } /// Handle status command async fn handle_status(uuid: Option) -> Result<()> { println!("Checking storage status"); println!("UUID: {:?}", uuid); // TODO: Implement status logic Ok(()) } /// Handle backup command async fn handle_backup(action: &str, days: Option) -> Result<()> { println!("Backup action: {}", action); println!("Days to keep: {:?}", days); // TODO: Implement backup logic Ok(()) } /// Handle Gitea command async fn handle_gitea( action: GiteaAction, username: Option, password: Option, token_name: Option, scopes: Option, ) -> Result<()> { println!("Gitea action: {:?}", action); println!("Username: {:?}", username); println!("Token name: {:?}", token_name); println!("Scopes: {:?}", scopes); // TODO: Implement Gitea logic Ok(()) }