Files
momentry_core/src/api/files.rs
T
Accusys 85d5e1fe51 feat: trace_id i64→i32 fix, OCR search filter, Rule1 OCR trigger
- Fix trace_id SQL type mismatch: i64 → i32 in profile.rs structs and queries
- Add /ocr /asr /asrx search filter suffix to keyword/semantic/smart search
- Fix fetch_ocr_texts to handle both OCR data formats (string array + object array)
- Add has_ocr trigger for Rule1 chunk ingestion in job_worker.rs
- Add search_bm25 chunk_type filter parameter
- Fix single-frame video clip duration (0-frame → 1-frame minimum)
- Re-run Rule1 for 14 files with stuck OCR in pre_chunks
2026-07-30 19:34:35 +08:00

1879 lines
67 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use axum::{
extract::{Path, Query, State},
http::StatusCode,
response::Json,
routing::{get, post},
Router,
};
use serde::{Deserialize, Serialize};
use sqlx::Row;
use std::collections::HashMap;
use super::types::AppState;
use crate::core::config;
use crate::core::db::schema;
use crate::core::db::{Database, PostgresDb, QdrantDb, QdrantWorkspace, RedisClient};
use crate::core::storage::content_hash;
use crate::FileManager;
#[derive(Debug, Deserialize)]
struct RegisterFileRequest {
file_path: String,
user_id: Option<i64>,
content_hash: Option<String>,
pattern: Option<String>,
#[serde(default = "default_force")]
force: bool,
}
fn default_force() -> bool {
true
}
#[derive(Debug, Deserialize, Serialize)]
struct FileLookupMatch {
file_uuid: String,
file_name: String,
file_type: Option<String>,
status: String,
content_hash: Option<String>,
file_size: Option<i64>,
duration: Option<f64>,
width: Option<i32>,
height: Option<i32>,
}
#[derive(Serialize)]
struct FileLookupResponse {
file_name: String,
exists: bool,
matches: Vec<FileLookupMatch>,
next_name: String,
}
async fn lookup_file_by_name(
State(state): State<AppState>,
Query(params): Query<HashMap<String, String>>,
) -> Result<Json<FileLookupResponse>, StatusCode> {
let file_name = params.get("file_name").ok_or(StatusCode::BAD_REQUEST)?;
let base = file_name.to_string();
let dot_pos = base.rfind('.');
let (stem, _ext) = match dot_pos {
Some(p) => (base[..p].to_string(), base[p..].to_string()),
None => (base.clone(), String::new()),
};
let pattern = format!("{}%%", &stem);
let table = schema::table_name("videos");
let query_sql = format!("SELECT file_uuid, file_name, file_type, status, content_hash, duration, width, height FROM {} WHERE file_name = $1 OR file_name LIKE $2 ORDER BY file_name", table);
let rows = sqlx::query(&query_sql)
.bind(&base)
.bind(&pattern)
.fetch_all(state.db.pool())
.await
.map_err(|e| {
tracing::error!("lookup query error: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let exists = rows.iter().any(|r| r.get::<String, _>("file_name") == base);
let matches: Vec<FileLookupMatch> = rows
.iter()
.map(|r| FileLookupMatch {
file_uuid: r.get("file_uuid"),
file_name: r.get("file_name"),
file_type: r.get("file_type"),
status: r.get("status"),
content_hash: r.get("content_hash"),
file_size: None,
duration: r.get("duration"),
width: r.get("width"),
height: r.get("height"),
})
.collect();
let next_name = if exists {
let mut attempt = 1usize;
loop {
let candidate = if let Some(p) = dot_pos {
format!("{} ({}){}", &base[..p], attempt, &base[p..])
} else {
format!("{} ({})", base, attempt)
};
let conflict: Option<String> = sqlx::query_scalar(&format!(
"SELECT file_uuid FROM {} WHERE file_name = $1",
table
))
.bind(&candidate)
.fetch_optional(state.db.pool())
.await
.unwrap_or(None);
if conflict.is_none() {
break candidate;
}
attempt += 1;
}
} else {
base.clone()
};
Ok(Json(FileLookupResponse {
file_name: base,
exists,
matches,
next_name,
}))
}
#[derive(Debug, Serialize)]
struct RegisterFileResponse {
success: bool,
file_uuid: String,
file_name: String,
file_path: String,
file_type: Option<String>,
duration: f64,
width: u32,
height: u32,
fps: f64,
total_frames: u64,
registration_time: Option<String>,
already_exists: bool,
message: String,
#[serde(skip_serializing_if = "Option::is_none")]
warning: Option<String>,
}
#[derive(Debug, Serialize)]
struct ProbeResponse {
file_uuid: String,
file_name: String,
file_size: Option<i64>,
duration: f64,
width: u32,
height: u32,
fps: f64,
total_frames: u64,
file_type: Option<String>,
probe_result: Option<serde_json::Value>,
}
// --- Fields-only structs for response ---
fn sha256_file(path: &std::path::Path) -> Option<String> {
content_hash::compute_sha256(path).ok()
}
async fn resolve_filename(db: &PostgresDb, file_name: &str, content_hash: &str) -> String {
let table = schema::table_name("videos");
let base = file_name.to_string();
let dot_pos = base.rfind('.');
let (stem, ext) = match dot_pos {
Some(p) => (base[..p].to_string(), base[p..].to_string()),
None => (base.clone(), String::new()),
};
let mut candidate = base.clone();
let mut attempt = 0usize;
loop {
let conflict: Option<String> = sqlx::query_scalar(
&format!("SELECT file_uuid FROM {} WHERE file_name = $1 AND (content_hash IS DISTINCT FROM $2 OR content_hash IS NULL)", table)
)
.bind(&candidate)
.bind(content_hash)
.fetch_optional(db.pool())
.await
.unwrap_or(None);
if conflict.is_none() {
return candidate;
}
attempt += 1;
candidate = format!("{} ({}){}", stem, attempt, ext);
}
}
async fn register_single_file(
state: &AppState,
file_path: &str,
_user_id: Option<i64>,
provided_hash: Option<String>,
force: bool,
) -> RegisterFileResponse {
tracing::info!("[REGISTER] Starting registration for: {}", file_path);
let path = std::path::Path::new(file_path);
if !path.exists() {
return RegisterFileResponse {
success: false,
file_uuid: String::new(),
file_name: String::new(),
file_path: file_path.to_string(),
file_type: None,
duration: 0.0,
width: 0,
height: 0,
fps: 0.0,
total_frames: 0,
registration_time: None,
already_exists: false,
message: format!("File not found: {}", file_path),
warning: None,
};
}
let canonical_path = path
.canonicalize()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| file_path.to_string());
let file_name = path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
let db = match PostgresDb::init().await {
Ok(db) => db,
Err(e) => {
tracing::error!("[REGISTER] DB init failed: {}", e);
return RegisterFileResponse {
success: false,
file_uuid: String::new(),
file_name,
file_path: canonical_path,
file_type: None,
duration: 0.0,
width: 0,
height: 0,
fps: 0.0,
total_frames: 0,
registration_time: None,
already_exists: false,
message: format!("DB init failed: {}", e),
warning: None,
};
}
};
let output_dir = std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/output_dev".to_string());
let birthday = std::fs::metadata(&path)
.ok()
.and_then(|m| m.modified().ok())
.map(|t| {
let secs = t
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
chrono::DateTime::from_timestamp(secs as i64, 0)
.map(|dt| dt.to_rfc3339())
.unwrap_or_else(|| chrono::Utc::now().to_rfc3339())
})
.unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
let mac_address = crate::core::storage::uuid::get_mac_address();
let pre_file_uuid = crate::core::storage::uuid::compute_birth_uuid(
&mac_address,
&birthday,
&canonical_path,
&file_name,
);
let pre_path = std::path::Path::new(&output_dir).join(format!("{}.pre.json", pre_file_uuid));
let pre_data: Option<serde_json::Value> = std::fs::read_to_string(&pre_path)
.ok()
.and_then(|s| serde_json::from_str(&s).ok());
let (content_hash_val, birthday, _pre_file_uuid) = if let Some(ref pre) = pre_data {
let h = pre
.get("content_hash")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let b = pre
.get("birthday")
.and_then(|v| v.as_str())
.unwrap_or(&birthday)
.to_string();
let u = pre
.get("file_uuid")
.and_then(|v| v.as_str())
.unwrap_or(&pre_file_uuid)
.to_string();
(h, b, u)
} else {
let h = provided_hash
.filter(|h| !h.is_empty())
.unwrap_or_else(|| sha256_file(&path).unwrap_or_default());
(h, birthday, pre_file_uuid)
};
let file_uuid = crate::core::storage::uuid::compute_birth_uuid(
&mac_address,
&birthday,
&canonical_path,
&file_name,
);
tracing::info!(
"[REGISTER] UUID inputs: mac={} birthday={} path={} name={} pre_found={} → {}",
mac_address,
birthday,
canonical_path,
file_name,
pre_data.is_some(),
file_uuid
);
let videos_table = schema::table_name("videos");
if !content_hash_val.is_empty() {
if let Ok(Some(existing_uuid)) = sqlx::query_scalar::<_, String>(&format!(
"SELECT file_uuid FROM {} WHERE content_hash = $1 LIMIT 1",
videos_table
))
.bind(&content_hash_val)
.fetch_optional(db.pool())
.await
{
tracing::info!(
"[REGISTER] Content hash collision → already registered: {}",
existing_uuid
);
// If force=true, unregister asynchronously then continue
if force {
tracing::info!(
"[REGISTER] Force mode: async unregistering existing file {}",
existing_uuid
);
if let Err(e) = unregister_internal(&state, &existing_uuid).await {
tracing::error!(
"[REGISTER] Force unregister failed for {}: {:?}",
existing_uuid,
e
);
} else {
tracing::info!(
"[REGISTER] Force unregister completed for {}",
existing_uuid
);
}
} else {
let existing_info: Option<(String, String, f64, i32, i32, f64, i64, Option<String>)> = sqlx::query_as(
&format!("SELECT file_name, file_path, duration, width, height, fps, total_frames, registration_time::text FROM {} WHERE file_uuid = $1", videos_table)
).bind(&existing_uuid).fetch_optional(db.pool()).await.unwrap_or(None);
if let Some((ename, epath, dur, w, h, f, tf, rt)) = existing_info {
return RegisterFileResponse {
success: true,
file_uuid: existing_uuid,
file_name: ename,
file_path: epath.clone(),
file_type: None,
duration: dur,
width: w as u32,
height: h as u32,
fps: f,
total_frames: tf as u64,
registration_time: rt,
already_exists: true,
message: format!("Content already registered: {}", epath),
warning: None,
};
}
return RegisterFileResponse {
success: true,
file_uuid: existing_uuid,
file_name: file_name.clone(),
file_path: canonical_path.clone(),
file_type: None,
duration: 0.0,
width: 0,
height: 0,
fps: 0.0,
total_frames: 0,
registration_time: None,
already_exists: true,
message: "Content already registered (identical file)".to_string(),
warning: None,
};
}
}
}
let final_name = resolve_filename(&db, &file_name, &content_hash_val).await;
let mac_address = crate::core::storage::uuid::get_mac_address();
let file_uuid = crate::core::storage::uuid::compute_birth_uuid(
&mac_address,
&birthday,
&canonical_path,
&final_name,
);
let temp_probe_json: serde_json::Value = if let Some(ref pre) = pre_data {
pre.get("probe_json").cloned().unwrap_or_default()
} else {
let scripts_dir = std::env::var("MOMENTRY_SCRIPTS_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry_core_0.1/scripts".to_string());
let python_path = std::env::var("MOMENTRY_PYTHON_PATH")
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string());
crate::core::probe::unified::unified_probe(&path, &scripts_dir, &python_path).await
};
let probe_json = Some(temp_probe_json.clone());
let has_video = temp_probe_json
.get("streams")
.and_then(|s| s.as_array())
.map_or(false, |streams| {
streams
.iter()
.any(|st| st.get("codec_type").and_then(|c| c.as_str()) == Some("video"))
});
let has_audio = temp_probe_json
.get("streams")
.and_then(|s| s.as_array())
.map_or(false, |streams| {
streams
.iter()
.any(|st| st.get("codec_type").and_then(|c| c.as_str()) == Some("audio"))
});
let final_file_type = if has_video {
Some("video".to_string())
} else if has_audio {
Some("audio".to_string())
} else {
Some(
temp_probe_json
.get("format")
.and_then(|f| f.get("file_type"))
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string(),
)
};
let duration = temp_probe_json
.get("format")
.and_then(|f| f.get("duration"))
.and_then(|v| v.as_str())
.and_then(|s| s.parse::<f64>().ok())
.unwrap_or_else(|| {
temp_probe_json
.get("streams")
.and_then(|s| s.as_array())
.and_then(|streams| streams.iter().next())
.and_then(|st| st.get("duration"))
.and_then(|v| v.as_str())
.and_then(|s| s.parse::<f64>().ok())
.unwrap_or(0.0)
});
let mut width = 0u32;
let mut height = 0u32;
let mut fps = 0.0;
let mut total_frames = 0u64;
if let Some(streams) = temp_probe_json.get("streams").and_then(|s| s.as_array()) {
if let Some(s) = streams
.iter()
.find(|st| st.get("codec_type").and_then(|c| c.as_str()) == Some("video"))
{
width = s.get("width").and_then(|v| v.as_i64()).unwrap_or(0) as u32;
height = s.get("height").and_then(|v| v.as_i64()).unwrap_or(0) as u32;
if let Some(fps_str) = s.get("r_frame_rate").and_then(|v| v.as_str()) {
if let Some((num, den)) = fps_str.split_once('/') {
if let (Ok(n), Ok(d)) = (num.parse::<f64>(), den.parse::<f64>()) {
if d > 0.0 {
fps = n / d;
}
}
}
}
total_frames = s
.get("nb_frames")
.and_then(|v| v.as_str())
.and_then(|s| s.parse().ok())
.unwrap_or_else(|| (duration * fps) as u64);
}
}
let status = "registered";
let _ = sqlx::query(&format!(
"INSERT INTO {} (file_uuid, file_path, file_name, file_type, duration, width, height, fps, probe_json, status, content_hash, registration_time) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, NOW()) ON CONFLICT (file_uuid) DO UPDATE SET file_path = EXCLUDED.file_path, file_name = EXCLUDED.file_name, status = EXCLUDED.status, content_hash = EXCLUDED.content_hash, duration = EXCLUDED.duration, width = EXCLUDED.width, height = EXCLUDED.height, fps = EXCLUDED.fps, probe_json = EXCLUDED.probe_json",
videos_table
))
.bind(&file_uuid).bind(&canonical_path).bind(&final_name).bind(&final_file_type)
.bind(duration).bind(width as i32).bind(height as i32).bind(fps)
.bind(&probe_json).bind(status).bind(&content_hash_val)
.execute(db.pool()).await;
let mut cut_done = false;
if has_video && total_frames > 0 && fps > 0.0 {
let output_dir = std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/output_dev".to_string());
let scripts_dir = std::env::var("MOMENTRY_SCRIPTS_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry_core_0.1/scripts".to_string());
let python_path = std::env::var("MOMENTRY_PYTHON_PATH")
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string());
let cut_path = std::path::Path::new(&output_dir).join(format!("{}.cut.json", file_uuid));
if !cut_path.exists() {
let cut_script = std::path::Path::new(&scripts_dir).join("cut_processor.py");
if cut_script.exists() {
let cut_output = std::process::Command::new(&python_path)
.arg(&cut_script)
.arg(&canonical_path)
.arg(&cut_path)
.output();
if let Ok(output) = cut_output {
if output.status.success() {
cut_done = true;
tracing::info!("[REGISTER] CUT completed for {}", file_uuid);
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[REGISTER] CUT failed for {}: {}", file_uuid, stderr);
}
} else {
tracing::error!("[REGISTER] CUT execution error for {}", file_uuid);
}
}
} else {
cut_done = true;
if let Ok(content) = std::fs::read_to_string(&cut_path) {
if let Ok(cut_data) = serde_json::from_str::<serde_json::Value>(&content) {
let scenes = cut_data
.get("scenes")
.and_then(|s| s.as_array())
.map(|a| a.len() as i32)
.unwrap_or(0);
tracing::info!(
"[REGISTER] CUT already exists: {} scenes for {}",
scenes,
file_uuid
);
}
}
}
}
let audio_tracks: Vec<serde_json::Value> = temp_probe_json
.get("streams")
.and_then(|s| s.as_array())
.map_or(vec![], |streams| {
streams
.iter()
.filter(|st| st.get("codec_type").and_then(|c| c.as_str()) == Some("audio"))
.map(|st| {
serde_json::json!({
"index": st.get("index").and_then(|v| v.as_i64()),
"codec": st.get("codec_name").and_then(|v| v.as_str()),
"channels": st.get("channels").and_then(|v| v.as_i64()),
"sample_rate": st.get("sample_rate").and_then(|v| v.as_str()),
"language": st.get("tags").and_then(|t| t.get("language")),
})
})
.collect()
});
let audio_tracks_json = serde_json::to_value(&audio_tracks).ok();
let cut_path = std::path::Path::new(
&std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/output_dev".to_string()),
)
.join(format!("{}.cut.json", file_uuid));
let mut cut_count = 0i32;
let mut cut_max_duration = 0.0f64;
if let Ok(content) = std::fs::read_to_string(&cut_path) {
if let Ok(cut_data) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(scenes) = cut_data.get("scenes").and_then(|s| s.as_array()) {
cut_count = scenes.len() as i32;
cut_max_duration = scenes
.iter()
.filter_map(|s| {
let start = s.get("start_time").and_then(|v| v.as_f64()).unwrap_or(0.0);
let end = s.get("end_time").and_then(|v| v.as_f64()).unwrap_or(0.0);
if end > start {
Some(end - start)
} else {
None
}
})
.fold(0.0_f64, f64::max);
}
}
}
let _ = sqlx::query(
&format!("UPDATE {} SET cut_done = $1, scene_done = false, audio_tracks = $3, cut_count = $4, cut_max_duration = $5 WHERE file_uuid = $6", videos_table)
)
.bind(cut_done).bind(&audio_tracks_json).bind(cut_count).bind(cut_max_duration).bind(&file_uuid)
.execute(db.pool()).await;
if let Some(json_val) = probe_json {
let probe_path = std::path::Path::new(
&std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/output_dev".to_string()),
)
.join(format!("{}.probe.json", file_uuid));
let json_str = serde_json::to_string_pretty(&json_val).unwrap_or_default();
let _ = std::fs::write(&probe_path, json_str);
}
RegisterFileResponse {
success: true,
file_uuid,
file_name,
file_path: canonical_path,
file_type: final_file_type,
duration,
width,
height,
fps,
total_frames,
registration_time: None,
already_exists: false,
message: "File registered successfully".to_string(),
warning: None,
}
}
async fn register_file(
State(state): State<AppState>,
Json(req): Json<RegisterFileRequest>,
) -> Result<Json<RegisterFileResponse>, StatusCode> {
let worker_running = super::health::check_worker_alive(&state).await;
let worker_warning = if !worker_running {
Some("Worker is not running - file will be registered but not processed automatically".to_string())
} else {
None
};
let file_path = req.file_path.clone();
let pattern = req.pattern;
if let Some(ref pat) = pattern {
let dir = std::path::Path::new(&file_path);
if !dir.is_dir() {
return Ok(Json(RegisterFileResponse {
success: false,
file_uuid: String::new(),
file_name: String::new(),
file_path: file_path.clone(),
file_type: None,
duration: 0.0,
width: 0,
height: 0,
fps: 0.0,
total_frames: 0,
registration_time: None,
already_exists: false,
message: format!(
"Pattern requires a directory, but path is not a dir: {}",
file_path
),
warning: None,
}));
}
let re = regex::Regex::new(pat).map_err(|e| {
tracing::error!("[REGISTER] Invalid regex pattern: {}", e);
StatusCode::BAD_REQUEST
})?;
let mut registered = 0u32;
let mut failed = 0u32;
let mut skipped = 0u32;
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.flatten() {
let entry_path = entry.path();
if !entry_path.is_file() {
continue;
}
let fname = entry_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("");
if !re.is_match(fname) {
continue;
}
let result = register_single_file(
&state,
&entry_path.to_string_lossy().to_string(),
req.user_id,
None,
req.force,
)
.await;
if result.success {
registered += 1;
} else if result.already_exists {
skipped += 1;
} else {
failed += 1;
}
}
}
return Ok(Json(RegisterFileResponse {
success: true,
file_uuid: format!("batch_{}_registered_{}_failed", registered, failed),
file_name: format!(
"{} files registered, {} skipped, {} failed",
registered, skipped, failed
),
file_path: file_path.clone(),
file_type: None,
duration: 0.0,
width: 0,
height: 0,
fps: 0.0,
total_frames: 0,
registration_time: None,
already_exists: false,
message: format!(
"Batch register: {} registered, {} skipped, {} failed",
registered, skipped, failed
),
warning: worker_warning.clone(),
}));
}
// If force=true and file already exists, unregister first
if req.force {
let videos_table = schema::table_name("videos");
// Check by file_path first
if let Ok(Some(existing_uuid)) = sqlx::query_scalar::<_, String>(&format!(
"SELECT file_uuid FROM {} WHERE file_path = $1 LIMIT 1",
videos_table
))
.bind(&file_path)
.fetch_optional(state.db.pool())
.await
{
tracing::info!(
"[REGISTER] Force mode: unregistering existing file {}",
existing_uuid
);
if let Err(e) = unregister_internal(&state, &existing_uuid).await {
tracing::error!(
"[REGISTER] Force unregister failed for {}: {:?}",
existing_uuid,
e
);
}
}
// Also check by content_hash if provided
if let Some(ref content_hash) = req.content_hash {
if let Ok(Some(existing_uuid)) = sqlx::query_scalar::<_, String>(&format!(
"SELECT file_uuid FROM {} WHERE content_hash = $1 LIMIT 1",
videos_table
))
.bind(content_hash)
.fetch_optional(state.db.pool())
.await
{
tracing::info!(
"[REGISTER] Force mode: unregistering by content_hash {}",
existing_uuid
);
if let Err(e) = unregister_internal(&state, &existing_uuid).await {
tracing::error!(
"[REGISTER] Force unregister failed for {}: {:?}",
existing_uuid,
e
);
}
}
}
}
let mut resp =
register_single_file(&state, &file_path, req.user_id, req.content_hash, req.force).await;
if worker_warning.is_some() {
resp.warning = worker_warning;
}
if resp.success
&& !resp.already_exists
&& resp.file_type.as_deref() == Some("video")
&& crate::core::config::get_auto_pipeline_enabled()
{
let auto_uuid = resp.file_uuid.clone();
let auto_state = state.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
let video_path: Option<String> = sqlx::query_scalar(&format!(
"SELECT file_path FROM {} WHERE file_uuid = $1",
schema::table_name("videos")
))
.bind(&auto_uuid)
.fetch_optional(auto_state.db.pool())
.await
.ok()
.flatten();
if let Some(ref vp) = video_path {
if let Ok(job) = auto_state.db.create_monitor_job(&auto_uuid, Some(vp)).await {
tracing::info!("[AUTO-PIPELINE] Job {} created for {}", job.id, auto_uuid);
let all_procs: Vec<&str> =
vec!["cut", "asr", "asrx", "ocr", "face", "pose", "appearance"];
let total = sqlx::query_scalar::<_, i64>(&format!(
"SELECT COALESCE(total_frames, 0) FROM {} WHERE file_uuid = $1",
schema::table_name("videos")
))
.bind(&auto_uuid)
.fetch_one(auto_state.db.pool())
.await
.unwrap_or(0);
let _ = auto_state
.db
.init_processing_status(&auto_uuid, all_procs, total as u64)
.await;
let _ = sqlx::query(&format!(
"UPDATE {} SET status = 'scanning' WHERE file_uuid = $1",
schema::table_name("videos")
))
.bind(&auto_uuid)
.execute(auto_state.db.pool())
.await;
tracing::info!("[AUTO-PIPELINE] Pipeline triggered for {}", auto_uuid);
}
}
});
}
Ok(Json(resp))
}
async fn probe_by_uuid(
State(state): State<AppState>,
Path(file_uuid): Path<String>,
) -> Result<Json<ProbeResponse>, (StatusCode, Json<serde_json::Value>)> {
let table = schema::table_name("videos");
let row: Option<(String, String)> = sqlx::query_as(&format!(
"SELECT file_name, file_path FROM {} WHERE file_uuid = $1",
table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
tracing::error!("DB error fetching video: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("DB error: {}", e), "file_uuid": file_uuid})),
)
})?;
let (file_name, path) = row.ok_or_else(|| {
tracing::warn!("Video not found: {}", file_uuid);
(
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": "Video not found", "file_uuid": file_uuid})),
)
})?;
let probe_path = format!(
"{}/{}.probe.json",
crate::core::config::OUTPUT_DIR.as_str(),
file_uuid
);
let (probe_result, cached) = if let Ok(content) = std::fs::read_to_string(&probe_path) {
tracing::info!("Using cached probe.json: {}", probe_path);
let result: crate::core::probe::ProbeResult =
serde_json::from_str(&content).map_err(|e| {
tracing::error!("Failed to parse cached probe.json: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Failed to parse cached probe.json: {}", e), "file_uuid": file_uuid})),
)
})?;
(result, true)
} else {
let file_path = std::path::Path::new(&path);
if !file_path.exists() {
tracing::error!("File not found at path: {}", path);
return Err((
StatusCode::NOT_FOUND,
Json(
serde_json::json!({"error": "File does not exist at registered path", "file_uuid": file_uuid, "file_path": path}),
),
));
}
tracing::info!("Running ffprobe for: {}", path);
let result = crate::core::probe::probe_video(&path).map_err(|e| {
tracing::error!("ffprobe failed: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("ffprobe failed: {}", e), "file_uuid": file_uuid, "file_path": path})),
)
})?;
let file_manager = FileManager::new(std::path::PathBuf::from(
crate::core::config::OUTPUT_DIR.as_str(),
));
let json_str = serde_json::to_string(&result).map_err(|e| {
tracing::error!("Failed to serialize probe result: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Failed to serialize probe result: {}", e), "file_uuid": file_uuid})),
)
})?;
file_manager
.save_json(&file_uuid, "probe", &json_str)
.map_err(|e| {
tracing::error!("Failed to save probe.json: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Failed to save probe.json: {}", e), "file_uuid": file_uuid})),
)
})?;
(result, false)
};
let duration = probe_result
.format
.duration
.as_ref()
.and_then(|s| s.parse::<f64>().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 {
fps = if fps_str.contains('/') {
let parts: Vec<&str> = fps_str.split('/').collect();
if parts.len() == 2 {
let num: f64 = parts[0].parse().unwrap_or(0.0);
let den: f64 = parts[1].parse().unwrap_or(1.0);
if den > 0.0 {
num / den
} else {
0.0
}
} else {
0.0
}
} else {
fps_str.parse().unwrap_or(0.0)
};
}
}
}
let total_frames = probe_result
.streams
.iter()
.find(|s| s.codec_type.as_deref() == Some("video"))
.and_then(|s| s.nb_frames.as_ref())
.and_then(|n| n.parse::<i64>().ok())
.unwrap_or_else(|| (duration * fps).floor() as i64);
let _ = sqlx::query(&format!(
"UPDATE {} SET duration = $1, width = $2, height = $3, fps = $4, total_frames = $5 WHERE file_uuid = $6",
schema::table_name("videos")
))
.bind(duration)
.bind(width as i32)
.bind(height as i32)
.bind(fps)
.bind(total_frames)
.bind(&file_uuid)
.execute(state.db.pool())
.await;
let file_size = std::fs::metadata(&path).ok().map(|m| m.len() as i64);
let file_type = if width > 0 && height > 0 {
Some("video".to_string())
} else {
None
};
Ok(Json(ProbeResponse {
file_uuid,
file_name,
file_size,
duration,
width,
height,
fps,
total_frames: total_frames as u64,
file_type,
probe_result: if cached {
Some(serde_json::to_value(&probe_result).unwrap_or_default())
} else {
None
},
}))
}
#[derive(Debug, Serialize)]
struct UnregisterResponse {
success: bool,
message: String,
file_uuid: String,
deleted_face_detections: u64,
deleted_processor_results: u64,
deleted_chunks: u64,
deleted_tkg_nodes: u64,
deleted_qdrant_vectors: Option<u64>,
deleted_qdrant_workspace: Option<u64>,
deleted_redis_keys: Option<u64>,
deleted_output_files: u64,
deleted_file_identities: u64,
deleted_speaker_detections: u64,
deleted_face_clusters: u64,
deleted_face_recognition_results: u64,
deleted_characters: u64,
deleted_chunks_rule1: u64,
deleted_processor_alerts: u64,
deleted_processor_versions: u64,
}
#[derive(Debug, Deserialize)]
struct UnregisterRequest {
file_uuid: Option<String>,
file_path: Option<String>,
}
fn delete_output_files(uuid: &str) -> u64 {
let mut deleted_count = 0u64;
let output_dirs = [
config::OUTPUT_DIR.to_string(),
"/Users/accusys/momentry/output_dev".to_string(),
"/Users/accusys/momentry/output".to_string(),
];
for output_dir in &output_dirs {
if let Ok(entries) = std::fs::read_dir(output_dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
let is_uuid_file = name.starts_with(uuid) && !path.is_dir();
let is_pipeline_log = name.starts_with("pipeline_")
&& name.contains(uuid)
&& name.ends_with(".log");
if is_uuid_file || is_pipeline_log {
if std::fs::remove_file(&path).is_ok() {
deleted_count += 1;
tracing::info!("[UNREGISTER] Deleted output file: {}", name);
}
}
}
}
}
let uuid_dir = std::path::Path::new(output_dir).join(uuid);
if uuid_dir.is_dir() {
if std::fs::remove_dir_all(&uuid_dir).is_ok() {
deleted_count += 1;
tracing::info!(
"[UNREGISTER] Deleted output directory: {}",
uuid_dir.display()
);
}
}
}
let workspace_sqlite = format!("{}.workspace.sqlite", uuid);
for output_dir in &output_dirs {
let path = std::path::Path::new(output_dir).join(&workspace_sqlite);
if path.exists() && std::fs::remove_file(&path).is_ok() {
deleted_count += 1;
tracing::info!("[UNREGISTER] Deleted workspace SQLite: {}", path.display());
}
}
tracing::info!(
"[UNREGISTER] Deleted {} output files for {}",
deleted_count,
uuid
);
if deleted_count == 0 {
tracing::warn!(
"[UNREGISTER] No output files found to delete for {}",
uuid
);
}
deleted_count
}
async fn unregister(
State(state): State<AppState>,
Json(req): Json<UnregisterRequest>,
) -> Result<Json<UnregisterResponse>, StatusCode> {
let uuid = match req.file_uuid {
Some(u) => u,
None => return Err(StatusCode::BAD_REQUEST),
};
tracing::info!("[UNREGISTER] Unregistering file: {}", uuid);
let videos_table = schema::table_name("videos");
let processor_table = schema::table_name("processor_results");
let chunks_table = schema::table_name("chunk");
let parent_chunks_table = schema::table_name("parent_chunks");
let pre_chunks_table = schema::table_name("pre_chunks");
let tkg_nodes_table = schema::table_name("tkg_nodes");
let cuts_table = schema::table_name("cuts");
let strangers_table = schema::table_name("strangers");
let chunk_vectors_table = schema::table_name("chunk_vectors");
let monitor_jobs_table = schema::table_name("monitor_jobs");
let frames_table = schema::table_name("frames");
let file_identities_table = schema::table_name("file_identities");
let speaker_detections_table = schema::table_name("speaker_detections");
let face_clusters_table = schema::table_name("face_clusters");
let face_recognition_results_table = schema::table_name("face_recognition_results");
let characters_table = schema::table_name("characters");
let chunks_rule1_table = schema::table_name("chunks_rule1");
let processor_alerts_table = schema::table_name("processor_alerts");
let mut tx = state.db.pool().begin().await.map_err(|e| {
tracing::error!("[unregister] Failed to start transaction: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
macro_rules! delete_safe {
($table:expr, $where:expr, $bind:expr, $label:expr) => {{
sqlx::query(&format!("DELETE FROM {} WHERE {}", $table, $where))
.bind($bind)
.execute(&mut *tx)
.await
.map_err(|e| {
tracing::error!("[unregister] Failed to delete {}: {}", $label, e);
StatusCode::INTERNAL_SERVER_ERROR
})?
.rows_affected() as i64
}};
}
let deleted_faces = 0i64; // Deprecated: face_detections table removed
let deleted_processors = delete_safe!(processor_table, "file_uuid = $1", &uuid, "processors");
let deleted_parent_chunks =
delete_safe!(parent_chunks_table, "uuid = $1", &uuid, "parent chunks");
let deleted_chunks = delete_safe!(chunks_table, "file_uuid = $1", &uuid, "chunks");
let deleted_pre_chunks = delete_safe!(pre_chunks_table, "file_uuid = $1", &uuid, "pre_chunks");
let deleted_tkg_nodes = delete_safe!(tkg_nodes_table, "file_uuid = $1", &uuid, "TKG nodes");
let deleted_cuts = delete_safe!(cuts_table, "file_uuid = $1", &uuid, "cuts");
let deleted_strangers = delete_safe!(strangers_table, "file_uuid = $1", &uuid, "strangers");
let deleted_chunk_vectors =
delete_safe!(chunk_vectors_table, "uuid = $1", &uuid, "chunk vectors");
let deleted_monitor_jobs = delete_safe!(monitor_jobs_table, "uuid = $1", &uuid, "monitor jobs");
let deleted_frames: i64 = sqlx::query(&format!(
"DELETE FROM {} WHERE file_id = (SELECT id FROM {} WHERE file_uuid = $1)",
frames_table, videos_table
))
.bind(&uuid)
.execute(&mut *tx)
.await
.map_err(|e| {
tracing::error!("[unregister] Failed to delete frames: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?
.rows_affected() as i64;
let deleted_file_identities = delete_safe!(
file_identities_table,
"file_uuid = $1",
&uuid,
"file identities"
);
let deleted_speaker_detections = delete_safe!(
speaker_detections_table,
"file_uuid = $1",
&uuid,
"speaker detections"
);
let deleted_face_clusters = delete_safe!(
face_clusters_table,
"file_uuid = $1",
&uuid,
"face clusters"
);
let deleted_face_recognition = delete_safe!(
face_recognition_results_table,
"file_uuid = $1",
&uuid,
"face recognition results"
);
let deleted_characters = delete_safe!(characters_table, "file_uuid = $1", &uuid, "characters");
let deleted_chunks_rule1 = delete_safe!(chunks_rule1_table, "uuid = $1", &uuid, "chunks rule1");
let deleted_processor_alerts = delete_safe!(
processor_alerts_table,
"file_uuid = $1",
&uuid,
"processor alerts"
);
let deleted_processor_versions = delete_safe!(
"processor_versions",
"file_uuid = $1",
&uuid,
"processor versions"
);
sqlx::query(&format!(
"DELETE FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(&uuid)
.execute(&mut *tx)
.await
.map_err(|e| {
tracing::error!("[unregister] Failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
tx.commit().await.map_err(|e| {
tracing::error!("[unregister] Failed to commit transaction: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
tracing::info!(
"[UNREGISTER] Deleted: {} faces, {} processors, {} parent_chunks, {} chunks, {} pre_chunks, {} tkg_nodes, {} cuts, {} strangers, {} chunk_vectors, {} monitor_jobs, {} frames, {} file_identities, {} speaker_detections, {} face_clusters, {} face_recognition_results, {} characters, {} chunks_rule1, {} processor_alerts, {} processor_versions",
deleted_faces, deleted_processors, deleted_parent_chunks, deleted_chunks,
deleted_pre_chunks, deleted_tkg_nodes, deleted_cuts, deleted_strangers,
deleted_chunk_vectors, deleted_monitor_jobs, deleted_frames,
deleted_file_identities, deleted_speaker_detections, deleted_face_clusters,
deleted_face_recognition, deleted_characters, deleted_chunks_rule1,
deleted_processor_alerts, deleted_processor_versions
);
let deleted_output_files = delete_output_files(&uuid);
let deleted_qdrant_vectors = {
let qdrant = QdrantDb::new();
let mut total = 0u64;
if qdrant.delete_by_uuid(&uuid).await.is_ok() {
tracing::info!("[UNREGISTER] Deleted Qdrant vectors from main collection");
total += 1;
} else {
tracing::warn!("[UNREGISTER] Failed to delete Qdrant vectors from main collection");
}
let additional_collections = [
"_faces", // Python store_traced_faces.py
&format!("{}_voice", uuid), // Per-file voice embeddings
];
for coll in &additional_collections {
if QdrantDb::delete_by_uuid_from_collection(
&qdrant.client,
&qdrant.base_url,
&qdrant.api_key,
coll,
&uuid,
)
.await
.is_ok()
{
tracing::info!(
"[UNREGISTER] Deleted Qdrant vectors from collection: {}",
coll
);
total += 1;
} else {
tracing::debug!("[UNREGISTER] No vectors or collection not found: {}", coll);
}
}
Some(total)
};
let deleted_redis_keys = {
match RedisClient::new() {
Ok(redis) => {
let mut deleted = 0;
// Delete worker job keys
if redis.delete_worker_job(&uuid).await.is_ok() {
tracing::info!("[UNREGISTER] Deleted Redis worker job keys for {}", uuid);
deleted += 1;
}
// Delete PipelineProgress keys (all variants)
let progress_patterns = [
format!("{}progress:{}:pipeline", crate::core::config::REDIS_KEY_PREFIX.as_str(), uuid),
format!("{}progress:{}:agent", crate::core::config::REDIS_KEY_PREFIX.as_str(), uuid),
format!("{}progress:{}:tkg", crate::core::config::REDIS_KEY_PREFIX.as_str(), uuid),
];
if let Ok(mut conn) = redis.get_conn().await {
for key in &progress_patterns {
let _: Option<String> = redis::cmd("DEL")
.arg(key)
.query_async(&mut conn)
.await
.ok();
}
tracing::info!("[UNREGISTER] Deleted Redis PipelineProgress keys for {}", uuid);
deleted += progress_patterns.len() as u64;
}
Some(deleted)
}
Err(e) => {
tracing::warn!("[UNREGISTER] Failed to create Redis client: {}", e);
None
}
}
};
let deleted_qdrant_workspace = {
let workspace = QdrantWorkspace::new();
match workspace.delete_by_file_uuid(&uuid).await {
Ok(_) => {
tracing::info!("[UNREGISTER] Deleted Qdrant workspace vectors for {}", uuid);
Some(1)
}
Err(e) => {
tracing::warn!(
"[UNREGISTER] Failed to delete Qdrant workspace vectors: {}",
e
);
None
}
}
};
Ok(Json(UnregisterResponse {
success: true,
message: format!("File {} unregistered successfully.", uuid),
file_uuid: uuid,
deleted_face_detections: deleted_faces as u64,
deleted_processor_results: deleted_processors as u64,
deleted_chunks: (deleted_chunks + deleted_parent_chunks + deleted_pre_chunks) as u64,
deleted_tkg_nodes: deleted_tkg_nodes as u64,
deleted_qdrant_vectors,
deleted_qdrant_workspace,
deleted_redis_keys,
deleted_output_files,
deleted_file_identities: deleted_file_identities as u64,
deleted_speaker_detections: deleted_speaker_detections as u64,
deleted_face_clusters: deleted_face_clusters as u64,
deleted_face_recognition_results: deleted_face_recognition as u64,
deleted_characters: deleted_characters as u64,
deleted_chunks_rule1: deleted_chunks_rule1 as u64,
deleted_processor_alerts: deleted_processor_alerts as u64,
deleted_processor_versions: deleted_processor_versions as u64,
}))
}
/// Internal unregister function - can be called from both API and register
async fn unregister_internal(state: &AppState, uuid: &str) -> Result<(), StatusCode> {
let videos_table = schema::table_name("videos");
let processor_table = schema::table_name("processor_results");
let chunks_table = schema::table_name("chunk");
let parent_chunks_table = schema::table_name("parent_chunks");
let pre_chunks_table = schema::table_name("pre_chunks");
let tkg_nodes_table = schema::table_name("tkg_nodes");
let cuts_table = schema::table_name("cuts");
let strangers_table = schema::table_name("strangers");
let chunk_vectors_table = schema::table_name("chunk_vectors");
let monitor_jobs_table = schema::table_name("monitor_jobs");
let frames_table = schema::table_name("frames");
let file_identities_table = schema::table_name("file_identities");
let speaker_detections_table = schema::table_name("speaker_detections");
let face_clusters_table = schema::table_name("face_clusters");
let face_recognition_results_table = schema::table_name("face_recognition_results");
let characters_table = schema::table_name("characters");
let chunks_rule1_table = schema::table_name("chunks_rule1");
let processor_alerts_table = schema::table_name("processor_alerts");
let mut tx = state.db.pool().begin().await.map_err(|e| {
tracing::error!("[unregister] Failed to start transaction: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
macro_rules! delete_safe {
($table:expr, $where:expr, $bind:expr, $label:expr) => {{
sqlx::query(&format!("DELETE FROM {} WHERE {}", $table, $where))
.bind($bind)
.execute(&mut *tx)
.await
.map_err(|e| {
tracing::error!("[unregister] Failed to delete {}: {}", $label, e);
StatusCode::INTERNAL_SERVER_ERROR
})?
.rows_affected() as i64
}};
}
let _deleted_faces: i64 = 0; // Deprecated: face_detections table removed
let _deleted_processors = delete_safe!(processor_table, "file_uuid = $1", uuid, "processors");
let _deleted_parent_chunks =
delete_safe!(parent_chunks_table, "uuid = $1", uuid, "parent chunks");
let _deleted_chunks = delete_safe!(chunks_table, "file_uuid = $1", uuid, "chunks");
let _deleted_pre_chunks = delete_safe!(pre_chunks_table, "file_uuid = $1", uuid, "pre_chunks");
let _deleted_tkg_nodes = delete_safe!(tkg_nodes_table, "file_uuid = $1", uuid, "TKG nodes");
let _deleted_cuts = delete_safe!(cuts_table, "file_uuid = $1", uuid, "cuts");
let _deleted_strangers = delete_safe!(strangers_table, "file_uuid = $1", uuid, "strangers");
let _deleted_chunk_vectors =
delete_safe!(chunk_vectors_table, "uuid = $1", uuid, "chunk vectors");
let _deleted_monitor_jobs = delete_safe!(monitor_jobs_table, "uuid = $1", uuid, "monitor jobs");
let _deleted_frames: i64 = sqlx::query(&format!(
"DELETE FROM {} WHERE file_id = (SELECT id FROM {} WHERE file_uuid = $1)",
frames_table, videos_table
))
.bind(uuid)
.execute(&mut *tx)
.await
.map_err(|e| {
tracing::error!("[unregister] Failed to delete frames: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?
.rows_affected() as i64;
let _deleted_file_identities = delete_safe!(
file_identities_table,
"file_uuid = $1",
uuid,
"file identities"
);
let _deleted_speaker_detections = delete_safe!(
speaker_detections_table,
"file_uuid = $1",
uuid,
"speaker detections"
);
let _deleted_face_clusters =
delete_safe!(face_clusters_table, "file_uuid = $1", uuid, "face clusters");
let _deleted_face_recognition = delete_safe!(
face_recognition_results_table,
"file_uuid = $1",
uuid,
"face recognition results"
);
let _deleted_characters = delete_safe!(characters_table, "file_uuid = $1", uuid, "characters");
let _deleted_chunks_rule1 = delete_safe!(chunks_rule1_table, "uuid = $1", uuid, "chunks rule1");
let _deleted_processor_alerts = delete_safe!(
processor_alerts_table,
"file_uuid = $1",
uuid,
"processor alerts"
);
let _deleted_processor_versions = delete_safe!(
"processor_versions",
"file_uuid = $1",
uuid,
"processor versions"
);
sqlx::query(&format!(
"DELETE FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(uuid)
.execute(&mut *tx)
.await
.map_err(|e| {
tracing::error!("[unregister] Failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
tx.commit().await.map_err(|e| {
tracing::error!("[unregister] Failed to commit transaction: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
tracing::info!("[UNREGISTER] Deleted all data for {}", uuid);
// Delete output files
delete_output_files(uuid);
// Delete Qdrant vectors
let qdrant = QdrantDb::new();
let _ = qdrant.delete_by_uuid(uuid).await;
let _ = QdrantDb::delete_by_uuid_from_collection(
&qdrant.client,
&qdrant.base_url,
&qdrant.api_key,
"_faces",
uuid,
)
.await;
// Delete from speaker collection
let schema = std::env::var("DATABASE_SCHEMA").unwrap_or_else(|_| "dev".to_string());
let speaker_collection = if schema == "public" {
"momentry_public_speaker"
} else {
&format!("momentry_{}_speaker", schema)
};
let _ = QdrantDb::delete_by_uuid_from_collection(
&qdrant.client,
&qdrant.base_url,
&qdrant.api_key,
speaker_collection,
uuid,
)
.await;
// Delete Qdrant workspace
let workspace = QdrantWorkspace::new();
let _ = workspace.delete_by_file_uuid(uuid).await;
// Delete Redis keys
if let Ok(redis) = RedisClient::new() {
let _ = redis.delete_worker_job(uuid).await;
}
Ok(())
}
#[derive(Debug, Deserialize)]
struct UpdateMetadataRequest {
duration: Option<f64>,
status: Option<String>,
width: Option<i32>,
height: Option<i32>,
fps: Option<f64>,
}
#[derive(Serialize)]
struct UpdateMetadataResponse {
success: bool,
file_uuid: String,
message: String,
}
async fn update_file_metadata(
Path(file_uuid): Path<String>,
State(state): State<AppState>,
Json(req): Json<UpdateMetadataRequest>,
) -> Result<Json<UpdateMetadataResponse>, StatusCode> {
let videos_table = schema::table_name("videos");
let mut set_clauses: Vec<String> = Vec::new();
let mut bind_idx = 2;
if let Some(_) = req.duration {
set_clauses.push(format!("duration = ${}", bind_idx));
bind_idx += 1;
}
if let Some(_) = req.status {
set_clauses.push(format!("status = ${}", bind_idx));
bind_idx += 1;
}
if let Some(_) = req.width {
set_clauses.push(format!("width = ${}", bind_idx));
bind_idx += 1;
}
if let Some(_) = req.height {
set_clauses.push(format!("height = ${}", bind_idx));
bind_idx += 1;
}
if let Some(_) = req.fps {
set_clauses.push(format!("fps = ${}", bind_idx));
bind_idx += 1;
}
if set_clauses.is_empty() {
return Ok(Json(UpdateMetadataResponse {
success: false,
file_uuid,
message: "No fields to update".to_string(),
}));
}
set_clauses.push("updated_at = NOW()".to_string());
let sql = format!(
"UPDATE {} SET {} WHERE file_uuid = $1",
videos_table,
set_clauses.join(", ")
);
let mut query = sqlx::query(&sql).bind(&file_uuid);
if let Some(d) = req.duration {
query = query.bind(d);
}
if let Some(s) = req.status {
query = query.bind(s);
}
if let Some(w) = req.width {
query = query.bind(w);
}
if let Some(h) = req.height {
query = query.bind(h);
}
if let Some(f) = req.fps {
query = query.bind(f);
}
let result = query.execute(state.db.pool()).await;
match result {
Ok(res) if res.rows_affected() > 0 => Ok(Json(UpdateMetadataResponse {
success: true,
file_uuid,
message: "Metadata updated successfully".to_string(),
})),
Ok(_) => Ok(Json(UpdateMetadataResponse {
success: false,
file_uuid,
message: "File not found".to_string(),
})),
Err(e) => {
tracing::error!("[METADATA] Update failed: {}", e);
Ok(Json(UpdateMetadataResponse {
success: false,
file_uuid,
message: format!("Update failed: {}", e),
}))
}
}
}
pub fn file_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/files/register", post(register_file))
.route("/api/v1/files/lookup", get(lookup_file_by_name))
.route("/api/v1/unregister", post(unregister))
.route("/api/v1/file/:file_uuid/probe", get(probe_by_uuid))
.route(
"/api/v1/file/:file_uuid/metadata",
post(update_file_metadata),
)
.route(
"/api/v1/file/:file_uuid/sync-status",
post(sync_file_status),
)
}
async fn sync_file_status(
Path(file_uuid): Path<String>,
State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
use crate::core::config::OUTPUT_DIR;
let output_dir = OUTPUT_DIR.as_str();
let videos_table = schema::table_name("videos");
let chunk_table = schema::table_name("chunk");
let tp_table = schema::table_name("trace_profiles");
let tkg_nodes_table = schema::table_name("tkg_nodes");
let tkg_edges_table = schema::table_name("tkg_edges");
// 檢查 processor JSON 是否存在
let processors = [
("asr", "asr.json"),
("asrx", "asrx.json"),
("ocr", "ocr.json"),
("pose", "pose.json"),
("cut", "cut.json"),
("face", "face.json"),
("face_cluster", "face_cluster.json"),
];
let mut processor_status = serde_json::Map::new();
let mut errors = Vec::new();
let mut all_consistent = true;
let mut any_json_exists = false;
for (name, filename) in &processors {
let path = std::path::Path::new(output_dir).join(format!("{}.{}", file_uuid, filename));
let json_exists = path.exists();
let mut consistent = false;
if json_exists {
any_json_exists = true;
// 讀取 JSON 內容
match std::fs::read_to_string(&path) {
Ok(content) => {
if let Ok(json_data) = serde_json::from_str::<serde_json::Value>(&content) {
// 檢查 DB 與 JSON 是否一致
let pre_table = schema::table_name("pre_chunks");
consistent = match *name {
"asr" => {
let json_count = json_data.get("segments").and_then(|s| s.as_array()).map(|a| a.len()).unwrap_or(0);
let is_no_audio = json_data.get("status").and_then(|s| s.as_str()) == Some("no_audio_track")
|| json_data.get("status").and_then(|s| s.as_str()) == Some("silent_audio");
let db_count: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'asr'", pre_table
))
.bind(&file_uuid).fetch_one(state.db.pool()).await.unwrap_or(0);
is_no_audio || (json_count as i64) == db_count
}
"asrx" => {
let json_count = json_data.get("segments").and_then(|s| s.as_array()).map(|a| a.len()).unwrap_or(0);
let db_count: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'asrx'", pre_table
))
.bind(&file_uuid).fetch_one(state.db.pool()).await.unwrap_or(0);
(json_count as i64) == db_count
}
"ocr" => {
// pre_chunks 存的是 grouped chunks (zone + proximity grouping),
// 不等於 frame count,只要 JSON 存在就視為一致
true
}
"cut" => {
let json_count = json_data.get("scenes").and_then(|s| s.as_array()).map(|a| a.len()).unwrap_or(0);
let db_count: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND processor_type = 'cut'", pre_table
))
.bind(&file_uuid).fetch_one(state.db.pool()).await.unwrap_or(0);
(json_count as i64) == db_count
}
"face" => {
// face 已遷移至 Qdrant,不再比對 pre_chunks
true
}
"face_cluster" => {
// cluster 數量可能不等於 trace 數量,只要 JSON 存在就視為一致
true
}
"pose" => {
// pose 通常不需要入庫 chunks,只要 JSON 存在就視為一致
true
}
_ => true,
};
} else {
errors.push(serde_json::json!({
"processor": name,
"error": "JSON parse failed"
}));
consistent = false;
}
}
Err(e) => {
errors.push(serde_json::json!({
"processor": name,
"error": format!("Read failed: {}", e)
}));
consistent = false;
}
}
}
// JSON not existing also counts as inconsistent
if !consistent {
all_consistent = false;
}
processor_status.insert(name.to_string(), serde_json::json!({
"json_exists": json_exists,
"consistent": consistent
}));
}
// 如果有錯誤,回傳錯誤
if !errors.is_empty() {
return Ok(Json(serde_json::json!({
"success": false,
"file_uuid": file_uuid,
"status": "error",
"errors": errors
})));
}
// 檢查 DB 進階狀態
let has_sentence: bool = sqlx::query_scalar(&format!(
"SELECT 1 FROM {} WHERE file_uuid = $1 AND chunk_type = 'sentence' LIMIT 1", chunk_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.unwrap_or(None)
.unwrap_or(0) > 0;
let has_tkg_nodes: bool = sqlx::query_scalar(&format!(
"SELECT 1 FROM {} WHERE file_uuid = $1 LIMIT 1", tkg_nodes_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.unwrap_or(None)
.unwrap_or(0) > 0;
let has_tkg_edges: bool = sqlx::query_scalar(&format!(
"SELECT 1 FROM {} WHERE file_uuid = $1 LIMIT 1", tkg_edges_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.unwrap_or(None)
.unwrap_or(0) > 0;
// 查詢 processing_status phase
let phase: String = sqlx::query_scalar(&format!(
"SELECT COALESCE(processing_status->>'phase', '') FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.ok()
.flatten()
.unwrap_or_default();
let phase_completed = phase == "COMPLETED";
// 狀態判斷
let new_status = if all_consistent && any_json_exists {
"completed"
} else if any_json_exists {
// 部分 JSON 存在或不一致 → 入庫中
"scanning"
} else {
// 無 JSON → 未開始
"registered"
};
// 更新 DB status
sqlx::query(&format!(
"UPDATE {} SET status = $1, updated_at = NOW() WHERE file_uuid = $2",
videos_table
))
.bind(new_status)
.bind(&file_uuid)
.execute(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[SYNC_STATUS] Update failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
// 查詢 monitor_jobs 取得 worker 狀態
let monitor_jobs_table = schema::table_name("monitor_jobs");
let job: Option<(String, Option<String>, i32, i32, Vec<String>, Vec<String>, Option<chrono::NaiveDateTime>)> =
sqlx::query_as(&format!(
"SELECT status, current_processor, progress_total, progress_current, \
completed_processors, failed_processors, updated_at \
FROM {} WHERE uuid = $1 ORDER BY created_at DESC LIMIT 1",
monitor_jobs_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.ok()
.flatten();
let worker_info = if let Some((status, current_proc, total, current, completed, failed, updated)) = job {
serde_json::json!({
"has_job": true,
"job_status": status,
"current_processor": current_proc,
"progress_total": total,
"progress_current": current,
"completed_processors": completed,
"failed_processors": failed,
"updated_at": updated.map(|t| t.format("%Y-%m-%dT%H:%M:%S").to_string())
})
} else {
serde_json::json!({
"has_job": false
})
};
Ok(Json(serde_json::json!({
"success": true,
"file_uuid": file_uuid,
"status": new_status,
"processors": processor_status,
"worker": worker_info
})))
}