ubisync/ubisync-lib/src/lib.rs

85 lines
2.1 KiB
Rust
Raw Normal View History

2023-12-07 19:51:19 +01:00
use std::sync::Arc;
use anyhow::bail;
use api::{Api, ApiBuilder};
use comm::{CommHandle, Peer};
use config::Config;
use i2p::net::I2pSocketAddr;
2024-01-05 20:48:23 +01:00
use serde::{Deserialize, Serialize};
use state::{
types::{MessageId, PeerId},
ApiState, CommState, State,
};
2023-12-07 19:51:19 +01:00
pub mod api;
2023-12-07 19:51:19 +01:00
pub mod comm;
pub mod config;
pub mod state;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct MessageRelations {
pub parents: Vec<MessageId>,
}
pub struct Ubisync {
comm_handle: Arc<CommHandle>,
state_handle: Arc<State>,
api: Arc<Api>,
}
impl Ubisync {
pub async fn new(config: &Config) -> anyhow::Result<Self> {
let state = State::new().await?;
let comm_handle = Arc::new(CommHandle::new(CommState::new(state.clone()), config)?);
2023-12-07 19:51:19 +01:00
state.set_comm_handle(comm_handle.clone());
2024-01-05 20:48:23 +01:00
let api = Arc::new(
ApiBuilder::from(config.api_config.clone())
.build(ApiState::new(state.clone(), &config.jwt_secret))
.await,
);
2023-12-07 19:51:19 +01:00
comm_handle.run().await;
Ok(Ubisync {
comm_handle: comm_handle,
state_handle: state,
2024-01-05 20:48:23 +01:00
api: api,
2023-12-07 19:51:19 +01:00
})
}
pub fn api(&self) -> Arc<Api> {
self.api.clone()
}
2024-01-05 20:48:23 +01:00
pub fn add_peer(&self, p: impl TryInto<Peer, Error = anyhow::Error>) -> anyhow::Result<()> {
2023-12-07 19:51:19 +01:00
match p.try_into() {
Ok(peer) => self.state_handle.set_peer(&peer),
Err(e) => bail!(e),
}
}
pub fn add_peer_from_id(&self, id: PeerId) -> anyhow::Result<()> {
// TODO: resolve peer's name before setting
self.state_handle.set_peer(&Peer::new(id, "".to_string()))
}
pub fn get_peers(&self) -> Vec<Peer> {
self.state_handle.get_peers().unwrap_or(vec![])
}
pub fn get_destination(&self) -> anyhow::Result<I2pSocketAddr> {
self.comm_handle.i2p_address()
}
}
#[cfg(test)]
mod tests {
#[test]
#[ignore]
fn full_system_test1() {
// Do a test requiring a specific system state (including homeserver state or such)
// Disabled by default, since files need to be set up explicitly for this test
todo!()
}
}