daemon: implement solution for background sync
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
use tokio::sync::oneshot;
|
||||
use kordophone_db::models::Conversation;
|
||||
|
||||
pub type Reply<T: Send> = oneshot::Sender<T>;
|
||||
pub type Reply<T> = oneshot::Sender<T>;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Event {
|
||||
/// Get the version of the daemon.
|
||||
GetVersion(Reply<String>),
|
||||
|
||||
@@ -10,9 +10,12 @@ use std::error::Error;
|
||||
use std::path::PathBuf;
|
||||
use thiserror::Error;
|
||||
use tokio::sync::mpsc::{Sender, Receiver};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
use futures_util::FutureExt;
|
||||
|
||||
use kordophone_db::{
|
||||
database::Database,
|
||||
database::{Database, DatabaseAccess},
|
||||
models::Conversation,
|
||||
repository::Repository,
|
||||
};
|
||||
@@ -36,7 +39,7 @@ pub struct Daemon {
|
||||
pub event_sender: Sender<Event>,
|
||||
event_receiver: Receiver<Event>,
|
||||
version: String,
|
||||
database: Database,
|
||||
database: Arc<Mutex<Database>>,
|
||||
runtime: tokio::runtime::Runtime,
|
||||
}
|
||||
|
||||
@@ -58,7 +61,8 @@ impl Daemon {
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let database = Database::new(&database_path.to_string_lossy())?;
|
||||
let database_impl = Database::new(&database_path.to_string_lossy())?;
|
||||
let database = Arc::new(Mutex::new(database_impl));
|
||||
Ok(Self { version: "0.1.0".to_string(), database, event_receiver, event_sender, runtime })
|
||||
}
|
||||
|
||||
@@ -75,70 +79,100 @@ impl Daemon {
|
||||
},
|
||||
|
||||
Event::SyncAllConversations(reply) => {
|
||||
self.sync_all_conversations().await.unwrap_or_else(|e| {
|
||||
log::error!("Error handling sync event: {}", e);
|
||||
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);
|
||||
}
|
||||
});
|
||||
|
||||
// This is a background operation, so return right away.
|
||||
reply.send(()).unwrap();
|
||||
},
|
||||
},
|
||||
|
||||
Event::GetAllConversations(reply) => {
|
||||
let conversations = self.get_conversations();
|
||||
let conversations = self.get_conversations().await;
|
||||
reply.send(conversations).unwrap();
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn get_conversations(&mut self) -> Vec<Conversation> {
|
||||
self.database.with_repository(|r| r.all_conversations().unwrap())
|
||||
async fn get_conversations(&mut self) -> Vec<Conversation> {
|
||||
self.database.lock().await.with_repository(|r| r.all_conversations().unwrap()).await
|
||||
}
|
||||
|
||||
async fn sync_all_conversations(&mut self) -> Result<()> {
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;
|
||||
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?;
|
||||
|
||||
let mut client = self.get_client()
|
||||
.map_err(|_| DaemonError::ClientNotConfigured)?;
|
||||
let server_url = settings.server_url
|
||||
.ok_or(DaemonError::ClientNotConfigured)?;
|
||||
|
||||
let mut client = HTTPAPIClient::new(
|
||||
server_url.parse().unwrap(),
|
||||
match (settings.username, settings.credential_item) {
|
||||
(Some(username), Some(password)) => Some(
|
||||
Credentials {
|
||||
username,
|
||||
password,
|
||||
}
|
||||
),
|
||||
_ => None,
|
||||
}
|
||||
);
|
||||
|
||||
// This function needed to implement TokenManagement
|
||||
// let token = database.lock().await.get_token();
|
||||
// TODO: Clent.token = token
|
||||
|
||||
// Fetch conversations from server
|
||||
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)?;
|
||||
|
||||
database.with_repository(|r| r.insert_conversation(conversation)).await?;
|
||||
|
||||
// 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)?;
|
||||
}
|
||||
database.with_repository(|r| -> Result<()> {
|
||||
for message in db_messages {
|
||||
r.insert_message(&conversation_id, message)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}).await?;
|
||||
}
|
||||
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn get_settings(&mut self) -> Result<Settings> {
|
||||
async fn get_settings(&mut self) -> Result<Settings> {
|
||||
let settings = self.database.with_settings(|s|
|
||||
Settings::from_db(s)
|
||||
)?;
|
||||
).await?;
|
||||
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
fn get_client(&mut self) -> Result<HTTPAPIClient> {
|
||||
async fn get_client(&mut self) -> Result<HTTPAPIClient> {
|
||||
let settings = self.database.with_settings(|s|
|
||||
Settings::from_db(s)
|
||||
)?;
|
||||
).await?;
|
||||
|
||||
let server_url = settings.server_url
|
||||
.ok_or(DaemonError::ClientNotConfigured)?;
|
||||
@@ -170,13 +204,3 @@ impl Daemon {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user