use std::{future::Future, path::PathBuf, sync::Arc}; use common::{ call::{Call, GetStorageUsage, Login, Logout, Register}, event::Event, model::{Attachment, CommunityUsage, Id, Staged, User, UserUsage}, open::Blob, }; use quinn::Connection; use tokio::sync::{mpsc, oneshot, watch}; mod fail; mod fetch; mod link; mod media; mod receive; pub use fail::{Fail, LinkError}; pub(crate) use link::dial; pub use link::start; use media::Media; pub(crate) fn device_name() -> String { let host = gethostname::gethostname() .to_string_lossy() .trim() .to_string(); let host = if host.is_empty() { "unknown".to_string() } else { host }; format!("{host} {}", std::env::consts::OS) } #[derive(Default)] pub struct Levels { pub voice: Vec<(Id, Vec)>, pub own: Vec, pub own_sending: bool, pub watching: Vec<(Id, Vec)>, pub sharing: Option>, } #[derive(Debug)] pub enum NetworkEvent { Connected, VoiceRejoined, VoiceEnded, Disconnected(LinkError), SessionLost, Pushed(Box), } pub(super) struct SignIn { token: Option, reply: oneshot::Sender, Fail>>, } #[derive(Clone)] pub struct NetworkHandle { sign_in: mpsc::Sender, server: watch::Sender, media: Arc, fetches: Arc, } impl NetworkHandle { pub fn server(&self) -> crate::Server { self.server.borrow().clone() } pub fn set_server(&self, server: crate::Server) -> bool { self.server.send_if_modified(|current| { let changed = *current != server; *current = server; changed }) } async fn switch(&self, token: Option) -> Result, Fail> { let (reply, response) = oneshot::channel(); self.sign_in .send(SignIn { token, reply }) .await .map_err(|_| Fail::Offline)?; response.await.map_err(|_| Fail::Offline)? } async fn sign_in(&self, token: String) -> Result { self.switch(Some(token)).await?.ok_or(Fail::Protocol) } async fn on_connection( &self, work: impl FnOnce(Connection) -> Fut + Send + 'static, ) -> Result where T: Send + 'static, Fut: Future> + Send + 'static, { let media = self.media.clone(); self.media .run(async move { let connection = media.connection().await?; work(connection).await }) .await } pub async fn call(&self, call: C) -> Result { call.validate()?; self.on_connection(move |connection| async move { link::call(&connection, call).await }) .await } pub async fn resume(&self, token: &str) -> Result<(User, String), Fail> { let user = self.sign_in(token.to_string()).await?; Ok((user, token.to_string())) } pub async fn detach(&self) -> Result<(), Fail> { self.switch(None).await.map(|_| ()) } pub async fn register( &self, username: &str, password: &str, invite: Option<&str>, ) -> Result<(User, String), Fail> { let session = self .call(Register { username: username.to_string(), password: password.to_string(), invite: invite.map(str::to_string), }) .await?; let user = self.sign_in(session.token.clone()).await?; Ok((user, session.token)) } pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Fail> { let session = self .call(Login { username: username.to_string(), password: password.to_string(), }) .await?; let user = self.sign_in(session.token.clone()).await?; Ok((user, session.token)) } pub async fn logout(&self) -> Result<(), Fail> { let result = self.call(Logout).await; self.detach().await?; result } pub async fn storage_usage(&self) -> Result<(Vec, Vec), Fail> { let usage = self.call(GetStorageUsage).await?; Ok((usage.users, usage.communities)) } pub async fn upload_attachment( &self, community_id: Id, path: PathBuf, maximum: Option, ) -> Result { self.on_connection(move |connection| async move { link::upload(&connection, community_id, &path, maximum).await }) .await } pub async fn download_attachment( &self, attachment_id: Id, thumbnail: bool, ) -> Result, Fail> { let blob = if thumbnail { Blob::Thumbnail(attachment_id) } else { Blob::Attachment(attachment_id) }; let fetches = self.fetches.clone(); self.on_connection( move |connection| async move { fetches.download(&connection, blob).await }, ) .await } pub async fn stage_release( &self, path: PathBuf, progress: watch::Sender, ) -> Result { self.on_connection(move |connection| async move { link::stage(&connection, &path, &progress).await }) .await } pub async fn download_backup(&self, name: &str, path: PathBuf) -> Result<(), Fail> { let name = name.to_string(); let fetches = self.fetches.clone(); self.on_connection(move |connection| async move { let _permit = fetches.permit().await; link::backup_download(&connection, &name, &path).await }) .await } }