orchai/src-tauri/src/lib.rs

66 lines
1.9 KiB
Rust
Raw Normal View History

mod commands;
mod db;
mod error;
mod models;
use std::sync::{Arc, Mutex};
use tauri::Manager;
pub struct AppState {
pub db: Arc<Mutex<rusqlite::Connection>>,
pub encryption_key: [u8; 32],
pub http_client: reqwest::Client,
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
.setup(|app| {
let db_dir = app.path().app_data_dir()?;
std::fs::create_dir_all(&db_dir)?;
let db_path = db_dir.join("orchai.db");
let conn = db::init(&db_path).expect("Failed to initialize database");
let key_path = db_dir.join("orchai.key");
let encryption_key = load_or_generate_key(&key_path)?;
let http_client = reqwest::Client::new();
app.manage(AppState {
db: Arc::new(Mutex::new(conn)),
encryption_key,
http_client,
});
Ok(())
})
.invoke_handler(tauri::generate_handler![
commands::project::create_project,
commands::project::list_projects,
commands::project::get_project,
commands::project::update_project,
commands::project::delete_project,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
fn load_or_generate_key(path: &std::path::Path) -> Result<[u8; 32], Box<dyn std::error::Error>> {
use rand::RngCore;
if path.exists() {
let bytes = std::fs::read(path)?;
if bytes.len() != 32 {
return Err("Invalid key file size".into());
}
let mut key = [0u8; 32];
key.copy_from_slice(&bytes);
Ok(key)
} else {
let mut key = [0u8; 32];
rand::rngs::OsRng.fill_bytes(&mut key);
std::fs::write(path, &key)?;
Ok(key)
}
}