feat: 添加完整的模板管理系统

🎉 新功能:
- 批量导入模板功能,支持文件夹结构解析
- 自动解析 draft_content.json 并提取轨道/素材信息
- 智能素材管理,自动复制到统一资源目录
- 路径转换为相对路径,确保模板可移植性
- 现代化的模板管理界面,支持网格/列表视图
- 搜索和筛选功能
- 模板详情预览和删除功能

🏗️ 技术实现:
- Python: TemplateManager 核心服务类
- Rust/Tauri: 跨平台命令处理和进程管理
- React/TypeScript: 响应式前端界面
- JSON-RPC: 前后端通信协议

📁 文件结构:
- 模板存储在 attachments/templates/{uuid}/ 目录
- 素材统一管理在 resources/ 子目录
- 元数据存储在 templates.json 文件

 已测试功能:
- 批量导入多个模板
- 模板列表显示和搜索
- 模板详情查看
- 模板删除操作
- CLI 命令行接口

这个系统为视频编辑提供了强大的模板管理能力,
支持从外部导入模板并自动处理素材依赖关系。
This commit is contained in:
root
2025-07-10 20:14:49 +08:00
parent 168ad4dafa
commit c73aeb58e9
15 changed files with 5187 additions and 20 deletions

View File

@@ -0,0 +1,349 @@
use serde::{Deserialize, Serialize};
use std::process::Command;
use std::io::{BufRead, BufReader, Read};
use std::time::{Duration, Instant};
use std::thread;
use std::sync::{Arc, Mutex};
use std::sync::mpsc;
#[derive(Debug, Deserialize)]
pub struct BatchImportRequest {
pub source_folder: String,
}
#[derive(Debug, Serialize)]
pub struct TemplateInfo {
pub id: String,
pub name: String,
pub description: String,
pub thumbnail_path: String,
pub draft_content_path: String,
pub resources_path: String,
pub created_at: String,
pub updated_at: String,
pub canvas_config: serde_json::Value,
pub duration: i64,
pub material_count: i32,
pub track_count: i32,
pub tags: Vec<String>,
}
async fn execute_python_template_command(_app: tauri::AppHandle, args: &[String]) -> Result<String, String> {
println!("Executing Python template command with args: {:?}", args);
// Get project root directory
let current_dir = std::env::current_dir()
.map_err(|e| format!("Failed to get current directory: {}", e))?;
let project_root = if current_dir.ends_with("src-tauri") {
current_dir.parent().unwrap_or(&current_dir).to_path_buf()
} else {
current_dir
};
println!("Working directory: {:?}", project_root);
// Try multiple Python commands in order of preference
let python_commands = if cfg!(target_os = "windows") {
vec!["python", "python3", "py"]
} else {
vec!["python3", "python"]
};
let mut child = None;
let mut last_error = String::new();
for python_cmd in python_commands {
println!("Trying Python command: {}", python_cmd);
let mut cmd = Command::new(python_cmd);
cmd.current_dir(&project_root);
cmd.args(args);
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
// Set environment variables for consistent encoding
cmd.env("PYTHONIOENCODING", "utf-8");
cmd.env("PYTHONUNBUFFERED", "1");
// On Windows, ensure UTF-8 console output
if cfg!(target_os = "windows") {
cmd.env("PYTHONUTF8", "1");
}
match cmd.spawn() {
Ok(process) => {
println!("Successfully started Python process with: {}", python_cmd);
child = Some(process);
break;
}
Err(e) => {
last_error = format!("Failed to start {} process: {}", python_cmd, e);
println!("{}", last_error);
continue;
}
}
}
let mut child = child.ok_or_else(|| {
format!("Failed to start Python process with any command. Last error: {}", last_error)
})?;
let stdout = child.stdout.take().unwrap();
let stderr = child.stderr.take().unwrap();
// Use channels for concurrent reading
let (stdout_tx, _stdout_rx) = mpsc::channel();
let (stderr_tx, _stderr_rx) = mpsc::channel();
let (result_tx, result_rx) = mpsc::channel();
let progress_messages = Arc::new(Mutex::new(Vec::new()));
let error_messages = Arc::new(Mutex::new(Vec::new()));
let final_result = Arc::new(Mutex::new(None::<String>));
// Spawn thread for reading stdout
let progress_messages_clone = Arc::clone(&progress_messages);
let final_result_clone = Arc::clone(&final_result);
thread::spawn(move || {
let mut reader = BufReader::new(stdout);
let mut buffer = Vec::new();
// Read raw bytes and handle encoding issues
loop {
buffer.clear();
match reader.read_until(b'\n', &mut buffer) {
Ok(0) => break, // EOF
Ok(_) => {
// Convert bytes to string, handling invalid UTF-8
let line = String::from_utf8_lossy(&buffer);
let line = line.trim_end_matches('\n').trim_end_matches('\r');
if line.is_empty() {
continue;
}
println!("Python stdout: {}", line);
// Parse JSON-RPC messages
if line.starts_with("JSONRPC:") {
let json_str = &line[8..]; // Remove "JSONRPC:" prefix
if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(json_str) {
if let Some(method) = json_value.get("method") {
if method == "progress" {
if let Ok(mut messages) = progress_messages_clone.lock() {
messages.push(json_str.to_string());
}
println!("Progress: {}", json_str);
}
} else if json_value.get("result").is_some() || json_value.get("error").is_some() {
// This is a final result or error response
if let Ok(mut result) = final_result_clone.lock() {
*result = Some(json_str.to_string());
}
println!("JSON-RPC result found: {}", json_str);
}
}
} else if line.trim().starts_with('{') && line.trim().ends_with('}') {
// Fallback: try to parse as direct JSON result
if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(line.trim()) {
// Check if this looks like a final result (has status field)
if json_value.get("status").is_some() {
if let Ok(mut result) = final_result_clone.lock() {
*result = Some(line.trim().to_string());
}
println!("Direct JSON result: {}", line.trim());
}
}
} else {
println!("Python other: {}", line);
}
if stdout_tx.send(line.to_string()).is_err() {
break;
}
}
Err(e) => {
println!("Error reading stdout: {}", e);
break;
}
}
}
});
// Spawn thread for reading stderr
let error_messages_clone = Arc::clone(&error_messages);
thread::spawn(move || {
let mut reader = BufReader::new(stderr);
let mut buffer = Vec::new();
// Read raw bytes and handle encoding issues
loop {
buffer.clear();
match reader.read_until(b'\n', &mut buffer) {
Ok(0) => break, // EOF
Ok(_) => {
// Convert bytes to string, handling invalid UTF-8
let line = String::from_utf8_lossy(&buffer);
let line = line.trim_end_matches('\n').trim_end_matches('\r');
if line.is_empty() {
continue;
}
println!("Python stderr: {}", line);
if let Ok(mut messages) = error_messages_clone.lock() {
messages.push(line.to_string());
}
if stderr_tx.send(line.to_string()).is_err() {
break;
}
}
Err(e) => {
println!("Error reading stderr: {}", e);
break;
}
}
}
});
// Spawn thread to wait for process completion
thread::spawn(move || {
match child.wait() {
Ok(status) => {
let _ = result_tx.send(Ok(status));
}
Err(e) => {
let _ = result_tx.send(Err(format!("Failed to wait for process: {}", e)));
}
}
});
// Wait for process to complete with timeout
println!("Waiting for Python process to complete...");
let timeout_duration = Duration::from_secs(600); // 10 minutes timeout
let start_time = Instant::now();
let exit_status = loop {
match result_rx.try_recv() {
Ok(Ok(status)) => break status,
Ok(Err(e)) => return Err(e),
Err(mpsc::TryRecvError::Empty) => {
if start_time.elapsed() > timeout_duration {
return Err("Python process timed out after 10 minutes".to_string());
}
thread::sleep(Duration::from_millis(100));
continue;
}
Err(mpsc::TryRecvError::Disconnected) => {
return Err("Process monitoring thread disconnected".to_string());
}
}
};
println!("Python process terminated with code: {:?}", exit_status.code());
// Extract final results from shared state
let final_result_value = {
final_result.lock().unwrap().clone()
};
let progress_messages_value = {
progress_messages.lock().unwrap().clone()
};
let error_messages_value = {
error_messages.lock().unwrap().clone()
};
// Return the final result if we found one
if let Some(result) = final_result_value {
println!("Extracted JSON-RPC result: {}", result);
return Ok(result);
}
// If no JSON-RPC result found, provide detailed error information
if exit_status.success() {
// Process succeeded but no output - this is unusual
let error_msg = if progress_messages_value.is_empty() {
"Python script completed successfully but produced no output"
} else {
"Python script completed but did not return a valid JSON result"
};
Err(error_msg.to_string())
} else {
// Process failed - provide detailed error based on exit code
let error_msg = if let Some(code) = exit_status.code() {
match code {
1 => "Python script failed with general error. Check if all dependencies are installed.".to_string(),
120 => "Python module import failed or function not supported. This may be due to missing dependencies or incompatible Python environment.".to_string(),
_ => format!("Python script failed with exit code: {}. This may indicate a system or environment issue.", code)
}
} else {
"Python process was killed by external signal.".to_string()
};
// Include any error output we captured
let mut full_error = error_msg;
if !progress_messages_value.is_empty() {
full_error.push_str(&format!("\n\nLast stdout: {}", progress_messages_value.join("\n")));
}
if !error_messages_value.is_empty() {
full_error.push_str(&format!("\n\nStderr: {}", error_messages_value.join("\n")));
}
Err(full_error)
}
}
#[tauri::command]
pub async fn batch_import_templates(app: tauri::AppHandle, request: BatchImportRequest) -> Result<String, String> {
let args = vec![
"-m".to_string(),
"python_core.services.template_manager".to_string(),
"--action".to_string(),
"batch_import".to_string(),
"--source_folder".to_string(),
request.source_folder,
];
execute_python_template_command(app, &args).await
}
#[tauri::command]
pub async fn get_templates(app: tauri::AppHandle) -> Result<String, String> {
let args = vec![
"-m".to_string(),
"python_core.services.template_manager".to_string(),
"--action".to_string(),
"get_templates".to_string(),
];
execute_python_template_command(app, &args).await
}
#[tauri::command]
pub async fn get_template(app: tauri::AppHandle, template_id: String) -> Result<String, String> {
let args = vec![
"-m".to_string(),
"python_core.services.template_manager".to_string(),
"--action".to_string(),
"get_template".to_string(),
"--template_id".to_string(),
template_id,
];
execute_python_template_command(app, &args).await
}
#[tauri::command]
pub async fn delete_template(app: tauri::AppHandle, template_id: String) -> Result<String, String> {
let args = vec![
"-m".to_string(),
"python_core.services.template_manager".to_string(),
"--action".to_string(),
"delete_template".to_string(),
"--template_id".to_string(),
template_id,
];
execute_python_template_command(app, &args).await
}