Private
Public Access
1
0

daemon: setting foundation for client creation

This commit is contained in:
2025-04-25 20:02:18 -07:00
parent fe32efef2c
commit 82192ffbe5
10 changed files with 210 additions and 27 deletions

View File

@@ -1,13 +1,23 @@
mod settings;
use settings::Settings;
use directories::ProjectDirs;
use std::path::PathBuf;
use anyhow::Result;
use thiserror::Error;
use kordophone_db::{
database::Database,
models::Conversation,
repository::Repository,
};
use kordophone::api::http_client::HTTPAPIClient;
use kordophone::model::JwtToken;
use kordophone::api::{
http_client::{Credentials, HTTPAPIClient},
APIInterface,
TokenManagement,
};
#[derive(Debug, Error)]
pub enum DaemonError {
@@ -18,7 +28,6 @@ pub enum DaemonError {
pub struct Daemon {
pub version: String,
database: Database,
client: Option<HTTPAPIClient>,
}
impl Daemon {
@@ -31,27 +40,80 @@ impl Daemon {
std::fs::create_dir_all(database_dir)?;
let database = Database::new(&database_path.to_string_lossy())?;
// TODO: Check to see if we have client settings in the database
Ok(Self { version: "0.1.0".to_string(), database, client: None })
Ok(Self { version: "0.1.0".to_string(), database })
}
pub fn get_conversations(&mut self) -> Vec<Conversation> {
self.database.with_repository(|r| r.all_conversations().unwrap())
}
pub fn sync_all_conversations(&mut self) -> Result<()> {
let client = self.client
.as_mut()
.ok_or(DaemonError::ClientNotConfigured)?;
pub async fn sync_all_conversations(&mut self) -> Result<()> {
let mut client = self.get_client()
.map_err(|_| DaemonError::ClientNotConfigured)?;
let fetched_conversations = client.get_conversations().await?;
let db_conversations: Vec<kordophone_db::models::Conversation> = fetched_conversations.into_iter()
.map(|c| kordophone_db::models::Conversation::from(c))
.collect();
// Process each conversation
let mut repository = Repository::new(&mut self.database.connection);
for conversation in db_conversations {
let conversation_id = conversation.guid.clone();
// Insert the conversation
repository.insert_conversation(conversation)?;
// Fetch and sync messages for this conversation
let messages = client.get_messages(&conversation_id).await?;
let db_messages: Vec<kordophone_db::models::Message> = messages.into_iter()
.map(|m| kordophone_db::models::Message::from(m))
.collect();
// Insert each message
for message in db_messages {
repository.insert_message(&conversation_id, message)?;
}
}
Ok(())
}
pub fn get_settings(&mut self) -> Result<Settings> {
let settings = self.database.with_settings(|s|
Settings::from_db(s)
)?;
Ok(settings)
}
fn get_client(&mut self) -> Result<HTTPAPIClient> {
let settings = self.database.with_settings(|s|
Settings::from_db(s)
)?;
let server_url = settings.server_url
.ok_or(DaemonError::ClientNotConfigured)?;
let client = HTTPAPIClient::new(
server_url.parse().unwrap(),
match (settings.username, settings.credential_item) {
(Some(username), Some(password)) => Some(
Credentials {
username,
password,
}
),
_ => None,
}
);
Ok(client)
}
fn get_database_path() -> PathBuf {
if let Some(proj_dirs) = ProjectDirs::from("com", "kordophone", "kordophone") {
if let Some(proj_dirs) = ProjectDirs::from("net", "buzzert", "kordophonecd") {
let data_dir = proj_dirs.data_dir();
data_dir.join("database.db")
} else {
@@ -59,4 +121,15 @@ impl Daemon {
PathBuf::from("database.db")
}
}
}
}
impl TokenManagement for &mut Daemon {
fn get_token(&mut self) -> Option<JwtToken> {
self.database.get_token()
}
fn set_token(&mut self, token: JwtToken) {
self.database.set_token(token);
}
}

View File

@@ -0,0 +1,35 @@
use kordophone_db::settings::Settings as DbSettings;
use anyhow::Result;
mod keys {
pub static SERVER_URL: &str = "ServerURL";
pub static USERNAME: &str = "Username";
pub static CREDENTIAL_ITEM: &str = "CredentialItem";
}
pub struct Settings {
pub server_url: Option<String>,
pub username: Option<String>,
pub credential_item: Option<String>,
}
impl Settings {
pub fn from_db(db_settings: &mut DbSettings) -> Result<Self> {
let server_url = db_settings.get(keys::SERVER_URL)?;
let username = db_settings.get(keys::USERNAME)?;
let credential_item = db_settings.get(keys::CREDENTIAL_ITEM)?;
Ok(Self {
server_url,
username,
credential_item,
})
}
pub fn save(&self, db_settings: &mut DbSettings) -> Result<()> {
db_settings.put(keys::SERVER_URL, &self.server_url)?;
db_settings.put(keys::USERNAME, &self.username)?;
db_settings.put(keys::CREDENTIAL_ITEM, &self.credential_item)?;
Ok(())
}
}

View File

@@ -1,7 +1,8 @@
use dbus::arg;
use dbus_tree::MethodErr;
use std::sync::{Arc, Mutex, MutexGuard};
use log::info;
use std::future::Future;
use std::thread;
use crate::daemon::Daemon;
use crate::dbus::interface::NetBuzzertKordophoneRepository as DbusRepository;
@@ -47,10 +48,14 @@ impl DbusRepository for ServerImpl {
fn sync_all_conversations(&mut self) -> Result<bool, dbus::MethodErr> {
let mut daemon = self.get_daemon()?;
daemon.sync_all_conversations().map_err(|e| {
log::error!("Failed to sync conversations: {}", e);
MethodErr::failed(&format!("Failed to sync conversations: {}", e))
})?;
// TODO: We don't actually probably want to block here.
run_sync_future(daemon.sync_all_conversations())
.unwrap()
.map_err(|e| {
log::error!("Failed to sync conversations: {}", e);
MethodErr::failed(&format!("Failed to sync conversations: {}", e))
})?;
Ok(true)
}
@@ -90,3 +95,26 @@ impl DbusSettings for ServerImpl {
}
}
fn run_sync_future<F, T>(f: F) -> Result<T, MethodErr>
where
T: Send,
F: Future<Output = T> + Send,
{
// We use `scope` here to ensure that the thread is joined before the
// function returns. This allows us to capture references of values that
// have lifetimes shorter than 'static, which is what thread::spawn requires.
thread::scope(move |s| {
s.spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|_| MethodErr::failed("Unable to create tokio runtime"))?;
let result = rt.block_on(f);
Ok(result)
})
.join()
})
.expect("Error joining runtime thread")
}