Files
momentry_core/src/processing/handlers.rs
T
Accusys 3d441a1c76 release: v1.3.2 - Cross-Machine Deployment Support
Major Changes:
- Removed all hardcoded paths for cross-machine deployment
- Added unified path management module (path_utils.rs)
- Supports arbitrary user home directories
- Environment variable configuration for all paths

New Features:
- path_utils module with 15+ path resolution functions
- Dynamic user home directory detection
- Environment variable overrides for all paths
- Default paths using $HOME/momentry and $HOME/momentry_core

Fixed Files:
- Rust code: 8 core files (release.rs, service.rs, markbase_compat.rs, etc.)
- Python scripts: 10 files (ASR, ASRX, Face, Identity, VLM, Migration)
- Configuration: production.env (removed hardcoded paths)

Environment Variables Supported:
- HOME - User home directory
- MOMENTRY_ROOT - Momentry root directory
- MOMENTRY_CORE_DIR - Momentry_core directory
- MOMENTRY_OUTPUT_DIR - Output directory
- MOMENTRY_BACKUP_DIR - Backup directory
- MOMENTRY_STORAGE_ROOT - Storage root directory
- MOMENTRY_SCRIPTS_DIR - Scripts directory
- MOMENTRY_CLI_DIR - CLI tools directory

Breaking Changes:
- None (backward compatible with environment variables)

Deployment:
- Can now deploy to any machine with any username
- No hardcoded /Users/accusys paths in core functionality
- Ready for M4ProMini deployment (/Users/nextorageai)
2026-10-12 13:20:45 +08:00

623 lines
21 KiB
Rust

//! Command handlers for Momentry Core CLI
//!
//! This module contains the actual implementation of CLI command handlers.
use anyhow::Result;
use std::path::Path;
/// Handle video registration command
pub async fn handle_register(path: &str) -> Result<()> {
println!("Registering video: {}", path);
// TODO: Implement proper video registration
println!("(Video registration would happen here)");
// Simple UUID simulation
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
path.hash(&mut hasher);
let hash = hasher.finish();
let uuid = format!("{:016x}", hash);
println!("UUID that would be generated: {}", uuid);
Ok(())
}
/// Handle video processing command
pub async fn handle_process(
target: &str,
modules: Option<Vec<String>>,
cloud: bool,
force: bool,
resume: bool,
) -> Result<()> {
println!("=== handle_process called ===");
println!("Processing target: {}", target);
println!("Modules: {:?}", modules);
println!("Cloud processing: {}", cloud);
println!("Force reprocess: {}", force);
println!("Resume: {}", resume);
// Determine if target is a UUID or a path
let is_uuid = target.len() == 32 && target.chars().all(|c| c.is_ascii_hexdigit());
if is_uuid {
// UUID-based processing
println!("\n[PROCESS] Processing video with UUID: {}", target);
// Connect to database
let database_url = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://accusys@localhost:5432/momentry".to_string());
let db = momentry_core::core::db::PostgresDb::new(&database_url).await?;
// Get video info
let video = db
.get_video_by_uuid(target)
.await?
.ok_or_else(|| anyhow::anyhow!("Video not found: {}", target))?;
let file_path = video.file_path.clone();
let output_dir = std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| {
std::env::var("HOME")
.map(|h| format!("{}/momentry/output", h))
.unwrap_or_else(|_| "./output".to_string())
});
println!("[PROCESS] Video path: {}", file_path);
// Process modules
let modules_to_process = modules.unwrap_or_else(|| vec!["face".to_string()]);
for module in &modules_to_process {
match module.as_str() {
"face" => {
let output_path = format!("{}/{}.face.json", output_dir, target);
// Check if already exists
if !force && std::path::Path::new(&output_path).exists() {
println!("[FACE] Output already exists, use --force to reprocess");
continue;
}
println!("[FACE] Starting face processing...");
use momentry_core::core::processor::face::process_face;
let result = process_face(&file_path, &output_path, Some(target), None).await?;
println!(
"[FACE] Completed: {} frames, {} faces",
result.frames.len(),
result.total_faces
);
// Show trace statistics
let with_trace = result
.frames
.iter()
.flat_map(|f| &f.faces)
.filter(|face| face.trace_id.is_some())
.count();
println!(
"[FACE] Faces with trace_id: {}/{}",
with_trace, result.total_faces
);
}
"asr" => {
println!("[ASR] ASR processing not yet implemented in CLI");
}
"ocr" => {
println!("[OCR] OCR processing not yet implemented in CLI");
}
_ => {
println!("[WARN] Unknown module: {}", module);
}
}
}
println!("\n✅ Processing completed for UUID: {}", target);
} else {
// Path-based processing
let path = Path::new(target);
if !path.exists() {
anyhow::bail!("Path does not exist: {}", target);
}
println!("\n[PROCESS] Processing file: {}", target);
// For now, just process face module
if modules
.as_ref()
.map(|m| m.contains(&"face".to_string()))
.unwrap_or(true)
{
let output_path = format!("{}.face.json", target);
if !force && std::path::Path::new(&output_path).exists() {
println!("[FACE] Output already exists, use --force to reprocess");
} else {
println!("[FACE] Starting face processing...");
use momentry_core::core::processor::face::process_face;
let result = process_face(target, &output_path, None, None).await?;
println!(
"[FACE] Completed: {} frames, {} faces",
result.frames.len(),
result.total_faces
);
}
}
println!("\n✅ Processing completed for path: {}", target);
}
Ok(())
}
/// Handle video chunking command
pub async fn handle_chunk(uuid: &str) -> Result<()> {
println!("Chunking video with UUID: {}", uuid);
// TODO: Connect to database and fetch video
println!(
"Would connect to database and fetch video with UUID: {}",
uuid
);
println!("(Would show video details)");
// TODO: Implement chunking logic
Ok(())
}
/// Handle story generation command
pub async fn handle_story(uuid: &str) -> Result<()> {
println!("Generating story for video with UUID: {}", uuid);
// TODO: Connect to database and fetch video
println!(
"Would connect to database and fetch video with UUID: {}",
uuid
);
println!("(Would show video details)");
println!("Generating story...");
// TODO: Implement story generation logic
Ok(())
}
/// Handle vectorization command
pub async fn handle_vectorize(uuid: &str) -> Result<()> {
println!("Vectorizing video with UUID: {}", uuid);
// TODO: Connect to database and fetch video
println!(
"Would connect to database and fetch video with UUID: {}",
uuid
);
println!("(Would show video details)");
println!("Starting vectorization...");
// TODO: Implement vectorization logic
Ok(())
}
/// Handle video playback command
pub async fn handle_play(target: &str) -> Result<()> {
println!("Playing target: {}", target);
// TODO: Implement video playback logic
println!("(Video playback would start here)");
Ok(())
}
/// Handle file system watching command
pub async fn handle_watch(directories: Vec<String>) -> Result<()> {
println!("Watching directories for new videos:");
for dir in &directories {
println!(" - {}", dir);
}
// TODO: Implement directory watching logic
println!("(Directory watcher would start here)");
Ok(())
}
/// Handle system information command
pub async fn handle_system(gpu: bool) -> Result<()> {
println!("System Information:");
// TODO: Implement system information gathering
if gpu {
println!("GPU information requested");
// TODO: Add GPU-specific info
}
Ok(())
}
/// Handle server startup command
pub async fn handle_server(host: &str, port: u16) -> Result<()> {
println!("Starting API server on {}:{}", host, port);
// This is handled by the server binary directly
println!("(Server is started through binary entry point)");
Ok(())
}
/// Handle worker startup command
pub async fn handle_worker(
max_concurrent: Option<u32>,
poll_interval: Option<u64>,
batch_size: Option<u32>,
) -> Result<()> {
println!("Starting worker with configuration:");
println!(" Max concurrent jobs: {}", max_concurrent.unwrap_or(2));
println!(" Poll interval: {} seconds", poll_interval.unwrap_or(5));
println!(" Batch size: {}", batch_size.unwrap_or(10));
// TODO: Implement worker startup logic
Ok(())
}
/// Handle search query command
pub async fn handle_query(query: &str) -> Result<()> {
println!("Searching for: {}", query);
// TODO: Connect to database and search
println!("Would search for: {}", query);
let results: Vec<String> = vec![]; // Placeholder
println!("(Search would return results here)");
Ok(())
}
/// Handle file lookup command
pub async fn handle_lookup(path: &str) -> Result<()> {
println!("Looking up file: {}", path);
// TODO: Connect to database and lookup file
println!("Looking up file in database: {}", path);
let video: Option<String> = None; // Placeholder
if let Some(_) = video {
println!("File found in database: {}", path);
// In real implementation, show video details
} else {
println!("File not found in database: {}", path);
println!("(UUID would be generated for new files)");
}
Ok(())
}
/// Handle UUID resolution command
pub async fn handle_resolve(uuid: &str) -> Result<()> {
println!("Resolving UUID: {}", uuid);
// TODO: Connect to database and fetch video
println!(
"Would connect to database and fetch video with UUID: {}",
uuid
);
println!("Resolved to:");
println!(" File name: (would show from database)");
println!(" File path: (would show from database)");
println!(" Duration: (would show from database)");
println!(" Resolution: (would show from database)");
Ok(())
}
/// Handle thumbnail extraction command
pub async fn handle_thumbnails(uuid: Option<String>, count: Option<u32>) -> Result<()> {
let count = count.unwrap_or(5);
if let Some(uuid) = uuid {
println!("Extracting {} thumbnails for video UUID: {}", count, uuid);
// TODO: Connect to database and fetch video
println!("Would fetch video with UUID: {}", uuid);
println!("(Would show video details)");
// TODO: Implement thumbnail extraction
} else {
println!("Extracting {} thumbnails from all pending videos", count);
// TODO: Implement bulk thumbnail extraction
}
Ok(())
}
/// Handle video status check command
pub async fn handle_status(uuid: Option<String>) -> Result<()> {
// TODO: Connect to database
println!("Would connect to database to check status");
if let Some(uuid) = uuid {
println!("Checking status for video UUID: {}", uuid);
// Would fetch video from database
println!("Would fetch video with UUID: {}", uuid);
println!("Video Status:");
println!(" UUID: {}", uuid);
println!(" File name: (would show from database)");
println!(" Status: (would show from database)");
println!(" Processing status: (would show from database)");
println!(" Created at: (would show from database)");
println!(" Registration time: (would show from database)");
// TODO: Add more detailed processing status
} else {
println!("Checking status of all videos");
println!("(Would list videos from database)");
}
Ok(())
}
/// Handle backup operations command
pub async fn handle_backup(action: &str, days: Option<u32>) -> Result<()> {
match action {
"create" => {
println!("Creating backup...");
// TODO: Implement backup creation
}
"list" => {
println!("Listing backups...");
// TODO: Implement backup listing
}
"restore" => {
println!("Restoring from backup...");
// TODO: Implement backup restoration
}
"clean" | "cleanup" => {
let days = days.unwrap_or(30);
println!("Cleaning backups older than {} days...", days);
// TODO: Implement backup cleanup
}
_ => {
println!("Unknown backup action: {}", action);
println!("Available actions: create, list, restore, clean(up)");
}
}
Ok(())
}
/// Handle API key management command
pub async fn handle_api_key(
action: &crate::cli::args::ApiKeyAction,
name: Option<String>,
key_type: Option<String>,
ttl: Option<u64>,
key: Option<String>,
key_id: Option<String>,
) -> Result<()> {
use momentry_core::core::api_key::ApiKeyService;
use momentry_core::core::api_key::CreateApiKeyRequest;
use momentry_core::core::db::PostgresDb;
// Connect to database
let database_url = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://accusys@localhost:5432/momentry".to_string());
let db = PostgresDb::new(&database_url).await?;
let service = ApiKeyService::new(database_url);
match action {
crate::cli::args::ApiKeyAction::Create => {
let name = name.unwrap_or_else(|| "unnamed-key".to_string());
// Parse key type
let key_type_enum = match key_type.as_deref() {
Some("service") => momentry_core::core::api_key::ApiKeyType::Service,
Some("integration") => momentry_core::core::api_key::ApiKeyType::Integration,
Some("emergency") => momentry_core::core::api_key::ApiKeyType::Emergency,
_ => momentry_core::core::api_key::ApiKeyType::User,
};
// Create request with default permissions
let request = CreateApiKeyRequest {
name: name.clone(),
key_type: key_type_enum,
user_id: None,
service_name: None,
permissions: vec!["read".to_string(), "write".to_string()], // Default permissions
ttl_days: ttl.map(|u| u as i64),
};
// Generate key
let response = service.create_key(request)?;
// Hash key
let key_hash = service.hash_key(&response.key);
let key_type_str = key_type_enum.as_str().to_string();
let permissions = serde_json::json!(["read", "write"]); // Default permissions
// Create config
let config = momentry_core::core::db::CreateApiKeyConfig::new(
&response.key_id,
&key_hash,
key_type_enum.prefix(),
&name,
&key_type_str,
)
.with_permissions(&permissions)
.with_expires_at(response.expires_at);
// Insert into database - fail on error
db.create_api_key(config).await?;
println!("\n✅ API Key created successfully!");
println!(
"\n┌─────────────────────────────────────────────────────────────────────────────┐"
);
println!(
"│ ⚠️ IMPORTANT: Save this key now - it will not be shown again! │"
);
println!(
"└─────────────────────────────────────────────────────────────────────────────┘"
);
println!("\nKey ID: {}", response.key_id);
println!("API Key: {}", response.key);
println!("Expires: {}", response.expires_at);
if !response.warning.is_empty() {
println!("\n⚠️ {}", response.warning);
}
}
crate::cli::args::ApiKeyAction::List => match db.list_api_keys().await {
Ok(keys) => {
println!("\n📋 API Key List");
if keys.is_empty() {
println!(" (no API keys found)");
} else {
println!("\n┌────────────────────────────────────────────────────────────────────────────┐");
println!(
"│ {:8} │ {:20} │ {:12} │ {:8} │ {:15} │",
"Status", "Name", "Type", "Usage", "Last Used"
);
println!("├────────────────────────────────────────────────────────────────────────────┤");
for k in &keys {
let status = if k.status == "active" {
"✓ active"
} else {
&k.status
};
let last_used = k
.last_used_at
.map(|dt| dt.format("%Y-%m-%d %H:%M").to_string())
.unwrap_or_else(|| "never".to_string());
println!(
"│ {:8} │ {:20} │ {:12} │ {:8} │ {:15} │",
status,
if k.name.len() > 20 {
&k.name[..17]
} else {
&k.name
},
k.key_type,
k.usage_count,
last_used
);
}
println!("└────────────────────────────────────────────────────────────────────────────┘");
println!("\nTotal: {} key(s)", keys.len());
}
}
Err(e) => {
eprintln!("\n❌ Failed to list API keys: {}", e);
return Err(e);
}
},
crate::cli::args::ApiKeyAction::Validate => {
eprintln!("⚠️ Validate action not implemented");
std::process::exit(1);
}
crate::cli::args::ApiKeyAction::Revoke => {
eprintln!("⚠️ Revoke action not implemented");
std::process::exit(1);
}
crate::cli::args::ApiKeyAction::Rotate => {
eprintln!("⚠️ Rotate action not implemented");
std::process::exit(1);
}
crate::cli::args::ApiKeyAction::Stats => {
eprintln!("⚠️ Stats action not implemented");
std::process::exit(1);
}
}
Ok(())
}
/// Handle Gitea integration command
pub async fn handle_gitea(
action: &crate::cli::args::GiteaAction,
name: Option<String>,
url: Option<String>,
token: Option<String>,
repo_id: Option<String>,
) -> Result<()> {
match action {
crate::cli::args::GiteaAction::Create => {
println!("Creating Gitea integration...");
// TODO: Implement Gitea integration creation
}
crate::cli::args::GiteaAction::List => {
println!("Listing Gitea integrations...");
// TODO: Implement Gitea integration listing
}
crate::cli::args::GiteaAction::Delete => {
let repo_id = repo_id.expect("Repository ID required for deletion");
println!("Deleting Gitea integration: {}", repo_id);
// TODO: Implement Gitea integration deletion
}
crate::cli::args::GiteaAction::Verify => {
println!("Verifying Gitea integration...");
// TODO: Implement Gitea integration verification
}
}
Ok(())
}
/// Handle store-asrx command
pub async fn handle_store_asrx(uuid: &str) -> Result<()> {
let db = momentry_core::core::db::postgres_db::PostgresDb::new(
&momentry_core::core::config::DATABASE_URL,
)
.await?;
momentry_core::core::pipeline::store_asrx_chunks(&db, uuid).await
}
/// Handle phase1 command
pub async fn handle_phase1(uuid: &str) -> Result<()> {
momentry_core::core::pipeline::run_phase1(uuid).await
}
/// Handle tkg-backfill command
pub async fn handle_tkg_backfill(file_uuid: &str) -> Result<()> {
let db = momentry_core::core::db::postgres_db::PostgresDb::new(
&momentry_core::core::config::DATABASE_URL,
)
.await?;
let output_dir = momentry_core::core::config::OUTPUT_DIR.as_str();
let n = momentry_core::core::processor::tkg::backfill_trace_dirs(&db, file_uuid, output_dir)
.await?;
tracing::info!(
"[tkg-backfill] built {} trace artifact dirs for {}",
n,
file_uuid
);
Ok(())
}
/// Handle complete command
pub async fn handle_complete(uuid: &str) -> Result<()> {
let db = momentry_core::core::db::postgres_db::PostgresDb::new(
&momentry_core::core::config::DATABASE_URL,
)
.await?;
momentry_core::core::pipeline::mark_complete(&db, uuid).await
}