Files
momentry_core/src/api/import_api.rs
T

479 lines
15 KiB
Rust

/// Import API - restore files from .momentry.tar.gz packages
use axum::{
extract::{Multipart, Query, State},
http::StatusCode,
routing::post,
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use crate::api::types::AppState;
// ─── Request/Response Structures ──────────────────────────────────────────────
#[derive(Debug, Deserialize)]
pub struct ImportQuery {
#[serde(default)]
pub package_path: Option<String>,
#[serde(default)]
pub target_video_path: Option<String>,
#[serde(default)]
pub force: bool,
}
#[derive(Debug, Serialize)]
pub struct ImportResponse {
pub success: bool,
pub file_uuid: String,
pub video_path: String,
pub restored_records: usize,
pub message: String,
}
// ─── API Handlers ────────────────────────────────────────────────────────────
/// POST /api/v1/import
/// Import a file from a .momentry.tar.gz package
///
/// Query params:
/// - package_path: Path to the .momentry.tar.gz file
/// - target_video_path: Where to restore the video (default: original path from manifest)
/// - force: Overwrite if file already exists
pub async fn import_file_handler(
State(state): State<AppState>,
Query(params): Query<ImportQuery>,
) -> Result<Json<ImportResponse>, (StatusCode, Json<serde_json::Value>)> {
let package_path = params.package_path.ok_or((
StatusCode::BAD_REQUEST,
Json(serde_json::json!({"error": "Missing package_path parameter"})),
))?;
let pkg_path = std::path::PathBuf::from(&package_path);
if !pkg_path.exists() {
return Err((
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": format!("Package not found: {}", package_path)})),
));
}
// Perform import
match import_file(
state.db.pool(),
&package_path,
params.target_video_path.as_deref(),
params.force,
)
.await
{
Ok(result) => Ok(Json(result)),
Err(e) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Import failed: {}", e)})),
)),
}
}
/// POST /api/v1/import/list
/// List available packages in offline_storage
pub async fn list_packages_handler(
Query(params): Query<ListQuery>,
) -> Result<Json<ListResponse>, (StatusCode, Json<serde_json::Value>)> {
let storage_dir = params.storage_dir.unwrap_or_else(|| {
"/Users/accusys/momentry/offline_storage/files".to_string()
});
let packages = list_packages(&storage_dir).map_err(|e| (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Failed to list packages: {}", e)})),
))?;
let total = packages.len();
Ok(Json(ListResponse {
success: true,
packages,
total,
}))
}
#[derive(Debug, Deserialize)]
pub struct ListQuery {
pub storage_dir: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct ListResponse {
pub success: bool,
pub packages: Vec<PackageInfo>,
pub total: usize,
}
#[derive(Debug, Serialize)]
pub struct PackageInfo {
pub path: String,
pub file_uuid: String,
pub file_name: String,
pub library: String,
pub size: u64,
pub exported_at: String,
}
// ─── Import Logic ────────────────────────────────────────────────────────────
pub async fn import_file(
pool: &sqlx::PgPool,
package_path: &str,
target_video_path: Option<&str>,
force: bool,
) -> Result<ImportResponse> {
let pkg_path = PathBuf::from(package_path);
let temp_dir = pkg_path.with_extension(""); // Remove .tar.gz
// 1. Extract package
extract_package(&pkg_path, &temp_dir)?;
// 2. Read manifest
let manifest_path = temp_dir.join("manifest.json");
let manifest_str = std::fs::read_to_string(&manifest_path)?;
let manifest: crate::core::export::ExportManifest = serde_json::from_str(&manifest_str)?;
let file_uuid = &manifest.file.uuid;
// 3. Check if file already exists
let videos_table = crate::core::db::schema::table_name("videos");
let exists: Option<(i32,)> = sqlx::query_as(
&format!("SELECT id FROM {} WHERE file_uuid = $1", videos_table)
)
.bind(file_uuid)
.fetch_optional(pool)
.await?;
if exists.is_some() && !force {
return Err(anyhow::anyhow!(
"File {} already exists. Use force=true to overwrite.",
file_uuid
));
}
// 4. Delete existing records if force
if exists.is_some() {
delete_existing_records(pool, file_uuid).await?;
}
// 5. Restore video file
let video_src = temp_dir.join("video").join(&manifest.file.file_name);
let video_dest = target_video_path
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(&manifest.file.file_path));
if video_src.exists() {
if let Some(parent) = video_dest.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::copy(&video_src, &video_dest)?;
}
// 6. Restore output files
restore_output_files(&temp_dir, &manifest.file.uuid)?;
// 7. Restore identities
restore_identities(&temp_dir)?;
// 8. Restore DB records
let restored_records = restore_db_records(pool, &temp_dir, file_uuid).await?;
// 9. Clean up temp dir
let _ = std::fs::remove_dir_all(&temp_dir);
Ok(ImportResponse {
success: true,
file_uuid: file_uuid.clone(),
video_path: video_dest.to_string_lossy().to_string(),
restored_records,
message: format!(
"Imported {} successfully. {} records restored.",
manifest.file.file_name, restored_records
),
})
}
fn list_packages(storage_dir: &str) -> Result<Vec<PackageInfo>> {
let mut packages = Vec::new();
let dir = std::path::PathBuf::from(storage_dir);
if !dir.exists() {
return Ok(packages);
}
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.to_string_lossy().ends_with(".tar.gz") {
// Try to read manifest from package
if let Ok(info) = read_package_info(&path) {
packages.push(info);
}
}
}
Ok(packages)
}
fn read_package_info(package_path: &std::path::Path) -> Result<PackageInfo> {
use std::os::unix::fs::MetadataExt;
// Extract to temp to read manifest
let temp_dir = package_path.with_extension("");
extract_package(package_path, &temp_dir)?;
let manifest_path = temp_dir.join("manifest.json");
let manifest_str = std::fs::read_to_string(&manifest_path)?;
let manifest: crate::core::export::ExportManifest = serde_json::from_str(&manifest_str)?;
let size = std::fs::metadata(package_path)?.size();
// Clean up
let _ = std::fs::remove_dir_all(&temp_dir);
Ok(PackageInfo {
path: package_path.to_string_lossy().to_string(),
file_uuid: manifest.file.uuid,
file_name: manifest.file.file_name,
library: manifest.file.library,
size,
exported_at: manifest.exported_at,
})
}
fn extract_package(package_path: &std::path::Path, dest_dir: &std::path::Path) -> Result<()> {
use flate2::read::GzDecoder;
use tar::Archive;
if dest_dir.exists() {
std::fs::remove_dir_all(dest_dir)?;
}
let tar_gz = std::fs::File::open(package_path)?;
let tar = GzDecoder::new(tar_gz);
let mut archive = Archive::new(tar);
archive.unpack(dest_dir)?;
Ok(())
}
fn restore_output_files(temp_dir: &std::path::Path, uuid: &str) -> Result<()> {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let dest_dir = std::path::PathBuf::from(output_dir);
let src_output = temp_dir.join("output");
if !src_output.exists() {
return Ok(());
}
// Copy JSON files
if let Ok(entries) = std::fs::read_dir(&src_output) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() {
let dest = dest_dir.join(path.file_name().unwrap());
std::fs::copy(&path, &dest)?;
} else if path.is_dir() {
// Copy trace directories
if path.file_name().map(|n| n == uuid).unwrap_or(false) {
let dest = dest_dir.join(uuid);
copy_dir_all(&path, &dest)?;
}
}
}
}
Ok(())
}
fn restore_identities(temp_dir: &std::path::Path) -> Result<()> {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let dest_identities = std::path::PathBuf::from(output_dir).join("identities");
let src_identities = temp_dir.join("identities");
if !src_identities.exists() {
return Ok(());
}
if !dest_identities.exists() {
std::fs::create_dir_all(&dest_identities)?;
}
if let Ok(entries) = std::fs::read_dir(&src_identities) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
let name = entry.file_name();
let dest = dest_identities.join(&name);
if !dest.exists() {
copy_dir_all(&entry.path(), &dest)?;
}
}
}
}
Ok(())
}
async fn restore_db_records(pool: &sqlx::PgPool, temp_dir: &std::path::Path, uuid: &str) -> Result<usize> {
let db_dir = temp_dir.join("db");
if !db_dir.exists() {
return Ok(0);
}
let mut restored = 0;
// Restore each table
let tables = [
"videos",
"processor_results",
"monitor_jobs",
"trace_profiles",
"tkg_nodes",
"chunk",
"identities",
];
for table in tables {
let json_path = db_dir.join(format!("{}.json", table));
if !json_path.exists() {
continue;
}
let json_str = std::fs::read_to_string(&json_path)?;
let records: Vec<serde_json::Value> = serde_json::from_str(&json_str)?;
let table_name = crate::core::db::schema::table_name(table);
for record in records {
// Remove id column (auto-increment with NOT NULL)
let mut record = record.clone();
if let Some(obj) = record.as_object_mut() {
obj.remove("id");
}
if record.as_object().map(|o| o.is_empty()).unwrap_or(true) {
continue;
}
// Build explicit INSERT with columns (excluding id)
let columns: Vec<String> = record.as_object().unwrap().keys()
.map(|k| format!("\"{}\"", k)).collect();
let cols_str = columns.join(", ");
// Build values with proper type handling
let values: Vec<String> = record.as_object().unwrap().values()
.map(|v| match v {
serde_json::Value::Null => "NULL".to_string(),
serde_json::Value::Bool(b) => b.to_string(),
serde_json::Value::Number(n) => n.to_string(),
serde_json::Value::String(s) => format!("'{}'", s.replace("'", "''")),
serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
format!("'{}'::jsonb", serde_json::to_string(v).unwrap_or_else(|_| "null".to_string()).replace("'", "''"))
}
})
.collect();
let vals_str = values.join(", ");
let sql = format!(
"INSERT INTO {} ({}) VALUES ({})",
table_name, cols_str, vals_str
);
let result = sqlx::query(&sql)
.execute(pool)
.await;
match result {
Ok(_) => restored += 1,
Err(e) => {
tracing::warn!("[Import] Failed to insert into {}: {}", table, e);
// Try alternative approach: column-by-column insert
if let Err(e2) = insert_record_fallback(pool, &table_name, &record).await {
tracing::warn!("[Import] Fallback also failed: {}", e2);
} else {
restored += 1;
}
}
}
}
}
Ok(restored)
}
async fn insert_record_fallback(pool: &sqlx::PgPool, table: &str, record: &serde_json::Value) -> Result<()> {
// Use jsonb_to_record approach
let json_str = serde_json::to_string(record)?;
sqlx::query(&format!(
"INSERT INTO {} SELECT * FROM jsonb_populate_record(NULL::{}, $1::jsonb)",
table, table
))
.bind(json_str)
.execute(pool)
.await?;
Ok(())
}
async fn delete_existing_records(pool: &sqlx::PgPool, uuid: &str) -> Result<usize> {
let mut deleted = 0;
let tables = [
("processor_results", "file_uuid"),
("monitor_jobs", "uuid"),
("trace_profiles", "file_uuid"),
("tkg_nodes", "file_uuid"),
("tkg_edges", "file_uuid"),
("chunk", "file_uuid"),
("face_detections", "file_uuid"),
("videos", "file_uuid"),
];
for (table, col) in tables {
let table_name = crate::core::db::schema::table_name(table);
let result = sqlx::query(&format!("DELETE FROM {} WHERE {} = $1", table_name, col))
.bind(uuid)
.execute(pool)
.await;
if let Ok(r) = result {
deleted += r.rows_affected() as usize;
}
}
Ok(deleted)
}
fn copy_dir_all(src: &std::path::Path, dest: &std::path::Path) -> Result<()> {
std::fs::create_dir_all(dest)?;
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let path = entry.path();
let dest_path = dest.join(entry.file_name());
if path.is_dir() {
copy_dir_all(&path, &dest_path)?;
} else {
std::fs::copy(&path, &dest_path)?;
}
}
Ok(())
}
use anyhow::Result;
// ─── Router ──────────────────────────────────────────────────────────────────
pub fn import_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/import", post(import_file_handler))
.route("/api/v1/import/list", post(list_packages_handler))
}