feat: DELETE API /api/v1/file/delete-unregistered — 永久刪除殘留 entry(磁碟檔 + DB + Qdrant + Redis),路徑限縮 storage root
This commit is contained in:
@@ -240,9 +240,159 @@ fn delete_output_files(uuid: &str, output_dir: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Delete API (true delete, not unregister) ────────────────────────────────
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct DeleteUnregisteredRequest {
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct DeleteUnregisteredResponse {
|
||||
pub success: bool,
|
||||
pub deleted_file: bool,
|
||||
pub deleted_db: bool,
|
||||
pub file_uuid: Option<String>,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Resolve the rust_unregister binary the same way files.rs unregister does.
|
||||
fn resolve_rust_unregister_binary() -> std::path::PathBuf {
|
||||
std::env::var_os("MOMENTRY_RUST_UNREGISTER")
|
||||
.map(std::path::PathBuf::from)
|
||||
.filter(|p| p.is_file())
|
||||
.or_else(|| {
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|p| p.parent().map(|d| d.join("rust_unregister")))
|
||||
.filter(|p| p.is_file())
|
||||
})
|
||||
.unwrap_or_else(|| std::path::PathBuf::from("target/release/rust_unregister"))
|
||||
}
|
||||
|
||||
/// Storage root for path validation (prevent arbitrary file deletion).
|
||||
fn storage_roots() -> Vec<std::path::PathBuf> {
|
||||
let home = std::env::var("HOME").unwrap_or_default();
|
||||
let mut roots = vec![];
|
||||
if let Ok(r) = std::env::var("MOMENTRY_STORAGE_ROOT") {
|
||||
roots.push(std::path::PathBuf::from(r));
|
||||
}
|
||||
roots.push(std::path::PathBuf::from(format!(
|
||||
"{}/momentry/var/sftpgo/data",
|
||||
home
|
||||
)));
|
||||
roots
|
||||
}
|
||||
|
||||
/// POST /api/v1/file/delete-unregistered
|
||||
/// Permanently delete an unregistered/leftover entry:
|
||||
/// - disk file (if still present)
|
||||
/// - videos row + all related records + outputs + Qdrant + Redis (via rust_unregister)
|
||||
pub async fn delete_unregistered_handler(
|
||||
State(_state): State<AppState>,
|
||||
Json(req): Json<DeleteUnregisteredRequest>,
|
||||
) -> Result<Json<DeleteUnregisteredResponse>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let path = std::path::PathBuf::from(&req.path);
|
||||
|
||||
// Security: only allow deletion inside the storage roots
|
||||
let canonical = path
|
||||
.canonicalize()
|
||||
.unwrap_or_else(|_| std::path::PathBuf::from(&req.path));
|
||||
let allowed = storage_roots()
|
||||
.iter()
|
||||
.filter_map(|r| r.canonicalize().ok())
|
||||
.any(|r| canonical.starts_with(&r));
|
||||
if !allowed {
|
||||
return Err((
|
||||
StatusCode::FORBIDDEN,
|
||||
Json(serde_json::json!({
|
||||
"error": "Path is outside the storage root",
|
||||
"path": req.path
|
||||
})),
|
||||
));
|
||||
}
|
||||
|
||||
// 1. Delete disk file (if still present)
|
||||
let mut deleted_file = false;
|
||||
if canonical.exists() {
|
||||
match std::fs::remove_file(&canonical) {
|
||||
Ok(()) => {
|
||||
deleted_file = true;
|
||||
tracing::info!("[DELETE] Removed file: {}", canonical.display());
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("[DELETE] Failed to remove file {}: {}", canonical.display(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Find a leftover DB row by file_path → full cleanup via rust_unregister
|
||||
let uuid: Option<String> = sqlx::query_scalar("SELECT file_uuid FROM videos WHERE file_path = $1")
|
||||
.bind(&req.path)
|
||||
.fetch_optional(_state.db.pool())
|
||||
.await
|
||||
.ok()
|
||||
.flatten();
|
||||
|
||||
let mut deleted_db = false;
|
||||
if let Some(ref uuid) = uuid {
|
||||
let binary_path = resolve_rust_unregister_binary();
|
||||
if !binary_path.is_file() {
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": format!("rust_unregister binary not found at {:?}", binary_path)
|
||||
})),
|
||||
));
|
||||
}
|
||||
let output = std::process::Command::new(&binary_path)
|
||||
.args(["--uuid", &uuid])
|
||||
.output()
|
||||
.map_err(|e| {
|
||||
tracing::error!("[DELETE] Failed to execute rust_unregister: {:?}", e);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": format!("rust_unregister failed: {}", e)})),
|
||||
)
|
||||
})?;
|
||||
if output.status.success() {
|
||||
deleted_db = true;
|
||||
tracing::info!("[DELETE] rust_unregister cleaned DB/Qdrant/Redis for {}", uuid);
|
||||
} else {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
tracing::error!("[DELETE] rust_unregister failed for {}: {}", uuid, stderr);
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({
|
||||
"error": format!("rust_unregister exit {:?}: {}", output.status.code(), stderr.trim())
|
||||
})),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let message = match (deleted_file, deleted_db) {
|
||||
(true, true) => "File and database records deleted".to_string(),
|
||||
(true, false) => "File deleted".to_string(),
|
||||
(false, true) => "Database records deleted".to_string(),
|
||||
(false, false) => "Nothing to delete (entry not found)".to_string(),
|
||||
};
|
||||
|
||||
Ok(Json(DeleteUnregisteredResponse {
|
||||
success: true,
|
||||
deleted_file,
|
||||
deleted_db,
|
||||
file_uuid: uuid,
|
||||
message,
|
||||
}))
|
||||
}
|
||||
|
||||
// ─── Router ──────────────────────────────────────────────────────────────────
|
||||
|
||||
pub fn unregister_routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/api/v1/file/:uuid/unregister", post(unregister_file_handler))
|
||||
.route(
|
||||
"/api/v1/file/delete-unregistered",
|
||||
post(delete_unregistered_handler),
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user