From 76bc7e5e8bee9b3994855b071408a1de582d64f3 Mon Sep 17 00:00:00 2001 From: metamuffin Date: Fri, 7 Oct 2022 16:50:05 +0200 Subject: lib cleanup --- client-native-lib/src/state.rs | 42 ++++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 16 deletions(-) (limited to 'client-native-lib/src/state.rs') 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 */ -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>, - pub sender: UnboundedSender, pub peers: RwLock>>, - 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) { + 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, 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() } } -- cgit v1.2.3-70-g09d2