Migrated the data & config directory retrieval from Tauri JS to the runtime API

This commit is contained in:
Thorsten Sommer 2024-08-29 13:07:42 +02:00
parent 88ea640a68
commit 9f41062cb4
Signed by: tsommer
GPG Key ID: 371BBA77A02C0108
3 changed files with 59 additions and 9 deletions

View File

@ -14,9 +14,6 @@ namespace AIStudio.Layout;
public partial class MainLayout : LayoutComponentBase, IMessageBusReceiver, IDisposable public partial class MainLayout : LayoutComponentBase, IMessageBusReceiver, IDisposable
{ {
[Inject]
private IJSRuntime JsRuntime { get; init; } = null!;
[Inject] [Inject]
private SettingsManager SettingsManager { get; init; } = null!; private SettingsManager SettingsManager { get; init; } = null!;
@ -34,6 +31,9 @@ public partial class MainLayout : LayoutComponentBase, IMessageBusReceiver, IDis
[Inject] [Inject]
private NavigationManager NavigationManager { get; init; } = null!; private NavigationManager NavigationManager { get; init; } = null!;
[Inject]
private ILogger<MainLayout> Logger { get; init; } = null!;
public string AdditionalHeight { get; private set; } = "0em"; public string AdditionalHeight { get; private set; } = "0em";
@ -71,12 +71,15 @@ public partial class MainLayout : LayoutComponentBase, IMessageBusReceiver, IDis
// We use the Tauri API (Rust) to get the data and config directories // We use the Tauri API (Rust) to get the data and config directories
// for this app. // for this app.
// //
var dataDir = await this.JsRuntime.InvokeAsync<string>("window.__TAURI__.path.appLocalDataDir"); var dataDir = await this.RustService.GetDataDirectory();
var configDir = await this.JsRuntime.InvokeAsync<string>("window.__TAURI__.path.appConfigDir"); var configDir = await this.RustService.GetConfigDirectory();
this.Logger.LogInformation($"The data directory is: '{dataDir}'");
this.Logger.LogInformation($"The config directory is: '{configDir}'");
// Store the directories in the settings manager: // Store the directories in the settings manager:
SettingsManager.ConfigDirectory = configDir; SettingsManager.ConfigDirectory = configDir;
SettingsManager.DataDirectory = Path.Join(dataDir, "data"); SettingsManager.DataDirectory = dataDir;
Directory.CreateDirectory(SettingsManager.DataDirectory); Directory.CreateDirectory(SettingsManager.DataDirectory);
// Ensure that all settings are loaded: // Ensure that all settings are loaded:

View File

@ -87,6 +87,30 @@ public sealed class RustService(string apiPort) : IDisposable
} }
} }
public async Task<string> GetConfigDirectory()
{
var response = await this.http.GetAsync("/system/directories/config");
if (!response.IsSuccessStatusCode)
{
this.logger!.LogError($"Failed to get the config directory from Rust: '{response.StatusCode}'");
return string.Empty;
}
return await response.Content.ReadAsStringAsync();
}
public async Task<string> GetDataDirectory()
{
var response = await this.http.GetAsync("/system/directories/data");
if (!response.IsSuccessStatusCode)
{
this.logger!.LogError($"Failed to get the data directory from Rust: '{response.StatusCode}'");
return string.Empty;
}
return await response.Content.ReadAsStringAsync();
}
/// <summary> /// <summary>
/// Tries to copy the given text to the clipboard. /// Tries to copy the given text to the clipboard.
/// </summary> /// </summary>

View File

@ -7,7 +7,7 @@ extern crate core;
use std::collections::{BTreeMap, HashMap, HashSet}; use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt; use std::fmt;
use std::net::TcpListener; use std::net::TcpListener;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
@ -87,6 +87,10 @@ static ENCRYPTION: Lazy<Encryption> = Lazy::new(|| {
Encryption::new(&secret_key, &secret_key_salt).unwrap() Encryption::new(&secret_key, &secret_key_salt).unwrap()
}); });
static DATA_DIRECTORY: OnceLock<String> = OnceLock::new();
static CONFIG_DIRECTORY: OnceLock<String> = OnceLock::new();
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
@ -196,7 +200,7 @@ async fn main() {
_ = rocket::custom(figment) _ = rocket::custom(figment)
.mount("/", routes![ .mount("/", routes![
dotnet_port, dotnet_ready, set_clipboard, check_for_update, install_update, dotnet_port, dotnet_ready, set_clipboard, check_for_update, install_update,
get_secret, store_secret, delete_secret get_secret, store_secret, delete_secret, get_data_directory, get_config_directory,
]) ])
.ignite().await.unwrap() .ignite().await.unwrap()
.launch().await.unwrap(); .launch().await.unwrap();
@ -310,6 +314,9 @@ async fn main() {
let logger_path = app.path_resolver().app_local_data_dir().unwrap(); let logger_path = app.path_resolver().app_local_data_dir().unwrap();
let logger_path = logger_path.join("data"); let logger_path = logger_path.join("data");
DATA_DIRECTORY.set(logger_path.to_str().unwrap().to_string()).map_err(|_| error!("Was not abe to set the data directory.")).unwrap();
CONFIG_DIRECTORY.set(app.path_resolver().app_config_dir().unwrap().to_str().unwrap().to_string()).map_err(|_| error!("Was not able to set the config directory.")).unwrap();
info!(Source = "Bootloader Tauri"; "Reconfigure the file logger to use the app data directory {logger_path:?}"); info!(Source = "Bootloader Tauri"; "Reconfigure the file logger to use the app data directory {logger_path:?}");
logger.reset_flw(&FileLogWriter::builder( logger.reset_flw(&FileLogWriter::builder(
FileSpec::default() FileSpec::default()
@ -609,6 +616,22 @@ fn dotnet_port() -> String {
format!("{dotnet_server_port}") format!("{dotnet_server_port}")
} }
#[get("/system/directories/data")]
fn get_data_directory() -> String {
match DATA_DIRECTORY.get() {
Some(data_directory) => data_directory.clone(),
None => String::from(""),
}
}
#[get("/system/directories/config")]
fn get_config_directory() -> String {
match CONFIG_DIRECTORY.get() {
Some(config_directory) => config_directory.clone(),
None => String::from(""),
}
}
#[get("/system/dotnet/ready")] #[get("/system/dotnet/ready")]
async fn dotnet_ready() { async fn dotnet_ready() {
let main_window_spawn_clone = &MAIN_WINDOW; let main_window_spawn_clone = &MAIN_WINDOW;
@ -759,7 +782,7 @@ fn store_secret(request: Json<StoreSecret>) -> Json<StoreSecretResponse> {
}) })
}, },
}; };
let service = format!("mindwork-ai-studio::{}", request.destination); let service = format!("mindwork-ai-studio::{}", request.destination);
let entry = Entry::new(service.as_str(), user_name).unwrap(); let entry = Entry::new(service.as_str(), user_name).unwrap();
let result = entry.set_password(decrypted_text.as_str()); let result = entry.set_password(decrypted_text.as_str());