diff options
Diffstat (limited to 'client-native-lib/src/state.rs')
-rw-r--r-- | client-native-lib/src/state.rs | 42 |
1 files changed, 26 insertions, 16 deletions
diff --git a/client-native-lib/src/state.rs b/client-native-lib/src/state.rs index 6182e66..841c876 100644 --- a/client-native-lib/src/state.rs +++ b/client-native-lib/src/state.rs @@ -3,48 +3,54 @@ which is licensed under the GNU Affero General Public License (version 3); see /COPYING. Copyright (C) 2022 metamuffin <metamuffin@disroot.org> */ -use std::{collections::HashMap, sync::Arc}; -use log::warn; -use tokio::sync::{mpsc::UnboundedSender, RwLock}; -use webrtc::api::API; - use crate::{ crypto::Key, peer::Peer, protocol::{self, ClientboundPacket, RelayMessage, RelayMessageWrapper, ServerboundPacket}, + signaling::SignalingConnection, Config, }; +use futures_util::{SinkExt, StreamExt}; +use log::{debug, info, warn}; +use std::{collections::HashMap, sync::Arc}; +use tokio::sync::RwLock; +use webrtc::api::API; pub struct State { + pub conn: SignalingConnection, pub config: Config, pub api: API, pub key: Key, pub my_id: RwLock<Option<usize>>, - pub sender: UnboundedSender<ServerboundPacket>, pub peers: RwLock<HashMap<usize, Arc<Peer>>>, - pub relay_tx: UnboundedSender<(usize, RelayMessage)>, } impl State { pub async fn my_id(&self) -> usize { self.my_id.read().await.expect("not initialized yet") } + pub async fn receive_loop(self: Arc<Self>) { + while let Some(packet) = self.conn.recv.write().await.next().await { + debug!("{packet:?}"); + let state = self.clone(); + state.on_message(packet).await + } + } + pub async fn on_message(self: Arc<Self>, packet: ClientboundPacket) { match packet { - protocol::ClientboundPacket::Init { - your_id, - version: _, - } => { + protocol::ClientboundPacket::Init { your_id, version } => { + info!("server is running {version:?}"); *self.my_id.write().await = Some(your_id); } protocol::ClientboundPacket::ClientJoin { id } => { if id == self.my_id().await { // we joined - YAY! } else { - self.peers.write().await.insert( - id, - Peer::create(self.clone(), self.relay_tx.clone(), id).await, - ); + self.peers + .write() + .await + .insert(id, Peer::create(self.clone(), id).await); } } protocol::ClientboundPacket::ClientLeave { id } => { @@ -67,7 +73,10 @@ impl State { } pub async fn send_relay(&self, recipient: usize, inner: RelayMessage) { - self.sender + self.conn + .send + .write() + .await .send(ServerboundPacket::Relay { recipient: Some(recipient), message: self.key.encrypt( @@ -78,6 +87,7 @@ impl State { .unwrap(), ), }) + .await .unwrap() } } |