Inital Commit (Errors, I need to move through devices)

Signed-off-by: Alex Emmet <111742636+Alex-Emmet@users.noreply.github.com>
This commit is contained in:
Alex Emmet 2025-10-09 19:47:32 +00:00
commit 044eeb67a6
23 changed files with 5687 additions and 7 deletions

View file

@ -0,0 +1,189 @@
// part of calls or in your ws-server file
use std::sync::Arc;
use futures::{SinkExt, StreamExt, channel::mpsc::UnboundedSender, lock::Mutex};
use json::JsonValue;
use tokio::sync::mpsc::unbounded_channel;
use tungstenite::{Message, Utf8Bytes};
use uuid::Uuid;
use crate::{
calls::{call_group::CallGroup, call_group::Caller, call_manager::CallManagerState},
data::communication::{CommunicationType, CommunicationValue, DataTypes},
};
pub async fn handle_connection(
raw_stream: tokio::net::TcpStream,
state: Arc<Mutex<CallManagerState>>,
) {
let ws_stream = tokio_tungstenite::accept_async(raw_stream)
.await
.expect("Error during the websocket handshake");
let (mut outgoing, mut incoming) = ws_stream.split();
// We create a channel so other parts can send to this client
pub type Tx = UnboundedSender<Utf8Bytes>;
let (tx, mut rx): (_, _) = unbounded_channel();
// Spawn a task to forward from rx → outgoing
let mut outgoing_clone = outgoing;
tokio::spawn(async move {
while let Some(msg) = rx.recv().await {
let _ = outgoing_clone
.send(tokio_tungstenite::tungstenite::Message::Text(msg))
.await;
}
});
// Each connection will track its user_id, call_group, etc.
let mut maybe_user_id: Option<Uuid> = None;
let mut maybe_call_id: Option<Uuid> = None;
while let Some(msg) = incoming.next().await {
let msg = match msg {
Ok(m) => m,
Err(_) => break,
};
if let tokio_tungstenite::tungstenite::Message::Text(s) = msg {
// parse CommunicationValue
if let mut cv = CommunicationValue::from_json(&s) {
match cv.comm_type {
CommunicationType::identification => {
// extract fields
let user_str = cv.get_data(DataTypes::user_id).unwrap().as_str().unwrap();
let call_str = cv.get_data(DataTypes::call_id).unwrap().as_str().unwrap();
let _secret_sha = cv
.get_data(DataTypes::call_secret_sha)
.unwrap()
.as_str()
.unwrap();
let user_id = Uuid::parse_str(user_str).ok();
let call_id = Uuid::parse_str(call_str).ok();
if let (Some(uid), Some(cid)) = (user_id, call_id) {
maybe_user_id = Some(uid);
maybe_call_id = Some(cid);
// Add to call group
let mut st = state.lock().await;
let group = state.lock().await.get_or_create_group(cid, &_secret_sha);
group.clone().add_member(uid, tx.clone());
// Response: identification_response plus states
let mut response =
CommunicationValue::new(CommunicationType::identification_response)
.with_id(cv.get_id().clone());
// build user states
let mut users = JsonValue::new_object();
for c in group.callers.values() {
let mut user_info = JsonValue::new_object();
user_info.insert("state", JsonValue::from("muted".to_string()));
user_info.insert("streaming", JsonValue::from(false));
users.insert(&c.user_id.to_string(), JsonValue::from(user_info));
}
response = response.add_data(DataTypes::about, JsonValue::from(users));
// send back
let _ = tx.send(Utf8Bytes::from(response.to_json().to_string()));
}
}
CommunicationType::ping => {
// optionally parse LAST_PING
// reply with PONG with same message_id
let mut resp = CommunicationValue::new(CommunicationType::pong)
.with_id(cv.get_id().clone());
let _ = tx.send(Utf8Bytes::from(resp.to_json().to_string()));
}
CommunicationType::client_changed => {
match (maybe_user_id, cv.get_data(DataTypes::call_state)) {
(Some(uid), Some(JsonValue::String(state_str))) => {
if let Some(cid) = maybe_call_id {
{
let mut st = state.lock().await;
if let Some(group) = st.call_groups.get_mut(&cid) {
if let Some(caller) = group.caller_state_mut(&uid) {
caller_state_change(caller, &state_str);
}
let mut bc = cv.clone();
bc = bc.add_data(
DataTypes::sender_id,
JsonValue::String(uid.to_string()),
);
group.broadcast(&bc.to_json().to_string());
}
}
}
}
_ => (),
}
}
CommunicationType::start_stream | CommunicationType::end_stream => {
if let Some(uid) = maybe_user_id {
if let Some(cid) = maybe_call_id {
let mut st = state.lock().await;
if let Some(group) = st.call_groups.get_mut(&cid) {
if let Some(caller) = group.caller_state_mut(&uid) {
let streaming =
cv.comm_type == CommunicationType::start_stream;
// set streaming
// caller.streaming = streaming; // if you store streaming
}
let mut bc = cv.clone();
bc = bc.add_data(
DataTypes::sender_id,
JsonValue::String(uid.to_string()),
);
group.broadcast(&bc.to_json().to_string());
}
}
}
}
CommunicationType::webrtc_sdp
| CommunicationType::webrtc_ice
| CommunicationType::watch_stream => {
if let Some(uid) = maybe_user_id {
if let Some(JsonValue::String(receiver_str)) =
cv.get_data(DataTypes::receiver_id)
{
if let Ok(receiver_id) = Uuid::parse_str(&receiver_str) {
if let Some(cid) = maybe_call_id {
let mut st = state.lock().await;
if let Some(group) = st.call_groups.get(&cid) {
let mut bc = cv.clone();
bc = bc.add_data(
DataTypes::sender_id,
JsonValue::String(uid.to_string()),
);
group.send_to(&receiver_id, &bc.to_json().to_string());
}
}
}
}
}
}
_ => {
// other types you may handle
}
}
}
}
}
// on close / disconnection:
if let (Some(uid), Some(cid)) = (maybe_user_id, maybe_call_id) {
let mut st = state.lock().await;
if let Some(group) = st.call_groups.get_mut(&cid) {
group.remove_member(&uid);
}
st.remove_inactive();
}
}
fn caller_state_change(_caller: &mut Caller, _state_str: &str) {
// parse and set your enum, e.g. match _state_str { "active" => ..., etc. }
}

106
src/calls/call_group.rs Normal file
View file

@ -0,0 +1,106 @@
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
use tokio::sync::mpsc::UnboundedSender;
use json::JsonValue;
use tungstenite::Utf8Bytes;
use uuid::Uuid;
use crate::data::communication::{CommunicationType, CommunicationValue, DataTypes};
pub type Tx = UnboundedSender<Utf8Bytes>;
#[derive(Debug)]
pub struct CallGroup {
pub call_id: Uuid,
secret: String,
pub callers: HashMap<Uuid, Caller>,
pub inform_on_end: HashSet<Uuid>,
pub started_at: u64,
pub ended_at: Option<u64>,
}
impl CallGroup {
pub fn new(call_id: Uuid, secret: String) -> Self {
CallGroup {
call_id,
secret,
callers: HashMap::new(),
inform_on_end: HashSet::new(),
started_at: chrono::Utc::now().timestamp_millis() as u64,
ended_at: None,
}
}
pub fn add_member(mut self, user_id: Uuid, tx: Tx) {
// If already present, drop old
if let Some(old) = self.callers.remove(&user_id) {
// optionally notify or close old
// no direct close since we dont hold session here
}
// Notify existing about new client
let mut cv = CommunicationValue::new(CommunicationType::client_connected);
cv = cv
.add_data(DataTypes::user_id, JsonValue::String(user_id.to_string()))
.add_data(
DataTypes::call_state,
JsonValue::String("muted".to_string()),
);
// broadcast
let msg = cv.to_json().to_string();
for c in self.callers.values() {
let _ = c.tx.send(Utf8Bytes::from(msg.clone()));
}
self.callers.insert(user_id, Caller { user_id, tx });
}
pub fn remove_member(&mut self, user_id: &Uuid) {
if self.callers.remove(user_id).is_some() {
let cv = CommunicationValue::new(CommunicationType::client_closed)
.add_data(DataTypes::user_id, JsonValue::String(user_id.to_string()))
.to_json()
.to_string();
for c in self.callers.values() {
let _ = c.tx.send(Utf8Bytes::from(cv.clone()));
}
}
if self.callers.is_empty() {
self.ended_at = Some(chrono::Utc::now().timestamp_millis() as u64);
// Optionally notify inform_on_end
let end_msg = CommunicationValue::new(CommunicationType::end_call)
.add_data(
DataTypes::call_id,
JsonValue::String(self.call_id.to_string()),
)
.to_json()
.to_string();
for &uid in &self.inform_on_end {
// here youd send via your Rho / other channel to user
// e.g. RhoManager::message_to(uid, end_msg.clone());
}
}
}
pub fn broadcast(&self, msg: &str) {
for c in self.callers.values() {
let _ = c.tx.send(Utf8Bytes::from(msg.clone()));
}
}
pub fn send_to(&self, target: &Uuid, msg: &str) {
if let Some(c) = self.callers.get(target) {
let _ = c.tx.send(Utf8Bytes::from(msg.clone()));
}
}
pub fn caller_state_mut(&mut self, uid: &Uuid) -> Option<&mut Caller> {
self.callers.get_mut(uid)
}
}
#[derive(Debug)]
pub struct Caller {
pub user_id: Uuid,
pub tx: Tx,
}

40
src/calls/call_manager.rs Normal file
View file

@ -0,0 +1,40 @@
use crate::calls::call_group::CallGroup;
use crate::data::communication::{CommunicationType, CommunicationValue, DataTypes};
use futures::{SinkExt, StreamExt};
use json::JsonValue;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
use tungstenite::Utf8Bytes;
use uuid::Uuid;
use warp::Filter;
pub type Tx = UnboundedSender<Utf8Bytes>;
#[derive(Debug)]
pub struct CallManagerState {
pub call_groups: HashMap<Uuid, Arc<CallGroup>>,
}
impl CallManagerState {
pub fn new() -> Self {
CallManagerState {
call_groups: HashMap::new(),
}
}
pub fn get_or_create_group(&mut self, call_id: Uuid, secret: &str) -> Arc<CallGroup> {
let g = self.call_groups.get_mut(&call_id);
if let Some(group) = g {
group.clone()
} else {
let cg = Arc::new(CallGroup::new(call_id, secret.to_string()));
self.call_groups.insert(call_id, cg);
self.call_groups.get(&call_id).unwrap().clone()
}
}
pub fn remove_inactive(&mut self) {
self.call_groups.retain(|_k, v| v.callers.len() > 0);
}
}

3
src/calls/mod.rs Normal file
View file

@ -0,0 +1,3 @@
pub mod call_connection;
pub mod call_group;
pub mod call_manager;