1872 lines
64 KiB
Rust
1872 lines
64 KiB
Rust
use axum::{
|
||
extract::{Path, Query, State},
|
||
http::StatusCode,
|
||
response::Json,
|
||
routing::get,
|
||
Router,
|
||
};
|
||
use serde::{Deserialize, Serialize};
|
||
|
||
use super::types::AppState;
|
||
use crate::core::db::schema;
|
||
use crate::core::file_profile::{count_face_artifacts, FaceArtifactsCounts};
|
||
|
||
/// Comprehensive file stats endpoint — provides all data sources for frontend transparency
|
||
/// Combines: JSON file status + PostgreSQL counts + Qdrant collections + TKG stats + Identity Agent stats
|
||
#[derive(Debug, Serialize)]
|
||
struct FileStatsResponse {
|
||
file_uuid: String,
|
||
file_name: Option<String>,
|
||
status: Option<String>,
|
||
// Timestamps
|
||
created_at: Option<String>,
|
||
updated_at: Option<String>,
|
||
processing_completed_at: Option<String>,
|
||
// Processor status
|
||
processors: Vec<ProcessorStatus>,
|
||
// PostgreSQL counts
|
||
postgres: PostgresStats,
|
||
// ASRX stats
|
||
asrx: AsrxStats,
|
||
// Qdrant collection counts
|
||
qdrant: QdrantStats,
|
||
// TKG stats
|
||
tkg: TkgFileStats,
|
||
// Face Dedup stats
|
||
face_dedup: FaceDedupStats,
|
||
// VLM Summary progress
|
||
vlm_summary: VlmSummaryStats,
|
||
// Scene VLM stats
|
||
scene_vlm: SceneVlmStats,
|
||
// On-disk face artifact counts (vs expected)
|
||
face_artifacts: FaceArtifactsCounts,
|
||
}
|
||
|
||
#[derive(Debug, Serialize)]
|
||
struct ProcessorStatus {
|
||
name: String,
|
||
status: String,
|
||
progress: u32,
|
||
message: Option<String>,
|
||
}
|
||
|
||
#[derive(Debug, Serialize, Default)]
|
||
struct PostgresStats {
|
||
sentence_chunks: i64,
|
||
relationship_chunks: i64,
|
||
identities: i64,
|
||
file_identities: i64,
|
||
}
|
||
|
||
#[derive(Debug, Serialize, Default)]
|
||
struct AsrxStats {
|
||
status: Option<String>,
|
||
segment_count: i32,
|
||
language: Option<String>,
|
||
}
|
||
|
||
#[derive(Debug, Serialize)]
|
||
struct QdrantStats {
|
||
faces: i64,
|
||
face_traces: i64,
|
||
face_identities: i64,
|
||
text_chunks: i64,
|
||
speakers: i64,
|
||
}
|
||
|
||
#[derive(Debug, Serialize, Default)]
|
||
struct TkgFileStats {
|
||
total_nodes: i64,
|
||
total_edges: i64,
|
||
face_track_nodes: i64,
|
||
gaze_track_nodes: i64,
|
||
lip_track_nodes: i64,
|
||
text_region_nodes: i64,
|
||
appearance_nodes: i64,
|
||
accessory_nodes: i64,
|
||
object_nodes: i64,
|
||
hand_nodes: i64,
|
||
speaker_nodes: i64,
|
||
co_occurrence_edges: i64,
|
||
speaker_face_edges: i64,
|
||
face_face_edges: i64,
|
||
mutual_gaze_edges: i64,
|
||
lip_sync_edges: i64,
|
||
has_appearance_edges: i64,
|
||
wears_edges: i64,
|
||
hand_object_edges: i64,
|
||
}
|
||
|
||
#[derive(Debug, Serialize, Default)]
|
||
struct FaceDedupStats {
|
||
clusters: i64,
|
||
face_tracks: i64,
|
||
consistent: bool,
|
||
}
|
||
|
||
#[derive(Debug, Serialize, Default)]
|
||
struct VlmSummaryStats {
|
||
total: i64,
|
||
done: i64,
|
||
}
|
||
|
||
#[derive(Debug, Serialize, Default)]
|
||
struct SceneVlmStats {
|
||
total_scenes: i64,
|
||
status: String,
|
||
vlm_done: i64,
|
||
vlm_total: i64,
|
||
}
|
||
|
||
#[derive(Debug, Serialize, Deserialize)]
|
||
struct ScannedFileInfo {
|
||
file_name: String,
|
||
relative_path: String,
|
||
file_path: String,
|
||
file_size: u64,
|
||
modified_time: String,
|
||
is_registered: bool,
|
||
file_uuid: Option<String>,
|
||
status: Option<String>,
|
||
registration_time: Option<String>,
|
||
status_updated_at: Option<String>,
|
||
job_id: Option<i32>,
|
||
}
|
||
|
||
#[derive(Debug, Serialize, Deserialize)]
|
||
struct ScanFilesResponse {
|
||
files: Vec<ScannedFileInfo>,
|
||
total: usize,
|
||
filtered_total: usize,
|
||
page: usize,
|
||
page_size: usize,
|
||
total_pages: usize,
|
||
registered_count: usize,
|
||
unregistered_count: usize,
|
||
total_chunks: i64,
|
||
searchable_chunks: i64,
|
||
pending_videos: i64,
|
||
}
|
||
|
||
#[derive(Debug, Deserialize)]
|
||
struct ScanFilesQuery {
|
||
limit: Option<usize>,
|
||
page: Option<usize>,
|
||
page_size: Option<usize>,
|
||
pattern: Option<String>,
|
||
sort_by: Option<String>,
|
||
sort_order: Option<String>,
|
||
}
|
||
|
||
fn scan_directory_recursive(
|
||
dir: &std::path::Path,
|
||
root: &std::path::Path,
|
||
allowed_extensions: &[&str],
|
||
registered_paths: &std::collections::HashMap<
|
||
String,
|
||
(String, String, Option<String>, Option<String>, Option<i32>),
|
||
>,
|
||
files: &mut Vec<ScannedFileInfo>,
|
||
) {
|
||
if let Ok(entries) = std::fs::read_dir(dir) {
|
||
for entry in entries.flatten() {
|
||
let path = entry.path();
|
||
if path.is_dir() {
|
||
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
|
||
if name.starts_with('.') {
|
||
return;
|
||
}
|
||
}
|
||
scan_directory_recursive(&path, root, allowed_extensions, registered_paths, files);
|
||
} else if path.is_file() {
|
||
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
|
||
if allowed_extensions.contains(&ext.to_lowercase().as_str()) {
|
||
if let Ok(meta) = entry.metadata() {
|
||
let abs_path = path.to_string_lossy().to_string();
|
||
let rel_path = path
|
||
.strip_prefix(root)
|
||
.map(|p| p.to_string_lossy().to_string())
|
||
.unwrap_or_else(|_| abs_path.clone());
|
||
|
||
let file_name = path
|
||
.file_name()
|
||
.map(|n| n.to_string_lossy().to_string())
|
||
.unwrap_or_default();
|
||
|
||
let modified_time = meta
|
||
.modified()
|
||
.ok()
|
||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||
.map(|d| {
|
||
chrono::DateTime::from_timestamp(d.as_secs() as i64, 0)
|
||
.map(|dt| dt.to_rfc3339())
|
||
.unwrap_or_default()
|
||
})
|
||
.unwrap_or_default();
|
||
|
||
match registered_paths.get(&abs_path) {
|
||
Some((uuid, status, reg_time, updated_at, jid))
|
||
if status != "unregistered" =>
|
||
{
|
||
files.push(ScannedFileInfo {
|
||
file_name,
|
||
relative_path: rel_path,
|
||
file_path: abs_path,
|
||
file_size: meta.len(),
|
||
modified_time,
|
||
is_registered: true,
|
||
file_uuid: Some(uuid.clone()),
|
||
status: Some(status.clone()),
|
||
registration_time: reg_time.clone(),
|
||
status_updated_at: updated_at.clone(),
|
||
job_id: *jid,
|
||
});
|
||
}
|
||
_ => {
|
||
files.push(ScannedFileInfo {
|
||
file_name,
|
||
relative_path: rel_path,
|
||
file_path: abs_path,
|
||
file_size: meta.len(),
|
||
modified_time,
|
||
is_registered: false,
|
||
file_uuid: None,
|
||
status: Some("unregistered".to_string()),
|
||
registration_time: None,
|
||
status_updated_at: None,
|
||
job_id: None,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
async fn scan_files(
|
||
State(state): State<AppState>,
|
||
Query(params): Query<ScanFilesQuery>,
|
||
) -> Result<Json<ScanFilesResponse>, StatusCode> {
|
||
// 用 momentry root 而非 current_exe(部署時 binary 在 <root>/bin/ 下,
|
||
// 直接取 parent 會多一層 bin 導致掃描到錯誤目錄)。
|
||
let demo_dir_str = std::env::var("MOMENTRY_SFTP_ROOT").unwrap_or_else(|_| {
|
||
crate::core::path_utils::demo_dir()
|
||
.to_string_lossy()
|
||
.to_string()
|
||
});
|
||
let demo_dir = std::path::Path::new(&demo_dir_str);
|
||
|
||
let allowed_extensions = vec![
|
||
"mp4", "mov", "mkv", "avi", "webm", "jpg", "jpeg", "png", "gif", "webp",
|
||
];
|
||
|
||
let table = schema::table_name("videos");
|
||
let mj_table = schema::table_name("monitor_jobs");
|
||
let registered_db: Vec<(
|
||
String,
|
||
String,
|
||
String,
|
||
String,
|
||
Option<String>,
|
||
Option<String>,
|
||
Option<i32>,
|
||
)> = sqlx::query_as(&format!(
|
||
"SELECT v.file_path, v.file_name, v.file_uuid, v.status, v.registration_time::text, \
|
||
v.updated_at::text, \
|
||
latest_job.id as job_id \
|
||
FROM {} v \
|
||
LEFT JOIN LATERAL ( \
|
||
SELECT id FROM {} WHERE uuid = v.file_uuid ORDER BY id DESC LIMIT 1 \
|
||
) latest_job ON true \
|
||
ORDER BY v.id",
|
||
table, mj_table
|
||
))
|
||
.fetch_all(state.db.pool())
|
||
.await
|
||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||
|
||
let registered_paths: std::collections::HashMap<
|
||
String,
|
||
(String, String, Option<String>, Option<String>, Option<i32>),
|
||
> = registered_db
|
||
.into_iter()
|
||
.map(|(path, _name, uuid, status, reg_time, updated_at, jid)| {
|
||
(path, (uuid, status, reg_time, updated_at, jid))
|
||
})
|
||
.collect();
|
||
|
||
let mut result_files = Vec::new();
|
||
|
||
if demo_dir.exists() {
|
||
scan_directory_recursive(
|
||
demo_dir,
|
||
demo_dir,
|
||
&allowed_extensions,
|
||
®istered_paths,
|
||
&mut result_files,
|
||
);
|
||
}
|
||
|
||
let desc = params.sort_order.as_deref().unwrap_or("asc") == "desc";
|
||
match params.sort_by.as_deref().unwrap_or("name") {
|
||
"size" => {
|
||
if desc {
|
||
result_files.sort_by(|a, b| b.file_size.cmp(&a.file_size));
|
||
} else {
|
||
result_files.sort_by(|a, b| a.file_size.cmp(&b.file_size));
|
||
}
|
||
}
|
||
"modified" | "time" => {
|
||
if desc {
|
||
result_files.sort_by(|a, b| b.modified_time.cmp(&a.modified_time));
|
||
} else {
|
||
result_files.sort_by(|a, b| a.modified_time.cmp(&b.modified_time));
|
||
}
|
||
}
|
||
"status" => {
|
||
if desc {
|
||
result_files
|
||
.sort_by(|a, b| b.status.cmp(&a.status).then(b.file_name.cmp(&a.file_name)));
|
||
} else {
|
||
result_files
|
||
.sort_by(|a, b| a.status.cmp(&b.status).then(a.file_name.cmp(&b.file_name)));
|
||
}
|
||
}
|
||
_ => {
|
||
if desc {
|
||
result_files.sort_by(|a, b| {
|
||
a.is_registered
|
||
.cmp(&b.is_registered)
|
||
.then(b.file_name.cmp(&a.file_name))
|
||
});
|
||
} else {
|
||
result_files.sort_by(|a, b| {
|
||
b.is_registered
|
||
.cmp(&a.is_registered)
|
||
.then(a.file_name.cmp(&b.file_name))
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
let total_all = result_files.len();
|
||
let registered_count = result_files.iter().filter(|f| f.is_registered).count();
|
||
let unregistered_count = result_files.iter().filter(|f| !f.is_registered).count();
|
||
|
||
let filtered: Vec<ScannedFileInfo> = if let Some(ref pat) = params.pattern {
|
||
let re = match regex::Regex::new(&format!("(?i){}", pat)) {
|
||
Ok(r) => r,
|
||
Err(_) => return Err(StatusCode::BAD_REQUEST),
|
||
};
|
||
result_files
|
||
.into_iter()
|
||
.filter(|f| re.is_match(&f.file_name))
|
||
.collect()
|
||
} else {
|
||
result_files
|
||
};
|
||
|
||
let filtered_total = filtered.len();
|
||
|
||
let page = params.page.unwrap_or(1).max(1);
|
||
let page_size = params
|
||
.page_size
|
||
.or(params.limit)
|
||
.unwrap_or(filtered_total.max(1));
|
||
let total_pages = if page_size > 0 {
|
||
(filtered_total + page_size - 1) / page_size
|
||
} else {
|
||
1
|
||
};
|
||
let start = (page - 1) * page_size;
|
||
let files: Vec<ScannedFileInfo> = filtered.into_iter().skip(start).take(page_size).collect();
|
||
|
||
let table_videos = schema::table_name("videos");
|
||
let table_chunks = schema::table_name("chunk");
|
||
let total_chunks: i64 = sqlx::query_scalar(&format!("SELECT COUNT(*) FROM {}", table_chunks))
|
||
.fetch_one(state.db.pool())
|
||
.await
|
||
.unwrap_or(0);
|
||
let searchable_chunks: i64 = sqlx::query_scalar(&format!(
|
||
"SELECT COUNT(*) FROM {} WHERE vector_id IS NOT NULL",
|
||
table_chunks
|
||
))
|
||
.fetch_one(state.db.pool())
|
||
.await
|
||
.unwrap_or(0);
|
||
let pending_videos: i64 = sqlx::query_scalar(&format!(
|
||
"SELECT COUNT(*) FROM {} WHERE status = 'pending'",
|
||
table_videos
|
||
))
|
||
.fetch_one(state.db.pool())
|
||
.await
|
||
.unwrap_or(0);
|
||
|
||
Ok(Json(ScanFilesResponse {
|
||
files,
|
||
total: total_all,
|
||
filtered_total,
|
||
page,
|
||
page_size,
|
||
total_pages,
|
||
registered_count,
|
||
unregistered_count,
|
||
total_chunks,
|
||
searchable_chunks,
|
||
pending_videos,
|
||
}))
|
||
}
|
||
|
||
#[derive(Debug, Serialize)]
|
||
struct SftpgoStatusResponse {
|
||
username: String,
|
||
home_dir: String,
|
||
files_count: i64,
|
||
registered_videos: Vec<RegisteredVideo>,
|
||
last_login: Option<String>,
|
||
}
|
||
|
||
#[derive(Debug, Serialize)]
|
||
struct RegisteredVideo {
|
||
uuid: String,
|
||
file_name: String,
|
||
status: String,
|
||
}
|
||
|
||
async fn get_sftpgo_status(
|
||
State(state): State<AppState>,
|
||
) -> Result<Json<SftpgoStatusResponse>, StatusCode> {
|
||
let demo_dir =
|
||
std::env::var("MOMENTRY_SFTP_ROOT").unwrap_or_else(|_| "var/sftpgo/data/demo".to_string());
|
||
|
||
let files_count: i64 = std::fs::read_dir(&demo_dir)
|
||
.map(|entries| entries.count() as i64)
|
||
.unwrap_or(0);
|
||
|
||
let table_videos = schema::table_name("videos");
|
||
|
||
let registered_videos: Vec<(String, String, String)> = sqlx::query_as(&format!(
|
||
"SELECT file_uuid, file_name, status FROM {} WHERE file_path LIKE '%demo%' ORDER BY id",
|
||
table_videos
|
||
))
|
||
.fetch_all(state.db.pool())
|
||
.await
|
||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||
|
||
let registered_videos = registered_videos
|
||
.into_iter()
|
||
.map(|(uuid, file_name, status)| RegisteredVideo {
|
||
uuid,
|
||
file_name,
|
||
status,
|
||
})
|
||
.collect();
|
||
|
||
Ok(Json(SftpgoStatusResponse {
|
||
username: "demo".to_string(),
|
||
home_dir: demo_dir.to_string(),
|
||
files_count,
|
||
registered_videos,
|
||
last_login: None,
|
||
}))
|
||
}
|
||
|
||
#[derive(Debug, Serialize)]
|
||
struct IngestionStep {
|
||
name: String,
|
||
status: String,
|
||
detail: Option<String>,
|
||
}
|
||
|
||
#[derive(Debug, Serialize)]
|
||
struct IdentityRef {
|
||
uuid: String,
|
||
name: String,
|
||
}
|
||
|
||
#[derive(Debug, Serialize)]
|
||
struct IngestionStatusResponse {
|
||
file_uuid: String,
|
||
steps: Vec<IngestionStep>,
|
||
related_identities: Vec<IdentityRef>,
|
||
strangers: i64,
|
||
}
|
||
|
||
async fn get_ingestion_status(
|
||
State(state): State<AppState>,
|
||
Path(file_uuid): Path<String>,
|
||
) -> Result<Json<IngestionStatusResponse>, StatusCode> {
|
||
let pool = state.db.pool();
|
||
let chunk = schema::table_name("chunk");
|
||
let identities = schema::table_name("identities");
|
||
|
||
// Get face counts from Qdrant _faces
|
||
use crate::core::db::qdrant_db::QdrantDb;
|
||
use serde_json::json;
|
||
|
||
let qdrant = QdrantDb::new();
|
||
let face_filter = json!({
|
||
"must": [
|
||
{"key": "file_uuid", "match": {"value": file_uuid}}
|
||
]
|
||
});
|
||
let points = qdrant
|
||
.scroll_all_points("_faces", face_filter, 1000)
|
||
.await
|
||
.unwrap_or_default();
|
||
|
||
let face_total = points.len() as i64;
|
||
let mut trace_ids: std::collections::HashSet<i64> = std::collections::HashSet::new();
|
||
let mut identity_ids: std::collections::HashSet<i64> = std::collections::HashSet::new();
|
||
let mut stranger_traces: std::collections::HashSet<i64> = std::collections::HashSet::new();
|
||
|
||
for point in &points {
|
||
let payload = &point["payload"];
|
||
if let Some(tid) = payload["trace_id"].as_i64() {
|
||
if tid > 0 {
|
||
trace_ids.insert(tid);
|
||
if payload["identity_id"].is_null() {
|
||
stranger_traces.insert(tid);
|
||
}
|
||
}
|
||
}
|
||
if let Some(iid) = payload["identity_id"].as_i64() {
|
||
if iid > 0 {
|
||
identity_ids.insert(iid);
|
||
}
|
||
}
|
||
}
|
||
|
||
let trace_count = trace_ids.len() as i64;
|
||
let identity_count = identity_ids.len() as i64;
|
||
let strangers = stranger_traces.len() as i64;
|
||
|
||
let scene_meta_path = format!(
|
||
"{}/{}.scene_meta.json",
|
||
crate::core::config::OUTPUT_DIR.as_str(),
|
||
file_uuid
|
||
);
|
||
let scene_meta_ok = std::path::Path::new(&scene_meta_path).exists();
|
||
|
||
macro_rules! count_sql {
|
||
($sql:expr) => {
|
||
sqlx::query_scalar::<_, i64>($sql)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0)
|
||
};
|
||
}
|
||
|
||
let sentence_count = count_sql!(&format!(
|
||
"SELECT COUNT(*) FROM {chunk} WHERE file_uuid = '{file_uuid}' AND chunk_type = 'sentence'"
|
||
));
|
||
let sentence_embedded = count_sql!(&format!("SELECT COUNT(*) FROM {chunk} WHERE file_uuid = '{file_uuid}' AND chunk_type = 'sentence' AND embedding IS NOT NULL"));
|
||
|
||
// OCR statistics
|
||
let pre_chunks_table = schema::table_name("pre_chunks");
|
||
let ocr_pre_chunks: i64 = count_sql!(&format!(
|
||
"SELECT COUNT(*) FROM {pre_chunks_table} WHERE file_uuid = '{file_uuid}' AND processor_type = 'ocr'"
|
||
));
|
||
let ocr_only_chunks: i64 = count_sql!(&format!(
|
||
"SELECT COUNT(*) FROM {chunk} WHERE file_uuid = '{file_uuid}' AND chunk_type = 'sentence' \
|
||
AND (content->>'text' = '' OR content->>'text' IS NULL) \
|
||
AND content->>'ocr_text' IS NOT NULL AND content->>'ocr_text' != ''"
|
||
));
|
||
let scene_count = count_sql!(&format!(
|
||
"SELECT COUNT(*) FROM {chunk} WHERE file_uuid = '{file_uuid}' AND chunk_type = 'cut'"
|
||
));
|
||
let face_total = face_total;
|
||
let trace_count = trace_count;
|
||
let identity_count = identity_count;
|
||
let tkg_nodes = count_sql!(&format!(
|
||
"SELECT COUNT(*) FROM {} WHERE file_uuid = '{file_uuid}'",
|
||
schema::table_name("tkg_nodes")
|
||
));
|
||
let tkg_edges = count_sql!(&format!(
|
||
"SELECT COUNT(*) FROM {} WHERE file_uuid = '{file_uuid}'",
|
||
schema::table_name("tkg_edges")
|
||
));
|
||
|
||
// Get individual node counts by type
|
||
let tkg_nodes_table = schema::table_name("tkg_nodes");
|
||
let face_track_nodes: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_nodes_table} WHERE file_uuid = '{file_uuid}' AND node_type = 'face_track'"));
|
||
let gaze_track_nodes: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_nodes_table} WHERE file_uuid = '{file_uuid}' AND node_type = 'gaze_track'"));
|
||
let lip_track_nodes: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_nodes_table} WHERE file_uuid = '{file_uuid}' AND node_type = 'lip_track'"));
|
||
let text_region_nodes: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_nodes_table} WHERE file_uuid = '{file_uuid}' AND node_type = 'text_trace'"));
|
||
let appearance_nodes: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_nodes_table} WHERE file_uuid = '{file_uuid}' AND node_type = 'appearance_trace'"));
|
||
let accessory_nodes: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_nodes_table} WHERE file_uuid = '{file_uuid}' AND node_type = 'accessory'"));
|
||
let object_nodes: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_nodes_table} WHERE file_uuid = '{file_uuid}' AND node_type = 'object'"));
|
||
let hand_nodes: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_nodes_table} WHERE file_uuid = '{file_uuid}' AND node_type = 'hand'"));
|
||
let speaker_nodes: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_nodes_table} WHERE file_uuid = '{file_uuid}' AND node_type = 'speaker'"));
|
||
|
||
// Get individual edge counts by type
|
||
let tkg_edges_table = schema::table_name("tkg_edges");
|
||
let co_occurrence_edges: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_edges_table} WHERE file_uuid = '{file_uuid}' AND edge_type = 'CO_OCCURS_WITH'"));
|
||
let speaker_face_edges: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_edges_table} WHERE file_uuid = '{file_uuid}' AND edge_type = 'SPEAKS_AS'"));
|
||
let face_face_edges: i64 = count_sql!(&format!(
|
||
"SELECT COUNT(*) FROM {tkg_edges_table} e \
|
||
INNER JOIN {tkg_nodes_table} sn ON e.source_node_id = sn.id \
|
||
INNER JOIN {tkg_nodes_table} tn ON e.target_node_id = tn.id \
|
||
WHERE e.file_uuid = '{file_uuid}' \
|
||
AND e.edge_type = 'CO_OCCURS_WITH' \
|
||
AND sn.node_type = 'face_track' \
|
||
AND tn.node_type = 'face_track'"
|
||
));
|
||
let mutual_gaze_edges: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_edges_table} WHERE file_uuid = '{file_uuid}' AND edge_type = 'MUTUAL_GAZE'"));
|
||
let lip_sync_edges: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_edges_table} WHERE file_uuid = '{file_uuid}' AND edge_type = 'LIP_SYNC'"));
|
||
let has_appearance_edges: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_edges_table} WHERE file_uuid = '{file_uuid}' AND edge_type = 'HAS_APPEARANCE'"));
|
||
let wears_edges: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_edges_table} WHERE file_uuid = '{file_uuid}' AND edge_type = 'WEARS'"));
|
||
let hand_object_edges: i64 = count_sql!(&format!("SELECT COUNT(*) FROM {tkg_edges_table} WHERE file_uuid = '{file_uuid}' AND edge_type = 'HAND_OBJECT'"));
|
||
|
||
// Rule 2 relationship chunks
|
||
let rule2_chunks = count_sql!(&format!(
|
||
"SELECT COUNT(*) FROM {chunk} WHERE file_uuid = '{file_uuid}' AND chunk_type = 'relationship'"
|
||
));
|
||
// Get related identities from Qdrant _faces
|
||
let related_identity_ids: Vec<i64> = identity_ids.into_iter().collect();
|
||
let related_identities: Vec<IdentityRef> = if !related_identity_ids.is_empty() {
|
||
let id_list: String = related_identity_ids
|
||
.iter()
|
||
.map(|id| id.to_string())
|
||
.collect::<Vec<_>>()
|
||
.join(",");
|
||
match sqlx::query_as::<_, (String, String)>(&format!(
|
||
"SELECT DISTINCT uuid::text, name FROM {identities} \
|
||
WHERE id IN ({id_list}) ORDER BY name"
|
||
))
|
||
.fetch_all(pool)
|
||
.await
|
||
{
|
||
Ok(rows) => rows
|
||
.into_iter()
|
||
.map(|(uuid, name)| IdentityRef {
|
||
uuid: uuid.replace('-', ""),
|
||
name,
|
||
})
|
||
.collect(),
|
||
Err(e) => {
|
||
tracing::error!("related_identities query failed: {}", e);
|
||
vec![]
|
||
}
|
||
}
|
||
} else {
|
||
vec![]
|
||
};
|
||
|
||
let strangers = strangers;
|
||
|
||
// Check if job is completed - if so, all ingestion steps are considered done
|
||
let mj_table = schema::table_name("monitor_jobs");
|
||
let job_completed: bool =
|
||
sqlx::query_scalar::<_, String>(&format!("SELECT status FROM {mj_table} WHERE uuid = $1"))
|
||
.bind(&file_uuid)
|
||
.fetch_optional(pool)
|
||
.await
|
||
.unwrap_or(None)
|
||
.map(|s| s == "completed")
|
||
.unwrap_or(false);
|
||
|
||
macro_rules! step {
|
||
($name:expr, $done:expr, $detail:expr) => {
|
||
IngestionStep {
|
||
name: $name.into(),
|
||
status: if $done || job_completed {
|
||
"done"
|
||
} else {
|
||
"pending"
|
||
}
|
||
.into(),
|
||
detail: $detail,
|
||
}
|
||
};
|
||
}
|
||
|
||
let steps = vec![
|
||
step!(
|
||
"rule1_sentence",
|
||
sentence_count > 0,
|
||
Some(format!("{sentence_count} sentence chunks"))
|
||
),
|
||
step!(
|
||
"rule1_ocr",
|
||
ocr_pre_chunks > 0,
|
||
Some(format!("{ocr_pre_chunks} OCR frames"))
|
||
),
|
||
step!(
|
||
"rule1_ocr_chunks",
|
||
ocr_only_chunks > 0,
|
||
Some(format!("{ocr_only_chunks} OCR-only chunks"))
|
||
),
|
||
step!(
|
||
"auto_vectorize",
|
||
sentence_embedded > 0,
|
||
Some(format!("{sentence_embedded} embedded"))
|
||
),
|
||
step!(
|
||
"face_track",
|
||
trace_count > 0,
|
||
Some(format!("{trace_count} traces / {face_total} detections"))
|
||
),
|
||
// TKG Nodes
|
||
step!(
|
||
"tkg_face_track",
|
||
face_track_nodes > 0,
|
||
Some(format!("{face_track_nodes} nodes"))
|
||
),
|
||
step!(
|
||
"tkg_gaze_track",
|
||
gaze_track_nodes > 0,
|
||
Some(format!("{gaze_track_nodes} nodes"))
|
||
),
|
||
step!(
|
||
"tkg_lip_track",
|
||
lip_track_nodes > 0,
|
||
Some(format!("{lip_track_nodes} nodes"))
|
||
),
|
||
step!(
|
||
"tkg_text_region",
|
||
text_region_nodes > 0,
|
||
Some(format!("{text_region_nodes} nodes"))
|
||
),
|
||
step!(
|
||
"tkg_appearance",
|
||
appearance_nodes > 0,
|
||
Some(format!("{appearance_nodes} nodes"))
|
||
),
|
||
step!(
|
||
"tkg_accessory",
|
||
accessory_nodes > 0,
|
||
Some(format!("{accessory_nodes} nodes"))
|
||
),
|
||
step!(
|
||
"tkg_object",
|
||
object_nodes > 0,
|
||
Some(format!("{object_nodes} nodes"))
|
||
),
|
||
step!(
|
||
"tkg_hand",
|
||
hand_nodes > 0,
|
||
Some(format!("{hand_nodes} nodes"))
|
||
),
|
||
step!(
|
||
"tkg_speaker",
|
||
speaker_nodes > 0,
|
||
Some(format!("{speaker_nodes} nodes"))
|
||
),
|
||
// TKG Edges
|
||
step!(
|
||
"tkg_co_occurrence",
|
||
co_occurrence_edges > 0,
|
||
Some(format!("{co_occurrence_edges} edges"))
|
||
),
|
||
step!(
|
||
"tkg_speaker_face",
|
||
speaker_face_edges > 0,
|
||
Some(format!("{speaker_face_edges} edges"))
|
||
),
|
||
step!(
|
||
"tkg_face_face",
|
||
face_face_edges > 0,
|
||
Some(format!("{face_face_edges} edges"))
|
||
),
|
||
step!(
|
||
"tkg_mutual_gaze",
|
||
mutual_gaze_edges > 0,
|
||
Some(format!("{mutual_gaze_edges} edges"))
|
||
),
|
||
step!(
|
||
"tkg_lip_sync",
|
||
lip_sync_edges > 0,
|
||
Some(format!("{lip_sync_edges} edges"))
|
||
),
|
||
step!(
|
||
"tkg_has_appearance",
|
||
has_appearance_edges > 0,
|
||
Some(format!("{has_appearance_edges} edges"))
|
||
),
|
||
step!(
|
||
"tkg_wears",
|
||
wears_edges > 0,
|
||
Some(format!("{wears_edges} edges"))
|
||
),
|
||
step!(
|
||
"tkg_hand_object",
|
||
hand_object_edges > 0,
|
||
Some(format!("{hand_object_edges} edges"))
|
||
),
|
||
// Rule 2
|
||
step!(
|
||
"rule2_relationship",
|
||
rule2_chunks > 0,
|
||
Some(format!("{rule2_chunks} relationship chunks"))
|
||
),
|
||
// Identity & Scene
|
||
step!(
|
||
"identity_match",
|
||
identity_count > 0,
|
||
Some(format!("{identity_count} identities matched"))
|
||
),
|
||
step!("scene_metadata", scene_meta_ok, None),
|
||
];
|
||
|
||
Ok(Json(IngestionStatusResponse {
|
||
file_uuid,
|
||
steps,
|
||
related_identities,
|
||
strangers,
|
||
}))
|
||
}
|
||
|
||
/// Comprehensive file stats endpoint — combines all data sources for frontend transparency
|
||
async fn get_file_stats(
|
||
State(state): State<AppState>,
|
||
Path(file_uuid): Path<String>,
|
||
) -> Result<Json<FileStatsResponse>, StatusCode> {
|
||
// Wrap entire handler in a 60-second timeout to prevent indefinite
|
||
// hangs from multiple scroll_all_points calls or slow DB queries.
|
||
// This is the last line of defense: each individual HTTP call has a
|
||
// 30s timeout (via new_http_client), but multiple calls + DB queries
|
||
// could still exceed reasonable response time.
|
||
match tokio::time::timeout(
|
||
std::time::Duration::from_secs(60),
|
||
get_file_stats_inner(state, file_uuid),
|
||
)
|
||
.await
|
||
{
|
||
Ok(result) => result,
|
||
Err(_) => {
|
||
tracing::error!("get_file_stats timed out after 60s");
|
||
Err(StatusCode::REQUEST_TIMEOUT)
|
||
}
|
||
}
|
||
}
|
||
|
||
async fn get_file_stats_inner(
|
||
state: AppState,
|
||
file_uuid: String,
|
||
) -> Result<Json<FileStatsResponse>, StatusCode> {
|
||
let pool = state.db.pool();
|
||
|
||
// 1. Get file info from PostgreSQL
|
||
let videos_table = schema::table_name("videos");
|
||
let file_info: Option<(String, String, String, Option<String>, Option<String>)> = sqlx::query_as(&format!(
|
||
"SELECT file_uuid, file_name, status, created_at::text, updated_at::text FROM {} WHERE file_uuid = $1",
|
||
videos_table
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_optional(pool)
|
||
.await
|
||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||
|
||
let (file_uuid_str, file_name, status, created_at, updated_at) =
|
||
file_info.unwrap_or_else(|| (file_uuid.clone(), String::new(), String::new(), None, None));
|
||
|
||
// Determine processing_completed_at based on status
|
||
let processing_completed_at = if status == "completed" {
|
||
updated_at.clone()
|
||
} else {
|
||
None
|
||
};
|
||
|
||
// 2. Get processor status from processing_status JSONB
|
||
let processing_status: serde_json::Value = sqlx::query_scalar(&format!(
|
||
"SELECT processing_status FROM {} WHERE file_uuid = $1",
|
||
videos_table
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_optional(pool)
|
||
.await
|
||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||
.unwrap_or(serde_json::json!({}));
|
||
|
||
let progress_map = processing_status
|
||
.get("progress")
|
||
.and_then(|p| p.as_object())
|
||
.cloned()
|
||
.unwrap_or_default();
|
||
|
||
let active_order: Vec<String> = processing_status
|
||
.get("active_processors")
|
||
.and_then(|a| a.as_array())
|
||
.map(|arr| {
|
||
arr.iter()
|
||
.filter_map(|v| v.as_str().map(|s| s.to_uppercase()))
|
||
.collect()
|
||
})
|
||
.unwrap_or_default();
|
||
|
||
let processors: Vec<ProcessorStatus> = if !active_order.is_empty() {
|
||
active_order
|
||
.iter()
|
||
.filter_map(|name| {
|
||
progress_map.get(name).and_then(|info| {
|
||
info.as_object().map(|obj| {
|
||
let status = obj
|
||
.get("status")
|
||
.and_then(|s| s.as_str())
|
||
.unwrap_or("pending")
|
||
.to_string();
|
||
let progress_val =
|
||
obj.get("percentage").and_then(|p| p.as_u64()).unwrap_or(0) as u32;
|
||
let message = obj
|
||
.get("message")
|
||
.and_then(|m| m.as_str())
|
||
.map(|s| s.to_string());
|
||
ProcessorStatus {
|
||
name: name.clone(),
|
||
status,
|
||
progress: progress_val,
|
||
message,
|
||
}
|
||
})
|
||
})
|
||
})
|
||
.collect()
|
||
} else {
|
||
progress_map
|
||
.iter()
|
||
.filter_map(|(name, info)| {
|
||
info.as_object().map(|obj| {
|
||
let status = obj
|
||
.get("status")
|
||
.and_then(|s| s.as_str())
|
||
.unwrap_or("pending")
|
||
.to_string();
|
||
let progress_val =
|
||
obj.get("percentage").and_then(|p| p.as_u64()).unwrap_or(0) as u32;
|
||
let message = obj
|
||
.get("message")
|
||
.and_then(|m| m.as_str())
|
||
.map(|s| s.to_string());
|
||
ProcessorStatus {
|
||
name: name.clone(),
|
||
status,
|
||
progress: progress_val,
|
||
message,
|
||
}
|
||
})
|
||
})
|
||
.collect()
|
||
};
|
||
|
||
// 3. Get PostgreSQL counts
|
||
let chunk_table = schema::table_name("chunk");
|
||
let identities_table = schema::table_name("identities");
|
||
let file_identities_table = schema::table_name("file_identities");
|
||
|
||
let postgres = PostgresStats {
|
||
sentence_chunks: sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(*) FROM {chunk_table} WHERE file_uuid = $1 AND chunk_type = 'sentence'"
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0),
|
||
relationship_chunks: sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(*) FROM {chunk_table} WHERE file_uuid = $1 AND chunk_type = 'relationship'"
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0),
|
||
identities: sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(DISTINCT i.id) FROM {identities_table} i \
|
||
JOIN {file_identities_table} fi ON fi.identity_id = i.id \
|
||
WHERE fi.file_uuid = $1"
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0),
|
||
file_identities: sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(*) FROM {file_identities_table} WHERE file_uuid = $1"
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0),
|
||
};
|
||
|
||
// 4. Get ASRX stats from processor_results
|
||
let pr_table = schema::table_name("processor_results");
|
||
let mj_table = schema::table_name("monitor_jobs");
|
||
|
||
#[derive(sqlx::FromRow)]
|
||
struct AsrxRow {
|
||
status: Option<String>,
|
||
segment_count: i32,
|
||
language: Option<String>,
|
||
}
|
||
|
||
let asrx_data_result = sqlx::query_as::<_, AsrxRow>(&format!(
|
||
"SELECT pr.asr_status AS status, COALESCE(pr.segment_count, 0) AS segment_count, pr.output_data->>'language' AS language \
|
||
FROM {pr_table} pr \
|
||
JOIN {mj_table} mj ON pr.job_id = mj.id \
|
||
WHERE mj.uuid = $1 AND pr.processor = 'asrx' \
|
||
LIMIT 1"
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_optional(pool)
|
||
.await;
|
||
|
||
let asrx = match asrx_data_result {
|
||
Ok(Some(row)) => {
|
||
eprintln!("[ASRX-DEBUG] Found data: status={:?}, segment_count={}, language={:?}", row.status, row.segment_count, row.language);
|
||
AsrxStats {
|
||
status: row.status,
|
||
segment_count: row.segment_count,
|
||
language: row.language,
|
||
}
|
||
}
|
||
Ok(None) => {
|
||
eprintln!("[ASRX-DEBUG] No ASRX data found for uuid={}", file_uuid);
|
||
AsrxStats::default()
|
||
}
|
||
Err(e) => {
|
||
eprintln!("[ASRX-DEBUG] Query failed for uuid={}: {}", file_uuid, e);
|
||
AsrxStats::default()
|
||
}
|
||
};
|
||
|
||
// 5. Get Qdrant stats
|
||
use crate::core::db::qdrant_db::QdrantDb;
|
||
use serde_json::json;
|
||
|
||
let qdrant_db = QdrantDb::new();
|
||
|
||
// Face stats
|
||
let face_filter = json!({
|
||
"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]
|
||
});
|
||
let face_points = qdrant_db
|
||
.scroll_all_points("_faces", face_filter.clone(), 500)
|
||
.await
|
||
.unwrap_or_default();
|
||
|
||
let mut face_traces = std::collections::HashSet::new();
|
||
let mut face_identities = std::collections::HashSet::new();
|
||
for point in &face_points {
|
||
let payload = &point["payload"];
|
||
if let Some(tid) = payload["trace_id"].as_i64() {
|
||
if tid > 0 {
|
||
face_traces.insert(tid);
|
||
}
|
||
}
|
||
if let Some(iid) = payload["identity_id"].as_i64() {
|
||
if iid > 0 {
|
||
face_identities.insert(iid);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Text chunk stats (rule1 collection)
|
||
let schema = std::env::var("DATABASE_SCHEMA").unwrap_or_else(|_| "public".to_string());
|
||
let rule1_collection = if schema == "public" {
|
||
"momentry_rule1".to_string()
|
||
} else {
|
||
format!("momentry_{}_rule1_v2", schema)
|
||
};
|
||
let text_filter = json!({
|
||
"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]
|
||
});
|
||
let text_points = qdrant_db
|
||
.scroll_all_points(&rule1_collection, text_filter, 500)
|
||
.await
|
||
.unwrap_or_default();
|
||
|
||
// Speaker stats
|
||
let speaker_collection = format!("momentry_{}_speaker", schema);
|
||
let speaker_filter = json!({
|
||
"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]
|
||
});
|
||
let speaker_points = qdrant_db
|
||
.scroll_all_points(&speaker_collection, speaker_filter, 500)
|
||
.await
|
||
.unwrap_or_default();
|
||
|
||
let qdrant_stats = QdrantStats {
|
||
faces: face_points.len() as i64,
|
||
face_traces: face_traces.len() as i64,
|
||
face_identities: face_identities.len() as i64,
|
||
text_chunks: text_points.len() as i64,
|
||
speakers: speaker_points.len() as i64,
|
||
};
|
||
|
||
// 5. Get TKG stats from PostgreSQL
|
||
let tkg_nodes_table = schema::table_name("tkg_nodes");
|
||
let tkg_edges_table = schema::table_name("tkg_edges");
|
||
|
||
let tkg_nodes_total: i64 = sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1",
|
||
tkg_nodes_table
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0);
|
||
let tkg_edges_total: i64 = sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1",
|
||
tkg_edges_table
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0);
|
||
|
||
let tkg = TkgFileStats {
|
||
total_nodes: tkg_nodes_total,
|
||
total_edges: tkg_edges_total,
|
||
face_track_nodes: count_nodes(pool, &tkg_nodes_table, &file_uuid, "face_track").await,
|
||
gaze_track_nodes: count_nodes(pool, &tkg_nodes_table, &file_uuid, "gaze_track").await,
|
||
lip_track_nodes: count_nodes(pool, &tkg_nodes_table, &file_uuid, "lip_track").await,
|
||
text_region_nodes: count_nodes(pool, &tkg_nodes_table, &file_uuid, "text_trace").await,
|
||
appearance_nodes: count_nodes(pool, &tkg_nodes_table, &file_uuid, "appearance_trace").await,
|
||
accessory_nodes: count_nodes(pool, &tkg_nodes_table, &file_uuid, "accessory").await,
|
||
object_nodes: count_nodes(pool, &tkg_nodes_table, &file_uuid, "object").await,
|
||
hand_nodes: count_nodes(pool, &tkg_nodes_table, &file_uuid, "hand").await,
|
||
speaker_nodes: count_nodes(pool, &tkg_nodes_table, &file_uuid, "speaker").await,
|
||
co_occurrence_edges: count_edges(pool, &tkg_edges_table, &file_uuid, "CO_OCCURS_WITH")
|
||
.await,
|
||
speaker_face_edges: count_edges(pool, &tkg_edges_table, &file_uuid, "SPEAKS_AS").await,
|
||
face_face_edges: sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(*) FROM {tkg_edges_table} e \
|
||
INNER JOIN {tkg_nodes_table} sn ON e.source_node_id = sn.id \
|
||
INNER JOIN {tkg_nodes_table} tn ON e.target_node_id = tn.id \
|
||
WHERE e.file_uuid = $1 \
|
||
AND e.edge_type = 'CO_OCCURS_WITH' \
|
||
AND sn.node_type = 'face_track' \
|
||
AND tn.node_type = 'face_track'"
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0),
|
||
mutual_gaze_edges: count_edges(pool, &tkg_edges_table, &file_uuid, "MUTUAL_GAZE").await,
|
||
lip_sync_edges: count_edges(pool, &tkg_edges_table, &file_uuid, "LIP_SYNC").await,
|
||
has_appearance_edges: count_edges(pool, &tkg_edges_table, &file_uuid, "HAS_APPEARANCE")
|
||
.await,
|
||
wears_edges: count_edges(pool, &tkg_edges_table, &file_uuid, "WEARS").await,
|
||
hand_object_edges: count_edges(pool, &tkg_edges_table, &file_uuid, "HAND_OBJECT").await,
|
||
..Default::default()
|
||
};
|
||
|
||
// 6. Get Face Dedup stats
|
||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||
let face_cluster_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
|
||
let face_clusters = if std::path::Path::new(&face_cluster_path).exists() {
|
||
if let Ok(content) = std::fs::read_to_string(&face_cluster_path) {
|
||
if let Ok(cluster_data) = serde_json::from_str::<serde_json::Value>(&content) {
|
||
cluster_data
|
||
.get("clusters")
|
||
.and_then(|c| c.as_array())
|
||
.map(|a| a.len())
|
||
.unwrap_or(0)
|
||
} else {
|
||
0
|
||
}
|
||
} else {
|
||
0
|
||
}
|
||
} else {
|
||
0
|
||
};
|
||
let face_track_count = tkg.face_track_nodes;
|
||
|
||
let face_dedup = FaceDedupStats {
|
||
clusters: face_clusters as i64,
|
||
face_tracks: face_track_count,
|
||
consistent: (face_clusters as i64) == face_track_count,
|
||
};
|
||
|
||
// 7. On-disk face artifact counts (trace dirs + key_frame/key_face/profile)
|
||
let trace_profiles_table = schema::table_name("trace_profiles");
|
||
let expected_traces: i64 = sqlx::query_scalar(&format!(
|
||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1",
|
||
trace_profiles_table
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0);
|
||
let mut face_artifacts = count_face_artifacts(output_dir, &file_uuid);
|
||
face_artifacts.expected_traces = expected_traces;
|
||
|
||
// 8. VLM Summary progress
|
||
let vlm_total: i64 = sqlx::query_scalar(&format!(
|
||
"SELECT COUNT(*) FROM {trace_profiles_table} WHERE file_uuid = $1"
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0);
|
||
let vlm_done: i64 = sqlx::query_scalar(&format!(
|
||
"SELECT COUNT(*) FROM {trace_profiles_table} \
|
||
WHERE file_uuid = $1 AND vlm_description IS NOT NULL"
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0);
|
||
let vlm_summary = VlmSummaryStats {
|
||
total: vlm_total,
|
||
done: vlm_done,
|
||
};
|
||
|
||
// 9. Scene VLM stats
|
||
let scenes_path = format!("{}/{}.scenes.json", output_dir, file_uuid);
|
||
let scene_vlm = if std::path::Path::new(&scenes_path).exists() {
|
||
if let Ok(scenes_json) = std::fs::read_to_string(&scenes_path) {
|
||
if let Ok(scenes_data) = serde_json::from_str::<serde_json::Value>(&scenes_json) {
|
||
let total_scenes = scenes_data
|
||
.get("total_scenes")
|
||
.and_then(|v| v.as_i64())
|
||
.unwrap_or(0);
|
||
let status = scenes_data
|
||
.get("status")
|
||
.and_then(|v| v.as_str())
|
||
.unwrap_or("pending")
|
||
.to_string();
|
||
|
||
let scenes_array = scenes_data
|
||
.get("scenes")
|
||
.and_then(|v| v.as_array())
|
||
.map(|arr| arr.len() as i64)
|
||
.unwrap_or(0);
|
||
|
||
let vlm_done = scenes_data
|
||
.get("scenes")
|
||
.and_then(|v| v.as_array())
|
||
.map(|arr| {
|
||
arr.iter()
|
||
.filter(|s| {
|
||
let status = s.get("vlm_status").and_then(|v| v.as_str());
|
||
status == Some("completed") || status == Some("done")
|
||
})
|
||
.count() as i64
|
||
})
|
||
.unwrap_or(0);
|
||
|
||
SceneVlmStats {
|
||
total_scenes: total_scenes.max(scenes_array),
|
||
status,
|
||
vlm_done,
|
||
vlm_total: total_scenes.max(scenes_array),
|
||
}
|
||
} else {
|
||
SceneVlmStats::default()
|
||
}
|
||
} else {
|
||
SceneVlmStats::default()
|
||
}
|
||
} else {
|
||
SceneVlmStats::default()
|
||
};
|
||
|
||
Ok(Json(FileStatsResponse {
|
||
file_uuid: file_uuid_str,
|
||
file_name: Some(file_name).filter(|s| !s.is_empty()),
|
||
status: Some(status).filter(|s| !s.is_empty()),
|
||
created_at,
|
||
updated_at,
|
||
processing_completed_at,
|
||
processors,
|
||
postgres,
|
||
asrx,
|
||
qdrant: qdrant_stats,
|
||
tkg,
|
||
face_dedup,
|
||
vlm_summary,
|
||
scene_vlm,
|
||
face_artifacts,
|
||
}))
|
||
}
|
||
|
||
async fn count_nodes(pool: &sqlx::PgPool, table: &str, file_uuid: &str, node_type: &str) -> i64 {
|
||
sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND node_type = $2",
|
||
table
|
||
))
|
||
.bind(file_uuid)
|
||
.bind(node_type)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0)
|
||
}
|
||
|
||
async fn count_edges(pool: &sqlx::PgPool, table: &str, file_uuid: &str, edge_type: &str) -> i64 {
|
||
sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND edge_type = $2",
|
||
table
|
||
))
|
||
.bind(file_uuid)
|
||
.bind(edge_type)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0)
|
||
}
|
||
|
||
pub fn scan_routes() -> Router<AppState> {
|
||
Router::new()
|
||
.route("/api/v1/files/scan", get(scan_files))
|
||
.route("/api/v1/files/scan-path", get(scan_specific_path))
|
||
.route("/api/v1/stats/sftpgo", get(get_sftpgo_status))
|
||
.route(
|
||
"/api/v1/stats/ingestion-status/:file_uuid",
|
||
get(get_ingestion_status),
|
||
)
|
||
.route("/api/v1/stats/file/:file_uuid", get(get_file_stats))
|
||
.route("/api/v1/file/:file_uuid/scene-vlm-stats", get(get_scene_vlm_stats))
|
||
.route(
|
||
"/api/v1/stats/pipeline/:file_uuid",
|
||
get(get_pipeline_progress_handler),
|
||
)
|
||
}
|
||
|
||
/// Get segmented pipeline progress with weighted stages
|
||
async fn get_pipeline_progress_handler(
|
||
State(state): State<AppState>,
|
||
Path(file_uuid): Path<String>,
|
||
) -> Result<Json<crate::core::progress::PipelineProgress>, StatusCode> {
|
||
// 1. Try to read existing progress from Redis first
|
||
let redis_progress: Option<crate::core::progress::PipelineProgress> = {
|
||
use crate::core::db::RedisClient;
|
||
if let Ok(redis) = RedisClient::new() {
|
||
if let Ok(mut conn) = redis.get_conn().await {
|
||
let key = format!(
|
||
"{}progress:{}:pipeline",
|
||
crate::core::config::REDIS_KEY_PREFIX.as_str(),
|
||
file_uuid
|
||
);
|
||
redis::cmd("GET")
|
||
.arg(&key)
|
||
.query_async(&mut conn)
|
||
.await
|
||
.ok()
|
||
.and_then(|s: String| serde_json::from_str(&s).ok())
|
||
} else {
|
||
None
|
||
}
|
||
} else {
|
||
None
|
||
}
|
||
};
|
||
|
||
// 2. If Redis has complete progress (100%), return it directly
|
||
if let Some(ref rp) = redis_progress {
|
||
if rp.overall_progress >= 1.0 {
|
||
return Ok(Json(rp.clone()));
|
||
}
|
||
}
|
||
|
||
// 3. Otherwise, compute actual progress from DB state
|
||
let pool = state.db.pool();
|
||
let chunk_table = schema::table_name("chunk");
|
||
let tkg_nodes_table = schema::table_name("tkg_nodes");
|
||
let tkg_edges_table = schema::table_name("tkg_edges");
|
||
let pr_table = schema::table_name("processor_results");
|
||
let mj_table = schema::table_name("monitor_jobs");
|
||
|
||
// Compute actual progress from DB state
|
||
let sentence_count: i64 = sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(*) FROM {chunk_table} WHERE file_uuid = $1 AND chunk_type = 'sentence'"
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0);
|
||
|
||
let sentence_embedded: i64 = sqlx::query_scalar::<_, i64>(
|
||
&format!("SELECT COUNT(*) FROM {chunk_table} WHERE file_uuid = $1 AND chunk_type = 'sentence' AND embedding IS NOT NULL")
|
||
).bind(&file_uuid).fetch_one(pool).await.unwrap_or(0);
|
||
|
||
let face_traced: i64 = sqlx::query_scalar::<_, i64>(
|
||
&format!("SELECT COUNT(*) FROM {pr_table} pr JOIN {mj_table} mj ON pr.job_id = mj.id WHERE mj.uuid = $1 AND pr.processor = 'face' AND pr.status = 'completed'")
|
||
).bind(&file_uuid).fetch_one(pool).await.unwrap_or(0);
|
||
|
||
let tkg_node_count: i64 = sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(*) FROM {tkg_nodes_table} WHERE file_uuid = $1"
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0);
|
||
|
||
let tkg_edge_count: i64 = sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(*) FROM {tkg_edges_table} WHERE file_uuid = $1"
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0);
|
||
|
||
let relationship_count: i64 = sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(*) FROM {chunk_table} WHERE file_uuid = $1 AND chunk_type = 'relationship'"
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0);
|
||
|
||
let asrx_completed: i64 = sqlx::query_scalar::<_, i64>(
|
||
&format!("SELECT COUNT(*) FROM {pr_table} pr JOIN {mj_table} mj ON pr.job_id = mj.id WHERE mj.uuid = $1 AND pr.processor = 'asrx' AND pr.status = 'completed'")
|
||
).bind(&file_uuid).fetch_one(pool).await.unwrap_or(0);
|
||
|
||
// Determine processor completion
|
||
let processors_done = asrx_completed > 0;
|
||
|
||
let mut pp = crate::core::progress::PipelineProgress::new(&file_uuid);
|
||
|
||
if processors_done {
|
||
pp.update_stage("processors", 1.0, "completed", None);
|
||
}
|
||
if sentence_count > 0 {
|
||
let detail = if sentence_embedded > 0 {
|
||
Some(format!(
|
||
"{} chunks, {} embedded",
|
||
sentence_count, sentence_embedded
|
||
))
|
||
} else {
|
||
Some(format!("{} chunks", sentence_count))
|
||
};
|
||
pp.update_stage("rule1_ingestion", 1.0, "completed", detail);
|
||
}
|
||
if face_traced > 0 {
|
||
pp.update_stage("face_tracing", 1.0, "completed", None);
|
||
}
|
||
// Update TKG stages - mark completed even if 0 results (A-10 fix)
|
||
// This ensures overall_progress can reach 1.0 for files with no faces/relationships
|
||
pp.update_stage(
|
||
"tkg_nodes",
|
||
1.0,
|
||
"completed",
|
||
Some(format!("{} nodes", tkg_node_count)),
|
||
);
|
||
pp.update_stage(
|
||
"tkg_edges",
|
||
1.0,
|
||
"completed",
|
||
Some(format!("{} edges", tkg_edge_count)),
|
||
);
|
||
pp.update_stage(
|
||
"rule2_ingestion",
|
||
1.0,
|
||
"completed",
|
||
Some(format!("{} chunks", relationship_count)),
|
||
);
|
||
|
||
// Handle files with processors done but no TKG data
|
||
// Mark face_dedup as completed with appropriate reason (A-10 fix)
|
||
if processors_done {
|
||
if tkg_node_count == 0 {
|
||
// No faces detected or no embeddings generated
|
||
pp.update_stage("face_dedup", 1.0, "completed", Some("no faces".to_string()));
|
||
} else if tkg_edge_count == 0 {
|
||
// Faces detected but no relationships
|
||
pp.update_stage(
|
||
"face_dedup",
|
||
1.0,
|
||
"completed",
|
||
Some("no relationships".to_string()),
|
||
);
|
||
}
|
||
}
|
||
|
||
// Check VLM summary progress from trace_profiles
|
||
let tp_table = schema::table_name("trace_profiles");
|
||
let vlm_total: i64 = sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1"
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0);
|
||
let vlm_done: i64 = sqlx::query_scalar::<_, i64>(&format!(
|
||
"SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1 AND vlm_description IS NOT NULL AND vlm_description != ''"
|
||
))
|
||
.bind(&file_uuid)
|
||
.fetch_one(pool)
|
||
.await
|
||
.unwrap_or(0);
|
||
|
||
// Update VLM summary stage - mark completed even if 0 results (A-10 fix)
|
||
let vlm_status = if vlm_total == 0 {
|
||
"completed"
|
||
} else if vlm_done == vlm_total {
|
||
"completed"
|
||
} else {
|
||
"running"
|
||
};
|
||
|
||
let vlm_progress = if vlm_total == 0 {
|
||
1.0 // Completed with 0 results
|
||
} else if vlm_done > 0 {
|
||
vlm_done as f64 / vlm_total as f64
|
||
} else {
|
||
0.0
|
||
};
|
||
|
||
pp.update_stage(
|
||
"vlm_summary",
|
||
vlm_progress,
|
||
vlm_status,
|
||
if vlm_total == 0 {
|
||
Some("no traces".to_string())
|
||
} else {
|
||
Some(format!("{}/{}", vlm_done, vlm_total))
|
||
},
|
||
);
|
||
|
||
|
||
// Check scene_vlm progress from scenes.json
|
||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||
let scenes_path = format!("{}/{}.scenes.json", output_dir, file_uuid);
|
||
if std::path::Path::new(&scenes_path).exists() {
|
||
if let Ok(scenes_json) = std::fs::read_to_string(&scenes_path) {
|
||
if let Ok(scenes_data) = serde_json::from_str::<serde_json::Value>(&scenes_json) {
|
||
let total_scenes = scenes_data
|
||
.get("total_scenes")
|
||
.and_then(|v| v.as_i64())
|
||
.unwrap_or(0) as i64;
|
||
|
||
let vlm_done = scenes_data
|
||
.get("scenes")
|
||
.and_then(|v| v.as_array())
|
||
.map(|arr| {
|
||
arr.iter()
|
||
.filter(|s| {
|
||
let status = s.get("vlm_status").and_then(|v| v.as_str());
|
||
status == Some("completed") || status == Some("done")
|
||
})
|
||
.count() as i64
|
||
})
|
||
.unwrap_or(0);
|
||
|
||
let scene_vlm_status = if total_scenes == 0 {
|
||
"completed"
|
||
} else if vlm_done == total_scenes {
|
||
"completed"
|
||
} else if vlm_done > 0 {
|
||
"running"
|
||
} else {
|
||
"pending"
|
||
};
|
||
|
||
let scene_vlm_progress = if total_scenes == 0 {
|
||
1.0
|
||
} else if vlm_done > 0 {
|
||
vlm_done as f64 / total_scenes as f64
|
||
} else {
|
||
0.0
|
||
};
|
||
|
||
pp.update_stage(
|
||
"scene_vlm",
|
||
scene_vlm_progress,
|
||
scene_vlm_status,
|
||
if total_scenes == 0 {
|
||
Some("no scenes".to_string())
|
||
} else {
|
||
Some(format!("{}/{}", vlm_done, total_scenes))
|
||
},
|
||
);
|
||
}
|
||
}
|
||
}
|
||
// Check face dedup from actual face_cluster.json content
|
||
// Always check if processors_done, regardless of tkg_node_count (A-10 fix)
|
||
if processors_done {
|
||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||
let face_cluster_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
|
||
if std::path::Path::new(&face_cluster_path).exists() {
|
||
if let Ok(content) = std::fs::read_to_string(&face_cluster_path) {
|
||
if let Ok(cluster_data) = serde_json::from_str::<serde_json::Value>(&content) {
|
||
let status = cluster_data
|
||
.get("status")
|
||
.and_then(|s| s.as_str())
|
||
.unwrap_or("");
|
||
let cluster_count = cluster_data
|
||
.get("clusters")
|
||
.and_then(|c| c.as_array())
|
||
.map(|a| a.len())
|
||
.unwrap_or(0);
|
||
|
||
match status {
|
||
"has_faces" if cluster_count > 0 => {
|
||
pp.update_stage(
|
||
"face_dedup",
|
||
1.0,
|
||
"completed",
|
||
Some(format!("{} persons", cluster_count)),
|
||
);
|
||
}
|
||
"no_faces" | "no_face_json" | "no_embeddings" => {
|
||
// Clustering ran but found nothing — mark as completed with reason
|
||
pp.update_stage(
|
||
"face_dedup",
|
||
1.0,
|
||
"completed",
|
||
Some(format!("ran ({})", status)),
|
||
);
|
||
}
|
||
_ => {
|
||
// File exists but status unclear — still mark as completed
|
||
// (the clustering process has finished)
|
||
pp.update_stage(
|
||
"face_dedup",
|
||
1.0,
|
||
"completed",
|
||
Some(format!("{} clusters", cluster_count)),
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 4. Merge with Redis progress: Redis-completed stages override DB state
|
||
if let Some(ref rp) = redis_progress {
|
||
for redis_stage in &rp.stages {
|
||
if redis_stage.status == "completed" {
|
||
pp.update_stage(
|
||
&redis_stage.name,
|
||
redis_stage.progress,
|
||
&redis_stage.status,
|
||
redis_stage.detail.clone(),
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
Ok(Json(pp))
|
||
}
|
||
|
||
/// Quick scene VLM stats endpoint (fast, no Qdrant queries)
|
||
pub async fn get_scene_vlm_stats(
|
||
State(state): State<AppState>,
|
||
Path(file_uuid): Path<String>,
|
||
) -> Result<Json<SceneVlmStats>, StatusCode> {
|
||
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
|
||
let scenes_path = format!("{}/{}.scenes.json", output_dir, file_uuid);
|
||
|
||
if !std::path::Path::new(&scenes_path).exists() {
|
||
return Ok(Json(SceneVlmStats::default()));
|
||
}
|
||
|
||
let scenes_json = std::fs::read_to_string(&scenes_path)
|
||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||
|
||
let scenes_data: serde_json::Value = serde_json::from_str(&scenes_json)
|
||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||
|
||
let total_scenes = scenes_data
|
||
.get("total_scenes")
|
||
.and_then(|v| v.as_i64())
|
||
.unwrap_or(0);
|
||
|
||
let status = scenes_data
|
||
.get("status")
|
||
.and_then(|v| v.as_str())
|
||
.unwrap_or("pending")
|
||
.to_string();
|
||
|
||
let scenes_array = scenes_data
|
||
.get("scenes")
|
||
.and_then(|v| v.as_array())
|
||
.map(|arr| arr.len() as i64)
|
||
.unwrap_or(0);
|
||
|
||
let vlm_done = scenes_data
|
||
.get("scenes")
|
||
.and_then(|v| v.as_array())
|
||
.map(|arr| {
|
||
arr.iter()
|
||
.filter(|s| {
|
||
let vlm_status = s.get("vlm_status").and_then(|v| v.as_str());
|
||
vlm_status == Some("completed") || vlm_status == Some("done")
|
||
})
|
||
.count() as i64
|
||
})
|
||
.unwrap_or(0);
|
||
|
||
Ok(Json(SceneVlmStats {
|
||
total_scenes: total_scenes.max(scenes_array),
|
||
status,
|
||
vlm_done,
|
||
vlm_total: total_scenes.max(scenes_array),
|
||
}))
|
||
}
|
||
|
||
// 掃描指定路徑
|
||
#[derive(Debug, Deserialize)]
|
||
pub struct ScanPathQuery {
|
||
pub path: String,
|
||
}
|
||
|
||
#[derive(Debug, Serialize)]
|
||
pub struct ScanPathResponse {
|
||
pub scanned_files: usize,
|
||
pub new_files: usize,
|
||
pub path: String,
|
||
}
|
||
|
||
fn scan_dir_recursive(dir: &std::path::Path, files: &mut Vec<std::path::PathBuf>) {
|
||
if let Ok(entries) = std::fs::read_dir(dir) {
|
||
for entry in entries.filter_map(|e| e.ok()) {
|
||
let path = entry.path();
|
||
if path.is_dir() {
|
||
scan_dir_recursive(&path, files);
|
||
} else if path.is_file() {
|
||
files.push(path);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
async fn scan_specific_path(
|
||
State(state): State<AppState>,
|
||
axum::extract::ConnectInfo(_addr): axum::extract::ConnectInfo<std::net::SocketAddr>,
|
||
Query(params): Query<ScanPathQuery>,
|
||
) -> Result<Json<ScanPathResponse>, StatusCode> {
|
||
use std::collections::HashSet;
|
||
|
||
let scan_root = std::path::Path::new(¶ms.path);
|
||
if !scan_root.exists() || !scan_root.is_dir() {
|
||
return Err(StatusCode::NOT_FOUND);
|
||
}
|
||
|
||
let allowed_extensions = vec!["mp4", "mov", "mkv", "avi", "webm", "jpg", "jpeg", "png", "gif", "webp"];
|
||
|
||
let table = schema::table_name("videos");
|
||
let registered: Vec<String> = sqlx::query_scalar(&format!("SELECT file_path FROM {}", table))
|
||
.fetch_all(state.db.pool())
|
||
.await
|
||
.unwrap_or_default();
|
||
let registered_set: HashSet<String> = registered.into_iter().collect();
|
||
|
||
// ── 收集候選檔案 (path, name, ext) ──────────────────────────────
|
||
// 優先透過 MarkBase 虛擬層 (/api/v2/myfiles/:user/files) 取得檔案清單;
|
||
// MarkBase 管不到的路徑(upload root 之外、外接碟等)回退本地遞迴掃描。
|
||
let mut candidates: Vec<(String, String, String)> = Vec::new(); // (path, name, ext)
|
||
|
||
// 依 upload_paths 推導 MarkBase username(user root = <upload>/<name>)
|
||
let mut username: Option<String> = None;
|
||
let mut rel_base = String::new();
|
||
let paths_table = schema::table_name("upload_paths");
|
||
if let Ok(rows) = sqlx::query_as::<_, (String, String)>(
|
||
&format!("SELECT name, full_path FROM {} WHERE enabled = true", paths_table),
|
||
)
|
||
.fetch_all(state.db.pool())
|
||
.await
|
||
{
|
||
for (name, full_path) in rows {
|
||
if params.path == full_path {
|
||
username = Some(name);
|
||
rel_base = String::new();
|
||
break;
|
||
}
|
||
if params.path.starts_with(&format!("{}/", full_path)) {
|
||
username = Some(name);
|
||
rel_base = params.path[full_path.len()..].trim_start_matches('/').to_string();
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
let mut used_markbase = false;
|
||
if let Some(user) = username {
|
||
let markbase_base =
|
||
std::env::var("MOMENTRY_MARKBASE_URL").unwrap_or_else(|_| "http://localhost:11438".to_string());
|
||
let mut url = format!("{}/api/v2/myfiles/{}/files", markbase_base, user);
|
||
if !rel_base.is_empty() {
|
||
url.push_str(&format!("?folder={}", rel_base));
|
||
}
|
||
let client = reqwest::Client::new();
|
||
if let Ok(resp) = client.get(&url).send().await {
|
||
if resp.status().is_success() {
|
||
if let Ok(files) = resp.json::<Vec<serde_json::Value>>().await {
|
||
for file in files {
|
||
let name = file.get("name").and_then(|v| v.as_str()).unwrap_or("");
|
||
if name.is_empty() {
|
||
continue;
|
||
}
|
||
let folder = file.get("folder").and_then(|v| v.as_str()).unwrap_or("");
|
||
// MarkBase 回傳的 folder 相對於 user root;換算成相對於掃描路徑
|
||
let rel_to_scan = folder.strip_prefix(&rel_base).unwrap_or(folder);
|
||
let rel_to_scan = rel_to_scan.trim_start_matches('/');
|
||
let file_path = if rel_to_scan.is_empty() {
|
||
format!("{}/{}", params.path, name)
|
||
} else {
|
||
format!("{}/{}/{}", params.path, rel_to_scan, name)
|
||
};
|
||
let ext = name.rsplit('.').next().unwrap_or("").to_lowercase();
|
||
if !allowed_extensions.contains(&ext.as_str()) {
|
||
continue;
|
||
}
|
||
candidates.push((file_path, name.to_string(), ext));
|
||
}
|
||
used_markbase = true;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
if !used_markbase {
|
||
// 回退:本地遞迴掃描(MarkBase 無法服務此路徑)
|
||
let mut all_files = Vec::new();
|
||
scan_dir_recursive(scan_root, &mut all_files);
|
||
for file_path in all_files {
|
||
let path_str = file_path.to_string_lossy().to_string();
|
||
let ext = file_path
|
||
.extension()
|
||
.and_then(|e| e.to_str())
|
||
.unwrap_or("")
|
||
.to_lowercase();
|
||
if !allowed_extensions.contains(&ext.as_str()) {
|
||
continue;
|
||
}
|
||
let file_name = file_path
|
||
.file_name()
|
||
.and_then(|n| n.to_str())
|
||
.unwrap_or("unknown")
|
||
.to_string();
|
||
candidates.push((path_str, file_name, ext));
|
||
}
|
||
}
|
||
|
||
let mut scanned = 0usize;
|
||
let mut new_files = 0usize;
|
||
|
||
for (path_str, file_name, ext) in candidates {
|
||
scanned += 1;
|
||
|
||
if registered_set.contains(&path_str) {
|
||
continue;
|
||
}
|
||
|
||
let file_uuid = uuid::Uuid::new_v4().to_string().replace("-", "");
|
||
|
||
let _ = sqlx::query(&format!(
|
||
"INSERT INTO {} (file_uuid, file_path, file_name, file_type, status) VALUES ($1, $2, $3, $4, 'pending')",
|
||
table
|
||
))
|
||
.bind(&file_uuid)
|
||
.bind(&path_str)
|
||
.bind(&file_name)
|
||
.bind(&ext)
|
||
.execute(state.db.pool())
|
||
.await;
|
||
|
||
new_files += 1;
|
||
}
|
||
|
||
Ok(Json(ScanPathResponse {
|
||
scanned_files: scanned,
|
||
new_files,
|
||
path: params.path,
|
||
}))
|
||
}
|