daemon: setting foundation for client creation
This commit is contained in:
1
Cargo.lock
generated
1
Cargo.lock
generated
@@ -215,6 +215,7 @@ dependencies = [
|
|||||||
"iana-time-zone",
|
"iana-time-zone",
|
||||||
"js-sys",
|
"js-sys",
|
||||||
"num-traits",
|
"num-traits",
|
||||||
|
"serde",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
"windows-targets 0.52.6",
|
"windows-targets 0.52.6",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -4,11 +4,14 @@ use diesel::prelude::*;
|
|||||||
use crate::repository::Repository;
|
use crate::repository::Repository;
|
||||||
use crate::settings::Settings;
|
use crate::settings::Settings;
|
||||||
|
|
||||||
|
pub use kordophone::api::TokenManagement;
|
||||||
|
use kordophone::model::JwtToken;
|
||||||
|
|
||||||
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
|
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
|
||||||
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
|
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
|
||||||
|
|
||||||
pub struct Database {
|
pub struct Database {
|
||||||
connection: SqliteConnection,
|
pub connection: SqliteConnection,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Database {
|
impl Database {
|
||||||
@@ -39,4 +42,22 @@ impl Database {
|
|||||||
let mut settings = Settings::new(&mut self.connection);
|
let mut settings = Settings::new(&mut self.connection);
|
||||||
f(&mut settings)
|
f(&mut settings)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static TOKEN_KEY: &str = "token";
|
||||||
|
|
||||||
|
impl TokenManagement for Database {
|
||||||
|
fn get_token(&mut self) -> Option<JwtToken> {
|
||||||
|
self.with_settings(|settings| {
|
||||||
|
let token: Result<Option<JwtToken>> = settings.get(TOKEN_KEY);
|
||||||
|
match token {
|
||||||
|
Ok(data) => data,
|
||||||
|
Err(_) => None,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_token(&mut self, token: JwtToken) {
|
||||||
|
self.with_settings(|settings| settings.put(TOKEN_KEY, &token).unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ edition = "2021"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
async-trait = "0.1.80"
|
async-trait = "0.1.80"
|
||||||
base64 = "0.22.1"
|
base64 = "0.22.1"
|
||||||
chrono = "0.4.38"
|
chrono = { version = "0.4.38", features = ["serde"] }
|
||||||
ctor = "0.2.8"
|
ctor = "0.2.8"
|
||||||
env_logger = "0.11.5"
|
env_logger = "0.11.5"
|
||||||
hyper = { version = "0.14", features = ["full"] }
|
hyper = { version = "0.14", features = ["full"] }
|
||||||
|
|||||||
@@ -26,3 +26,27 @@ pub trait APIInterface {
|
|||||||
async fn authenticate(&mut self, credentials: Credentials) -> Result<JwtToken, Self::Error>;
|
async fn authenticate(&mut self, credentials: Credentials) -> Result<JwtToken, Self::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub trait TokenManagement {
|
||||||
|
fn get_token(&mut self) -> Option<JwtToken>;
|
||||||
|
fn set_token(&mut self, token: JwtToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct InMemoryTokenManagement {
|
||||||
|
token: Option<JwtToken>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InMemoryTokenManagement {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self { token: None }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TokenManagement for InMemoryTokenManagement {
|
||||||
|
fn get_token(&mut self) -> Option<JwtToken> {
|
||||||
|
self.token.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_token(&mut self, token: JwtToken) {
|
||||||
|
self.token = Some(token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,23 +7,23 @@ use base64::{
|
|||||||
|
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
use hyper::http::HeaderValue;
|
use hyper::http::HeaderValue;
|
||||||
use serde::Deserialize;
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
#[derive(Deserialize, Serialize, Debug, Clone)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
struct JwtHeader {
|
struct JwtHeader {
|
||||||
alg: String,
|
alg: String,
|
||||||
typ: String,
|
typ: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
#[derive(Deserialize, Serialize, Debug, Clone)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
enum ExpValue {
|
enum ExpValue {
|
||||||
Integer(i64),
|
Integer(i64),
|
||||||
String(String),
|
String(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
#[derive(Deserialize, Serialize, Debug, Clone)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
struct JwtPayload {
|
struct JwtPayload {
|
||||||
exp: serde_json::Value,
|
exp: serde_json::Value,
|
||||||
@@ -31,7 +31,7 @@ struct JwtPayload {
|
|||||||
user: Option<String>,
|
user: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Deserialize, Serialize, Debug, Clone)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub struct JwtToken {
|
pub struct JwtToken {
|
||||||
header: JwtHeader,
|
header: JwtHeader,
|
||||||
|
|||||||
@@ -1,13 +1,23 @@
|
|||||||
|
mod settings;
|
||||||
|
use settings::Settings;
|
||||||
|
|
||||||
use directories::ProjectDirs;
|
use directories::ProjectDirs;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
use kordophone_db::{
|
use kordophone_db::{
|
||||||
database::Database,
|
database::Database,
|
||||||
models::Conversation,
|
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)]
|
#[derive(Debug, Error)]
|
||||||
pub enum DaemonError {
|
pub enum DaemonError {
|
||||||
@@ -18,7 +28,6 @@ pub enum DaemonError {
|
|||||||
pub struct Daemon {
|
pub struct Daemon {
|
||||||
pub version: String,
|
pub version: String,
|
||||||
database: Database,
|
database: Database,
|
||||||
client: Option<HTTPAPIClient>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Daemon {
|
impl Daemon {
|
||||||
@@ -31,27 +40,80 @@ impl Daemon {
|
|||||||
std::fs::create_dir_all(database_dir)?;
|
std::fs::create_dir_all(database_dir)?;
|
||||||
|
|
||||||
let database = Database::new(&database_path.to_string_lossy())?;
|
let database = Database::new(&database_path.to_string_lossy())?;
|
||||||
|
Ok(Self { version: "0.1.0".to_string(), database })
|
||||||
// TODO: Check to see if we have client settings in the database
|
|
||||||
|
|
||||||
|
|
||||||
Ok(Self { version: "0.1.0".to_string(), database, client: None })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_conversations(&mut self) -> Vec<Conversation> {
|
pub fn get_conversations(&mut self) -> Vec<Conversation> {
|
||||||
self.database.with_repository(|r| r.all_conversations().unwrap())
|
self.database.with_repository(|r| r.all_conversations().unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn sync_all_conversations(&mut self) -> Result<()> {
|
pub async fn sync_all_conversations(&mut self) -> Result<()> {
|
||||||
let client = self.client
|
let mut client = self.get_client()
|
||||||
.as_mut()
|
.map_err(|_| DaemonError::ClientNotConfigured)?;
|
||||||
.ok_or(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(())
|
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 {
|
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();
|
let data_dir = proj_dirs.data_dir();
|
||||||
data_dir.join("database.db")
|
data_dir.join("database.db")
|
||||||
} else {
|
} else {
|
||||||
@@ -59,4 +121,15 @@ impl Daemon {
|
|||||||
PathBuf::from("database.db")
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
35
kordophoned/src/daemon/settings.rs
Normal file
35
kordophoned/src/daemon/settings.rs
Normal 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(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
use dbus::arg;
|
use dbus::arg;
|
||||||
use dbus_tree::MethodErr;
|
use dbus_tree::MethodErr;
|
||||||
use std::sync::{Arc, Mutex, MutexGuard};
|
use std::sync::{Arc, Mutex, MutexGuard};
|
||||||
use log::info;
|
use std::future::Future;
|
||||||
|
use std::thread;
|
||||||
|
|
||||||
use crate::daemon::Daemon;
|
use crate::daemon::Daemon;
|
||||||
use crate::dbus::interface::NetBuzzertKordophoneRepository as DbusRepository;
|
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> {
|
fn sync_all_conversations(&mut self) -> Result<bool, dbus::MethodErr> {
|
||||||
let mut daemon = self.get_daemon()?;
|
let mut daemon = self.get_daemon()?;
|
||||||
daemon.sync_all_conversations().map_err(|e| {
|
|
||||||
log::error!("Failed to sync conversations: {}", e);
|
// TODO: We don't actually probably want to block here.
|
||||||
MethodErr::failed(&format!("Failed to sync conversations: {}", e))
|
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)
|
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")
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
use kordophone::APIInterface;
|
use kordophone::APIInterface;
|
||||||
use kordophone::api::http_client::HTTPAPIClient;
|
use kordophone::api::http_client::HTTPAPIClient;
|
||||||
use kordophone::api::http_client::Credentials;
|
use kordophone::api::http_client::Credentials;
|
||||||
|
use kordophone::api::InMemoryTokenManagement;
|
||||||
|
|
||||||
use dotenv;
|
use dotenv;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use clap::Subcommand;
|
|||||||
use dbus::blocking::{Connection, Proxy};
|
use dbus::blocking::{Connection, Proxy};
|
||||||
|
|
||||||
const DBUS_NAME: &str = "net.buzzert.kordophonecd";
|
const DBUS_NAME: &str = "net.buzzert.kordophonecd";
|
||||||
const DBUS_PATH: &str = "/net/buzzert/kordophonecd";
|
const DBUS_PATH: &str = "/net/buzzert/kordophonecd/daemon";
|
||||||
|
|
||||||
mod dbus_interface {
|
mod dbus_interface {
|
||||||
#![allow(unused)]
|
#![allow(unused)]
|
||||||
|
|||||||
Reference in New Issue
Block a user