2025-04-27 12:53:45 -07:00
|
|
|
pub mod settings;
|
2025-04-25 20:02:18 -07:00
|
|
|
use settings::Settings;
|
|
|
|
|
|
2025-04-27 12:53:45 -07:00
|
|
|
pub mod events;
|
|
|
|
|
use events::*;
|
|
|
|
|
|
|
|
|
|
use anyhow::Result;
|
2025-04-25 16:54:37 -07:00
|
|
|
use directories::ProjectDirs;
|
2025-04-27 12:53:45 -07:00
|
|
|
use std::error::Error;
|
2025-04-25 16:54:37 -07:00
|
|
|
use std::path::PathBuf;
|
2025-04-25 18:02:54 -07:00
|
|
|
use thiserror::Error;
|
2025-04-27 12:53:45 -07:00
|
|
|
use tokio::sync::mpsc::{Sender, Receiver};
|
2025-04-27 13:40:59 -07:00
|
|
|
use std::sync::Arc;
|
|
|
|
|
use tokio::sync::Mutex;
|
2025-04-27 14:01:19 -07:00
|
|
|
use async_trait::async_trait;
|
2025-04-25 20:02:18 -07:00
|
|
|
|
2025-04-25 16:54:37 -07:00
|
|
|
use kordophone_db::{
|
2025-04-27 13:40:59 -07:00
|
|
|
database::{Database, DatabaseAccess},
|
2025-04-25 16:54:37 -07:00
|
|
|
models::Conversation,
|
2025-04-25 20:02:18 -07:00
|
|
|
repository::Repository,
|
2025-04-25 16:54:37 -07:00
|
|
|
};
|
|
|
|
|
|
2025-04-25 20:02:18 -07:00
|
|
|
use kordophone::model::JwtToken;
|
|
|
|
|
use kordophone::api::{
|
|
|
|
|
http_client::{Credentials, HTTPAPIClient},
|
|
|
|
|
APIInterface,
|
2025-04-27 14:01:19 -07:00
|
|
|
TokenStore,
|
2025-04-25 20:02:18 -07:00
|
|
|
};
|
2025-04-25 18:02:54 -07:00
|
|
|
|
|
|
|
|
#[derive(Debug, Error)]
|
|
|
|
|
pub enum DaemonError {
|
|
|
|
|
#[error("Client Not Configured")]
|
|
|
|
|
ClientNotConfigured,
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-27 12:53:45 -07:00
|
|
|
pub type DaemonResult<T> = Result<T, Box<dyn Error + Send + Sync>>;
|
|
|
|
|
|
2025-04-27 14:01:19 -07:00
|
|
|
struct DatabaseTokenStore {
|
|
|
|
|
database: Arc<Mutex<Database>>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[async_trait]
|
|
|
|
|
impl TokenStore for DatabaseTokenStore {
|
|
|
|
|
async fn get_token(&mut self) -> Option<JwtToken> {
|
|
|
|
|
self.database.lock().await.get_token().await
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn set_token(&mut self, token: JwtToken) {
|
|
|
|
|
self.database.lock().await.set_token(token).await;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-02-11 23:15:24 -08:00
|
|
|
pub struct Daemon {
|
2025-04-27 12:53:45 -07:00
|
|
|
pub event_sender: Sender<Event>,
|
|
|
|
|
event_receiver: Receiver<Event>,
|
|
|
|
|
version: String,
|
2025-04-27 13:40:59 -07:00
|
|
|
database: Arc<Mutex<Database>>,
|
2025-04-27 12:53:45 -07:00
|
|
|
runtime: tokio::runtime::Runtime,
|
2025-02-11 23:15:24 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Daemon {
|
2025-04-25 16:54:37 -07:00
|
|
|
pub fn new() -> Result<Self> {
|
|
|
|
|
let database_path = Self::get_database_path();
|
|
|
|
|
log::info!("Database path: {}", database_path.display());
|
|
|
|
|
|
|
|
|
|
// Create the database directory if it doesn't exist
|
|
|
|
|
let database_dir = database_path.parent().unwrap();
|
|
|
|
|
std::fs::create_dir_all(database_dir)?;
|
|
|
|
|
|
2025-04-27 12:53:45 -07:00
|
|
|
// Create event channels
|
|
|
|
|
let (event_sender, event_receiver) = tokio::sync::mpsc::channel(100);
|
|
|
|
|
|
|
|
|
|
// Create background task runtime
|
|
|
|
|
let runtime = tokio::runtime::Builder::new_multi_thread()
|
|
|
|
|
.enable_all()
|
|
|
|
|
.build()
|
|
|
|
|
.unwrap();
|
|
|
|
|
|
2025-04-27 13:40:59 -07:00
|
|
|
let database_impl = Database::new(&database_path.to_string_lossy())?;
|
|
|
|
|
let database = Arc::new(Mutex::new(database_impl));
|
2025-04-27 12:53:45 -07:00
|
|
|
Ok(Self { version: "0.1.0".to_string(), database, event_receiver, event_sender, runtime })
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub async fn run(&mut self) {
|
|
|
|
|
while let Some(event) = self.event_receiver.recv().await {
|
|
|
|
|
self.handle_event(event).await;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn handle_event(&mut self, event: Event) {
|
|
|
|
|
match event {
|
|
|
|
|
Event::GetVersion(reply) => {
|
|
|
|
|
reply.send(self.version.clone()).unwrap();
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
Event::SyncAllConversations(reply) => {
|
2025-04-27 13:40:59 -07:00
|
|
|
let db_clone = self.database.clone();
|
|
|
|
|
self.runtime.spawn(async move {
|
|
|
|
|
let result = Self::sync_all_conversations_impl(db_clone).await;
|
|
|
|
|
if let Err(e) = result {
|
|
|
|
|
log::error!("Error handling sync event: {}", e);
|
|
|
|
|
}
|
2025-04-27 12:53:45 -07:00
|
|
|
});
|
|
|
|
|
|
2025-04-27 13:40:59 -07:00
|
|
|
// This is a background operation, so return right away.
|
2025-04-27 12:53:45 -07:00
|
|
|
reply.send(()).unwrap();
|
2025-04-27 13:40:59 -07:00
|
|
|
},
|
2025-04-27 12:53:45 -07:00
|
|
|
|
|
|
|
|
Event::GetAllConversations(reply) => {
|
2025-04-27 13:40:59 -07:00
|
|
|
let conversations = self.get_conversations().await;
|
2025-04-27 12:53:45 -07:00
|
|
|
reply.send(conversations).unwrap();
|
|
|
|
|
},
|
|
|
|
|
}
|
2025-04-25 20:02:18 -07:00
|
|
|
}
|
|
|
|
|
|
2025-04-27 13:40:59 -07:00
|
|
|
async fn get_conversations(&mut self) -> Vec<Conversation> {
|
|
|
|
|
self.database.lock().await.with_repository(|r| r.all_conversations().unwrap()).await
|
2025-04-25 20:02:18 -07:00
|
|
|
}
|
|
|
|
|
|
2025-04-27 13:40:59 -07:00
|
|
|
async fn sync_all_conversations_impl(mut database: Arc<Mutex<Database>>) -> Result<()> {
|
|
|
|
|
log::info!("Starting conversation sync");
|
|
|
|
|
|
|
|
|
|
// Get client from the database
|
|
|
|
|
let settings = database.with_settings(|s| Settings::from_db(s))
|
|
|
|
|
.await?;
|
2025-04-27 12:53:45 -07:00
|
|
|
|
2025-04-27 13:40:59 -07:00
|
|
|
let server_url = settings.server_url
|
|
|
|
|
.ok_or(DaemonError::ClientNotConfigured)?;
|
2025-04-25 16:54:37 -07:00
|
|
|
|
2025-04-27 13:40:59 -07:00
|
|
|
let mut client = HTTPAPIClient::new(
|
|
|
|
|
server_url.parse().unwrap(),
|
|
|
|
|
match (settings.username, settings.credential_item) {
|
|
|
|
|
(Some(username), Some(password)) => Some(
|
|
|
|
|
Credentials {
|
|
|
|
|
username,
|
|
|
|
|
password,
|
|
|
|
|
}
|
|
|
|
|
),
|
|
|
|
|
_ => None,
|
2025-04-27 14:01:19 -07:00
|
|
|
},
|
|
|
|
|
DatabaseTokenStore { database: database.clone() }
|
2025-04-27 13:40:59 -07:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// This function needed to implement TokenManagement
|
|
|
|
|
// let token = database.lock().await.get_token();
|
|
|
|
|
// TODO: Clent.token = token
|
|
|
|
|
|
|
|
|
|
// Fetch conversations from server
|
2025-04-25 20:02:18 -07:00
|
|
|
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();
|
2025-04-27 13:40:59 -07:00
|
|
|
|
2025-04-25 20:02:18 -07:00
|
|
|
// Process each conversation
|
|
|
|
|
for conversation in db_conversations {
|
|
|
|
|
let conversation_id = conversation.guid.clone();
|
|
|
|
|
|
|
|
|
|
// Insert the conversation
|
2025-04-27 13:40:59 -07:00
|
|
|
database.with_repository(|r| r.insert_conversation(conversation)).await?;
|
|
|
|
|
|
2025-04-25 20:02:18 -07:00
|
|
|
// 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();
|
2025-04-27 13:40:59 -07:00
|
|
|
|
2025-04-25 20:02:18 -07:00
|
|
|
// Insert each message
|
2025-04-27 13:40:59 -07:00
|
|
|
database.with_repository(|r| -> Result<()> {
|
|
|
|
|
for message in db_messages {
|
|
|
|
|
r.insert_message(&conversation_id, message)?;
|
|
|
|
|
}
|
2025-04-25 20:02:18 -07:00
|
|
|
|
2025-04-27 13:40:59 -07:00
|
|
|
Ok(())
|
|
|
|
|
}).await?;
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-25 20:02:18 -07:00
|
|
|
Ok(())
|
2025-04-27 13:40:59 -07:00
|
|
|
}
|
2025-04-25 16:54:37 -07:00
|
|
|
|
2025-04-27 13:40:59 -07:00
|
|
|
async fn get_settings(&mut self) -> Result<Settings> {
|
2025-04-25 20:02:18 -07:00
|
|
|
let settings = self.database.with_settings(|s|
|
|
|
|
|
Settings::from_db(s)
|
2025-04-27 13:40:59 -07:00
|
|
|
).await?;
|
2025-04-25 20:02:18 -07:00
|
|
|
|
|
|
|
|
Ok(settings)
|
2025-04-25 16:54:37 -07:00
|
|
|
}
|
|
|
|
|
|
2025-04-27 14:01:19 -07:00
|
|
|
async fn get_client(&mut self) -> Result<HTTPAPIClient<DatabaseTokenStore>> {
|
2025-04-25 20:02:18 -07:00
|
|
|
let settings = self.database.with_settings(|s|
|
|
|
|
|
Settings::from_db(s)
|
2025-04-27 13:40:59 -07:00
|
|
|
).await?;
|
2025-04-25 20:02:18 -07:00
|
|
|
|
|
|
|
|
let server_url = settings.server_url
|
2025-04-25 18:02:54 -07:00
|
|
|
.ok_or(DaemonError::ClientNotConfigured)?;
|
|
|
|
|
|
2025-04-25 20:02:18 -07:00
|
|
|
let client = HTTPAPIClient::new(
|
|
|
|
|
server_url.parse().unwrap(),
|
|
|
|
|
|
|
|
|
|
match (settings.username, settings.credential_item) {
|
|
|
|
|
(Some(username), Some(password)) => Some(
|
|
|
|
|
Credentials {
|
|
|
|
|
username,
|
|
|
|
|
password,
|
|
|
|
|
}
|
|
|
|
|
),
|
|
|
|
|
_ => None,
|
2025-04-27 14:01:19 -07:00
|
|
|
},
|
|
|
|
|
DatabaseTokenStore { database: self.database.clone() }
|
2025-04-25 20:02:18 -07:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
Ok(client)
|
2025-04-25 18:02:54 -07:00
|
|
|
}
|
|
|
|
|
|
2025-04-25 16:54:37 -07:00
|
|
|
fn get_database_path() -> PathBuf {
|
2025-04-25 20:02:18 -07:00
|
|
|
if let Some(proj_dirs) = ProjectDirs::from("net", "buzzert", "kordophonecd") {
|
2025-04-25 16:54:37 -07:00
|
|
|
let data_dir = proj_dirs.data_dir();
|
|
|
|
|
data_dir.join("database.db")
|
|
|
|
|
} else {
|
|
|
|
|
// Fallback to a local path if we can't get the system directories
|
|
|
|
|
PathBuf::from("database.db")
|
|
|
|
|
}
|
2025-02-11 23:15:24 -08:00
|
|
|
}
|
2025-04-25 20:02:18 -07:00
|
|
|
}
|