diff --git a/markbase-core/src/server.rs b/markbase-core/src/server.rs index 084a7f0..e71e827 100644 --- a/markbase-core/src/server.rs +++ b/markbase-core/src/server.rs @@ -9,7 +9,10 @@ use axum::{ Router, }; use base64::Engine as _; +use bcrypt::{hash, DEFAULT_COST}; +use rusqlite::Connection; use serde::{Deserialize, Serialize}; +use std::path::PathBuf; use std::str::FromStr; use std::sync::{Arc, LazyLock, Mutex, OnceLock}; use std::time::{Duration, Instant}; @@ -26,6 +29,89 @@ use crate::render; use filetree::{self, FileTree}; use tower_http::cors::CorsLayer; +/// Initialize database with demo user if not exists +fn init_database(db_path: &PathBuf, home: &PathBuf) -> anyhow::Result<()> { + let db_exists = db_path.exists(); + + // Create database if not exists + let conn = Connection::open(db_path)?; + + if !db_exists { + log::info!("Creating new database: {}", db_path.display()); + + // Create tables + conn.execute_batch( + r#" + CREATE TABLE IF NOT EXISTS sftpgo_users ( + username TEXT PRIMARY KEY, + password_hash TEXT NOT NULL, + email TEXT, + status INTEGER DEFAULT 1, + home_dir TEXT, + permissions TEXT, + uid INTEGER, + gid INTEGER, + last_login INTEGER, + created_at INTEGER, + updated_at INTEGER, + last_sync_at INTEGER, + sync_status INTEGER DEFAULT 0 + ); + + CREATE INDEX IF NOT EXISTS idx_users_status ON sftpgo_users(status); + CREATE INDEX IF NOT EXISTS idx_users_sync_status ON sftpgo_users(sync_status); + + CREATE TABLE IF NOT EXISTS sftpgo_groups ( + name TEXT PRIMARY KEY, + description TEXT, + created_at INTEGER, + updated_at INTEGER, + last_sync_at INTEGER + ); + + CREATE TABLE IF NOT EXISTS users_groups_mapping ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL, + group_name TEXT NOT NULL, + created_at INTEGER, + FOREIGN KEY (username) REFERENCES sftpgo_users(username) ON DELETE CASCADE, + FOREIGN KEY (group_name) REFERENCES sftpgo_groups(name) ON DELETE CASCADE, + UNIQUE(username, group_name) + ); + + CREATE INDEX IF NOT EXISTS idx_mapping_username ON users_groups_mapping(username); + CREATE INDEX IF NOT EXISTS idx_mapping_group ON users_groups_mapping(group_name); + "#, + )?; + + // Create demo user with home directory relative to user's home + let demo_home = home.join("markbase").join("data").join("demo"); + let demo_home_str = demo_home.to_string_lossy().to_string(); + let password_hash = hash("demo123", DEFAULT_COST)?; + let created_at = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as i64; + + conn.execute( + "INSERT INTO sftpgo_users (username, password_hash, home_dir, permissions, status, uid, gid, created_at) + VALUES (?1, ?2, ?3, ?4, 1, 501, 20, ?5)", + rusqlite::params![ + "demo", + password_hash, + demo_home_str, + r#"{"*": ["/"]}"#, + created_at + ], + )?; + + log::info!("Created demo user: demo (password: demo123, home: {})", demo_home.display()); + log::info!("Demo user is ready for testing"); + } + + Ok(()) +} + #[derive(Clone)] pub struct AppState { pub html: Arc>, @@ -39,7 +125,23 @@ pub struct AppState { pub upload_path: String, } -pub async fn run(port: u16, file: Option) -> anyhow::Result<()> { +pub async fn run(port: u16, file: Option, home: PathBuf) -> anyhow::Result<()> { + // Initialize data directory structure + let data_dir = home.join("markbase").join("data"); + let users_dir = data_dir.join("users"); + let demo_dir = data_dir.join("demo"); + let auth_db_path = data_dir.join("auth.sqlite"); + + // Create directories if not exist + std::fs::create_dir_all(&users_dir)?; + std::fs::create_dir_all(&demo_dir)?; + + log::info!("Data directory: {}", data_dir.display()); + log::info!("Auth database: {}", auth_db_path.display()); + + // Initialize database with demo user if not exists + init_database(&auth_db_path, &home)?; + let welcome = if let Some(f) = &file { let md = std::fs::read_to_string(f).unwrap_or_default(); let body = render::md_to_html(&md); @@ -80,7 +182,12 @@ pub async fn run(port: u16, file: Option) -> anyhow::Result<()> { // Initialize admin WebDAV upload path + MyFiles upload path (replaces env var reads) let _ = UPLOAD_PATH.set(upload_path.clone()); - crate::myfiles::init_upload_path(upload_path.clone()); + // MyFiles uses VfsBackend (LocalFs) directly — no init needed + + let users_dir_str = users_dir.to_string_lossy().to_string(); + let auth_db_str = auth_db_path.to_string_lossy().to_string(); + let s3_keys_path = data_dir.join("s3_keys.json"); + let s3_keys_path_str = s3_keys_path.to_string_lossy().to_string(); let state = AppState { html: Arc::new(Mutex::new(html)), @@ -89,19 +196,19 @@ pub async fn run(port: u16, file: Option) -> anyhow::Result<()> { "step": 0, "total": 0, "id": "", "label": "", "voice": "off" }))), labels: Arc::new(Mutex::new(vec![])), - db_dir: "data/users".to_string(), + db_dir: users_dir_str.clone(), auth: AuthState::with_provider(Box::new( - SqliteProvider::new("data/auth.sqlite") + SqliteProvider::new(&auth_db_str) .map_err(|e| anyhow::anyhow!("Failed to init SqliteProvider: {}", e))?, )), - auth_db_path: "data/auth.sqlite".to_string(), + auth_db_path: auth_db_str.clone(), upload_path: upload_path.clone(), - s3_keys: Arc::new(Mutex::new(load_s3_keys())), + s3_keys: Arc::new(Mutex::new(load_s3_keys(&s3_keys_path_str))), }; // Load S3 keys from file - fn load_s3_keys() -> Vec { - if let Ok(content) = std::fs::read_to_string("data/s3_keys.json") { + fn load_s3_keys(path: &str) -> Vec { + if let Ok(content) = std::fs::read_to_string(path) { serde_json::from_str(&content).unwrap_or_default() } else { vec![ @@ -123,52 +230,62 @@ pub async fn run(port: u16, file: Option) -> anyhow::Result<()> { } } - // Initial sync from SFTPGo PostgreSQL - let syncer = crate::pg_client::SftpGoSync::new("data/auth.sqlite")?; - tokio::spawn(async move { - match syncer.full_sync().await { - Ok(result) => { - log::info!( - "Initial sync completed: users={}, groups={}, mappings={}, status={}", - result.users_synced, - result.groups_synced, - result.mappings_synced, - result.status - ); - } - Err(e) => { - log::error!("Initial sync failed: {}", e); - } - } - }); + // SFTPGo sync (optional fallback - default disabled) + // Set MARKBASE_ENABLE_SFTPGO_SYNC=1 to enable sync from SFTPGo PostgreSQL + let enable_sftpgo_sync = std::env::var("MARKBASE_ENABLE_SFTPGO_SYNC") + .map(|v| v == "1" || v.to_lowercase() == "true") + .unwrap_or(false); - // Periodic sync task (every hour) - let syncer_clone = crate::pg_client::SftpGoSync::new("data/auth.sqlite")?; - tokio::spawn(async move { - let mut interval = tokio::time::interval(std::time::Duration::from_secs(3600)); - loop { - interval.tick().await; - match syncer_clone.full_sync().await { + if enable_sftpgo_sync { + log::info!("SFTPGo sync enabled - syncing from PostgreSQL to auth.sqlite"); + let syncer = crate::pg_client::SftpGoSync::new(&auth_db_str)?; + tokio::spawn(async move { + match syncer.full_sync().await { Ok(result) => { log::info!( - "Hourly sync: users={}, groups={}, status={}", + "Initial sync completed: users={}, groups={}, mappings={}, status={}", result.users_synced, result.groups_synced, + result.mappings_synced, result.status ); } Err(e) => { - log::error!("Hourly sync failed, keeping cached data: {}", e); + log::error!("Initial sync failed: {}", e); } } - } - }); + }); + + let syncer_clone = crate::pg_client::SftpGoSync::new(&auth_db_str)?; + tokio::spawn(async move { + let mut interval = tokio::time::interval(std::time::Duration::from_secs(3600)); + loop { + interval.tick().await; + match syncer_clone.full_sync().await { + Ok(result) => { + log::info!( + "Hourly sync: users={}, groups={}, status={}", + result.users_synced, + result.groups_synced, + result.status + ); + } + Err(e) => { + log::error!("Hourly sync failed, keeping cached data: {}", e); + } + } + } + }); + } else { + log::info!("SFTPGo sync disabled - using local auth.sqlite for user management (set MARKBASE_ENABLE_SFTPGO_SYNC=1 to enable)"); + } + // ===== WebDAV multi-user configuration (Phase 20 + P1) ===== let webdav_parent = std::path::PathBuf::from(&upload_path); // WebDAV versioning storage - let version_storage = std::path::PathBuf::from("data/webdav_versions"); + let version_storage = data_dir.join("webdav_versions"); std::fs::create_dir_all(&version_storage).ok(); // Upload hook (disabled by default) @@ -229,6 +346,14 @@ pub async fn run(port: u16, file: Option) -> anyhow::Result<()> { // Admin authentication API endpoints (public) .route("/api/v2/admin/login", post(crate::api::admin::admin_login_handler)) .route("/api/v2/admin/verify", get(crate::api::admin::admin_verify_handler)) + // User management endpoints (require admin token) + .route("/api/v2/admin/users", get(crate::api::admin::list_users_handler).post(crate::api::admin::create_user_handler)) + .route("/api/v2/admin/users/:username", delete(crate::api::admin::delete_user_handler).put(crate::api::admin::update_user_handler)) + .route("/api/v2/admin/users/:username/password", post(crate::api::admin::change_password_handler)) + // Service management endpoints + .route("/api/v2/service/stop", post(service_stop_handler)) + .route("/api/v2/service/start", post(service_start_handler)) + .route("/api/v2/worker/status", get(worker_status_handler)) // Protected endpoints (require auth) .route("/api/v2/tree/:user_id", get(get_tree)) .route("/api/v2/tree/:user_id/search", get(search_tree)) @@ -325,12 +450,20 @@ pub async fn run(port: u16, file: Option) -> anyhow::Result<()> { // MyFiles User Interface (Web UI + API) .route("/myfiles", get(crate::myfiles::ui_page)) .route("/api/v2/myfiles/:username/folders", get(crate::myfiles::list_folders).post(crate::myfiles::create_folder)) - .route("/api/v2/myfiles/:username/folders/:folder_name", delete(crate::myfiles::delete_folder)) + .route("/api/v2/myfiles/:username/folders/tree", get(crate::myfiles::folder_tree)) + .route("/api/v2/myfiles/:username/folders/*folder_path", delete(crate::myfiles::delete_folder)) .route("/api/v2/myfiles/:username/files", get(crate::myfiles::list_files)) .route("/api/v2/myfiles/:username/files/:filename", delete(crate::myfiles::delete_file)) .route("/api/v2/myfiles/:username/tags", post(crate::myfiles::add_tag).delete(crate::myfiles::remove_tag)) + .route("/api/v2/myfiles/:username/move", post(crate::myfiles::move_file)) + .route("/api/v2/myfiles/:username/move-folder", post(crate::myfiles::move_folder)) + .route("/api/v2/myfiles/:username/rename-file", post(crate::myfiles::rename_file)) + .route("/api/v2/myfiles/:username/rename-folder", post(crate::myfiles::rename_folder)) .route("/api/v2/myfiles/:username/files/:filename/tags", get(crate::myfiles::file_tags)) .route("/api/v2/myfiles/:username/preview/:filename", get(crate::myfiles::preview_file)) + // Admin Panel endpoints + .route("/api/v2/admin/system-stats", get(admin_system_stats)) + .route("/api/v2/admin/shares", get(admin_list_shares)) // Backup/Snapshot API endpoints (Phase 5-6) .route("/api/v2/backup/stats", get(get_backup_stats_handler)) .route("/api/v2/backup/config", get(get_backup_config_handler).post(set_backup_config_handler)) @@ -1430,10 +1563,6 @@ async fn upload_unlimited( let base_dir = &state.upload_path; let user_dir = format!("{}/{}", base_dir, user_id); - let mut filename = String::new(); - let mut file_size: i64 = 0; - let mut file_hash = String::new(); - if let Err(e) = tokio::fs::create_dir_all(&user_dir).await { return ( StatusCode::INTERNAL_SERVER_ERROR, @@ -1442,18 +1571,99 @@ async fn upload_unlimited( .into_response(); } + // Collect all parts: text fields (small) and file fields (chunked) + enum Part { + Text(String, String), + File(String, String, Vec), // (field_name, filename, chunks) + } + let mut parts = Vec::new(); + while let Ok(Some(mut field)) = multipart.next_field().await { let name = field.name().unwrap_or("").to_string(); + if name == "folder" || name == "user_id" { + if let Ok(text) = field.text().await { + parts.push(Part::Text(name, text.trim().to_string())); + } + continue; + } if name != "file" { continue; } + let filename = field.file_name().unwrap_or("upload.bin").to_string(); + let mut chunks = Vec::new(); + while let Ok(Some(chunk)) = field.chunk().await { + chunks.push(chunk); + } + parts.push(Part::File(name, filename, chunks)); + } - filename = field.file_name().unwrap_or("upload.bin").to_string(); - let file_path = format!("{}/{}", user_dir, filename); + // Extract metadata fields + let mut folder = String::new(); + for part in &parts { + if let Part::Text(ref name, ref val) = part { + if name == "folder" { + folder = val.clone(); + } + } + } + + // Process file parts + let mut results = Vec::new(); + for part in parts { + let (filename, chunks) = match part { + Part::File(_, fname, chunks) => (fname, chunks), + _ => continue, + }; + + // Prepend folder to path if specified + let target_dir = if folder.is_empty() { + format!("{}/{}", base_dir, user_id) + } else { + let folder_clean = folder.trim_start_matches('/'); + format!("{}/{}/{}", base_dir, user_id, folder_clean) + }; + + if let Err(e) = tokio::fs::create_dir_all(&target_dir).await { + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({"error": format!("create_dir error: {}", e)})), + ) + .into_response(); + } + + let mut filename = filename; + + // Auto-suffix if file exists: test.txt → test_1.txt, test_2.txt, etc. + { + let fpath = format!("{}/{}", target_dir, filename); + if tokio::fs::try_exists(&fpath).await.unwrap_or(false) { + let fname = std::path::Path::new(&filename); + let stem = fname.file_stem().unwrap_or_default().to_str().unwrap_or(&filename); + let ext = fname.extension().and_then(|e| e.to_str()).unwrap_or(""); + let mut counter = 1; + loop { + let alt = if ext.is_empty() { + format!("{}_{}", stem, counter) + } else { + format!("{}_{}.{}", stem, counter, ext) + }; + let alt_path = format!("{}/{}", target_dir, alt); + if !tokio::fs::try_exists(&alt_path).await.unwrap_or(false) { + filename = alt; + break; + } + counter += 1; + } + } + } + + let stored_at = format!("{}/{}", target_dir, filename); + let file_path = stored_at.clone(); + let file_path = stored_at.clone(); // Create subdirectory if filename contains path (webkitdirectory) if let Some(parent) = std::path::Path::new(&file_path).parent() { - if parent != std::path::Path::new(&user_dir) { + if parent != std::path::Path::new(&target_dir) { if let Err(e) = tokio::fs::create_dir_all(parent).await { return ( StatusCode::INTERNAL_SERVER_ERROR, @@ -1478,11 +1688,10 @@ async fn upload_unlimited( } }; - while let Ok(Some(chunk)) = field.chunk().await { + for chunk in &chunks { total_written += chunk.len() as u64; - hasher.update(&chunk); - - if let Err(e) = file.write_all(&chunk).await { + hasher.update(chunk); + if let Err(e) = file.write_all(chunk).await { return ( StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": format!("write error: {}", e)})), @@ -1494,15 +1703,24 @@ async fn upload_unlimited( let _ = file.flush().await; drop(file); - file_hash = format!("{:x}", hasher.finalize()); - file_size = total_written as i64; + let file_hash = format!("{:x}", hasher.finalize()); + + results.push(serde_json::json!({ + "ok": true, + "filename": filename, + "file_size": total_written as i64, + "file_hash": file_hash, + "user_id": user_id, + "folder": folder, + "stored_at": stored_at, + "timestamp": chrono::Utc::now().to_rfc3339() + })); } - // Allow empty files (0 bytes) for .localized, .keep, .gitkeep, etc. - if filename.is_empty() { + if results.is_empty() { return ( StatusCode::BAD_REQUEST, - Json(serde_json::json!({"error": "no filename provided"})), + Json(serde_json::json!({"error": "no file provided"})), ) .into_response(); } @@ -1511,11 +1729,9 @@ async fn upload_unlimited( StatusCode::OK, Json(serde_json::json!({ "ok": true, - "filename": filename, - "file_size": file_size, - "file_hash": file_hash, + "files": results, "user_id": user_id, - "stored_at": format!("{}/{}", user_dir, filename), + "folder": folder, "timestamp": chrono::Utc::now().to_rfc3339() })), ) @@ -1916,6 +2132,62 @@ async fn login_handler( } } +// === Admin Panel Handlers === + +async fn admin_system_stats() -> impl IntoResponse { + let mut sys = sysinfo::System::new_all(); + sys.refresh_all(); + let cpu = sys.global_cpu_usage().round() as u32; + let mem_used = sys.used_memory(); + let mem_total = sys.total_memory(); + let memory = if mem_total > 0 { + ((mem_used as f64 / mem_total as f64) * 100.0).round() as u32 + } else { + 0 + }; + // Disk: parse df output (works on macOS and Linux) + let disk = if let Ok(output) = std::process::Command::new("df").arg("-k").arg("/").output() { + if let Ok(text) = String::from_utf8(output.stdout) { + if let Some(line) = text.lines().nth(1) { + let parts: Vec<&str> = line.split_whitespace().collect(); + if parts.len() >= 5 { + if let (Ok(total), Ok(used)) = (parts[1].parse::(), parts[2].parse::()) { + if total > 0.0 { + ((used / total) * 100.0).round() as u32 + } else { 0 } + } else { 0 } + } else { 0 } + } else { 0 } + } else { 0 } + } else { 0 }; + Json(serde_json::json!({"cpu": cpu, "memory": memory, "disk": disk})) +} + +async fn admin_list_users(State(state): State) -> impl IntoResponse { + let mut users = Vec::new(); + if let Some(provider) = &state.auth.provider { + if let Ok(user_list) = provider.list_users() { + for u in user_list { + users.push(serde_json::json!({ + "username": u.username, + "homeDir": u.home_dir.to_string_lossy(), + "status": u.status + })); + } + } + } + Json(serde_json::Value::Array(users)) +} + +async fn admin_list_shares() -> impl IntoResponse { + let shares = vec![ + serde_json::json!({"name": "MarkBase Web", "port": 11438, "status": "running", "protocol": "HTTP/WebDAV", "url": "http://localhost:11438"}), + serde_json::json!({"name": "SFTP", "port": 2024, "status": "running", "protocol": "SSH/SFTP"}), + serde_json::json!({"name": "SMB", "port": 4445, "status": "running", "protocol": "SMB"}), + ]; + Json(serde_json::Value::Array(shares)) +} + async fn logout_handler(State(state): State, headers: HeaderMap) -> impl IntoResponse { let auth_header = headers .get("Authorization") @@ -1990,6 +2262,199 @@ fn verify_auth(state: &AppState, headers: &HeaderMap) -> Result, +) -> impl IntoResponse { + let name = body.get("name").and_then(|v| v.as_str()).unwrap_or(""); + // Worker has no port — stop via pidfile / pkill instead of lsof + if name == "Worker" || name == "worker" { + let cmd = format!( + "sleep 0.5; WPID=$(cat /Users/accusys/momentry_core/logs/worker_3002.pid 2>/dev/null); \ + if [ -n \"$WPID\" ]; then pkill -P $WPID 2>/dev/null; kill -9 $WPID 2>/dev/null; fi; \ + pkill -9 -f 'target/release/momentry worker' 2>/dev/null; rm -f /Users/accusys/momentry_core/logs/worker_3002.pid; \ + echo 'stopped'" + ); + let _ = std::process::Command::new("sh").arg("-c").arg(cmd).spawn(); + return (StatusCode::OK, Json(serde_json::json!({"result": "stopped"}))).into_response(); + } + let port = match name { + "Core API" | "core" => 3002, + "MarkBase" | "markbase" => 11438, + "MarkBaseEngine" | "mbe" => 8080, + "SFTP" => 2024, + "SMB" => 4445, + "Proxy" | "proxy" => 8888, + _ => return (StatusCode::BAD_REQUEST, Json(serde_json::json!({"error": format!("Unknown service: {}", name)}))).into_response(), + }; + // Spawn (not wait) so the server can respond before killing itself + let _ = std::process::Command::new("sh") + .arg("-c") + .arg(format!("sleep 0.5; lsof -ti :{} | xargs kill -9 2>/dev/null; echo 'stopped'", port)) + .spawn(); + (StatusCode::OK, Json(serde_json::json!({"result": "stopped"}))).into_response() +} + +async fn service_start_handler( + Json(body): Json, +) -> impl IntoResponse { + let name = body.get("name").and_then(|v| v.as_str()).unwrap_or(""); + // Worker has no port — start via run script, poll pidfile for liveness + if name == "Worker" || name == "worker" { + let cmd = "cd /Users/accusys/momentry_core && nohup bash run-worker-3002.sh > /tmp/momentry_worker.log 2>&1 &"; + return match std::process::Command::new("sh").arg("-c").arg(cmd).output() { + Ok(_) => { + let mut waited = 0u64; + let step = 2u64; + let max_wait = 10u64; + while waited < max_wait { + std::thread::sleep(std::time::Duration::from_secs(step)); + waited += step; + let check = std::process::Command::new("sh") + .arg("-c") + .arg("WPID=$(cat /Users/accusys/momentry_core/logs/worker_3002.pid 2>/dev/null); [ -n \"$WPID\" ] && kill -0 $WPID 2>/dev/null && echo alive") + .output(); + if let Ok(c) = check { + if String::from_utf8_lossy(&c.stdout).contains("alive") { + return (StatusCode::OK, Json(serde_json::json!({"result": "started"}))).into_response(); + } + } + } + (StatusCode::OK, Json(serde_json::json!({"result": "started", "warning": "Worker pid check inconclusive, verify manually"}))).into_response() + } + Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": format!("Failed to start: {}", e)}))).into_response(), + }; + } + let (cmd, port) = match name { + "MarkBase" | "markbase" => ( + "cd /Users/accusys/markbase && nohup cargo run --bin markbase-core -- web-start --port 11438 > /tmp/markbase_web.log 2>&1 &", + 11438, + ), + "Core API" | "core" => ( + "cd /Users/accusys/momentry_core && nohup bash run-server-3002.sh > /tmp/momentry_start.log 2>&1 &", + 3002, + ), + "Proxy" | "proxy" => ( + "cd /Users/accusys/momentry_studio/src-tauri && nohup ./target/debug/momentry-proxy > /tmp/momentry_proxy.log 2>&1 &", + 8888, + ), + "MarkBaseEngine" | "mbe" => ( + "cd /Users/accusys/MarkBaseEngine && nohup .build/arm64-apple-macosx/release/MarkBaseServer E4B-MarkBase 8080 > /tmp/markbase_engine.log 2>&1 &", + 8080, + ), + "SFTP" => ( + "cd /Users/accusys/markbase && nohup cargo run --bin markbase-core -- ssh-start --port 2024 > /tmp/markbase_ssh.log 2>&1 &", + 2024, + ), + "SMB" => ( + "cd /Users/accusys/markbase && nohup cargo run --bin markbase-core --features smb-server -- smb-start --port 4445 --share-name markbase --root /Users/accusys/momentry/var/sftpgo/data --user demo:demo123 > /tmp/markbase_smb.log 2>&1 &", + 4445, + ), + _ => return (StatusCode::BAD_REQUEST, Json(serde_json::json!({"error": format!("Unknown service: {}", name)}))).into_response(), + }; + match std::process::Command::new("sh").arg("-c").arg(cmd).output() { + Ok(_) => { + // Poll for port up to 60s (MBE needs time to load model) + let max_wait = match port { + 8080 => 60u64, // MarkBaseEngine + _ => 5u64, + }; + let mut waited = 0u64; + let step = 2u64; + while waited < max_wait { + std::thread::sleep(std::time::Duration::from_secs(step)); + waited += step; + let check = std::process::Command::new("sh") + .arg("-c") + .arg(format!("lsof -ti :{} 2>/dev/null", port)) + .output(); + if let Ok(c) = check { + if !c.stdout.is_empty() { + return (StatusCode::OK, Json(serde_json::json!({"result": "started"}))).into_response(); + } + } + } + (StatusCode::OK, Json(serde_json::json!({"result": "started", "warning": "Port check inconclusive, verify manually"}))).into_response() + } + Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": format!("Failed to start: {}", e)}))).into_response(), + } +} + +async fn worker_status_handler() -> impl IntoResponse { + let pid_file = "/Users/accusys/momentry_core/logs/worker_3002.pid"; + let pid = std::fs::read_to_string(pid_file) + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()); + let mut running = false; + if let Some(pid_str) = &pid { + if let Ok(pid_num) = pid_str.parse::() { + running = std::process::Command::new("sh") + .arg("-c") + .arg(format!("kill -0 {} 2>/dev/null", pid_num)) + .output() + .map(|o| o.status.success()) + .unwrap_or(false); + } + } + if !running { + // Fallback: pgrep by process name + running = std::process::Command::new("sh") + .arg("-c") + .arg("pgrep -f 'target/release/momentry worker' >/dev/null 2>&1") + .output() + .map(|o| o.status.success()) + .unwrap_or(false); + } + let uptime = if running { + let etime = std::process::Command::new("sh") + .arg("-c") + .arg("ps -o etime= -p $(cat /Users/accusys/momentry_core/logs/worker_3002.pid 2>/dev/null) 2>/dev/null") + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) + .unwrap_or_default(); + parse_etime_seconds(&etime) + } else { + 0 + }; + ( + StatusCode::OK, + Json(serde_json::json!({ + "status": if running { "running" } else { "stopped" }, + "pid": pid.and_then(|p| p.parse::().ok()), + "uptime": uptime, + "version": "worker (momentry-core)", + })), + ) + .into_response() +} + +/// Parse `ps -o etime` output like `HH:MM:SS` / `MM:SS` / `D-HH:MM:SS` into seconds. +fn parse_etime_seconds(etime: &str) -> u64 { + let etime = etime.trim(); + if etime.is_empty() { + return 0; + } + let (days, rest) = if let Some((d, r)) = etime.split_once('-') { + (d.parse::().unwrap_or(0), r) + } else { + (0, etime) + }; + let parts: Vec<&str> = rest.split(':').collect(); + let secs = match parts.as_slice() { + [s] => s.parse::().unwrap_or(0), + [m, s] => m.parse::().unwrap_or(0) * 60 + s.parse::().unwrap_or(0), + [h, m, s] => { + h.parse::().unwrap_or(0) * 3600 + + m.parse::().unwrap_or(0) * 60 + + s.parse::().unwrap_or(0) + } + _ => 0, + }; + days * 86400 + secs +} + // === Sync Handlers === fn html_escape(s: &str) -> String { @@ -2400,7 +2865,6 @@ async fn handle_webdav_admin( // ============================================================================ use crate::vfs::{VfsBackend, local_fs::LocalFs, backup_scheduler::{BackupScheduler, BackupScheduleConfig}}; -use std::path::PathBuf; #[derive(Debug, Serialize, Deserialize)] pub struct BackupStatsResponse { @@ -2573,3 +3037,34 @@ async fn get_storage_stats_handler(Query(params): Query