Auth Paths fixed
OUTLINE of calls Rho: Iota & Clients. Works Correct File handeling TODO: Omega Connection
This commit is contained in:
parent
044eeb67a6
commit
ba81f3651e
18 changed files with 488 additions and 477 deletions
108
Cargo.lock
generated
108
Cargo.lock
generated
|
|
@ -20,6 +20,7 @@ dependencies = [
|
||||||
"http",
|
"http",
|
||||||
"hyper",
|
"hyper",
|
||||||
"json",
|
"json",
|
||||||
|
"loom",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"pkcs8",
|
"pkcs8",
|
||||||
"rand 0.8.5",
|
"rand 0.8.5",
|
||||||
|
|
@ -683,6 +684,20 @@ dependencies = [
|
||||||
"slab",
|
"slab",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "generator"
|
||||||
|
version = "0.8.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "605183a538e3e2a9c1038635cc5c2d194e2ee8fd0d1b66b8349fad7dbacce5a2"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
"log",
|
||||||
|
"rustversion",
|
||||||
|
"windows 0.61.3",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "generic-array"
|
name = "generic-array"
|
||||||
version = "0.14.7"
|
version = "0.14.7"
|
||||||
|
|
@ -1187,6 +1202,28 @@ version = "0.4.28"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"
|
checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "loom"
|
||||||
|
version = "0.7.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "419e0dc8046cb947daa77eb95ae174acfbddb7673b4151f56d1eed8e93fbfaca"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"generator",
|
||||||
|
"scoped-tls",
|
||||||
|
"tracing",
|
||||||
|
"tracing-subscriber",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "matchers"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
|
||||||
|
dependencies = [
|
||||||
|
"regex-automata",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "matchit"
|
name = "matchit"
|
||||||
version = "0.8.4"
|
version = "0.8.4"
|
||||||
|
|
@ -2027,7 +2064,7 @@ dependencies = [
|
||||||
"ntapi",
|
"ntapi",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"rayon",
|
"rayon",
|
||||||
"windows",
|
"windows 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -2319,10 +2356,14 @@ version = "0.3.20"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2054a14f5307d601f88daf0553e1cbf472acc4f2c51afab632431cdcd72124d5"
|
checksum = "2054a14f5307d601f88daf0553e1cbf472acc4f2c51afab632431cdcd72124d5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"matchers",
|
||||||
"nu-ansi-term",
|
"nu-ansi-term",
|
||||||
|
"once_cell",
|
||||||
|
"regex-automata",
|
||||||
"sharded-slab",
|
"sharded-slab",
|
||||||
"smallvec",
|
"smallvec",
|
||||||
"thread_local",
|
"thread_local",
|
||||||
|
"tracing",
|
||||||
"tracing-core",
|
"tracing-core",
|
||||||
"tracing-log",
|
"tracing-log",
|
||||||
]
|
]
|
||||||
|
|
@ -2644,6 +2685,28 @@ dependencies = [
|
||||||
"windows-targets",
|
"windows-targets",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows"
|
||||||
|
version = "0.61.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
|
||||||
|
dependencies = [
|
||||||
|
"windows-collections",
|
||||||
|
"windows-core 0.61.2",
|
||||||
|
"windows-future",
|
||||||
|
"windows-link 0.1.3",
|
||||||
|
"windows-numerics",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-collections"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"
|
||||||
|
dependencies = [
|
||||||
|
"windows-core 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows-core"
|
name = "windows-core"
|
||||||
version = "0.52.0"
|
version = "0.52.0"
|
||||||
|
|
@ -2653,6 +2716,19 @@ dependencies = [
|
||||||
"windows-targets",
|
"windows-targets",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-core"
|
||||||
|
version = "0.61.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
|
||||||
|
dependencies = [
|
||||||
|
"windows-implement",
|
||||||
|
"windows-interface",
|
||||||
|
"windows-link 0.1.3",
|
||||||
|
"windows-result 0.3.4",
|
||||||
|
"windows-strings 0.4.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows-core"
|
name = "windows-core"
|
||||||
version = "0.62.1"
|
version = "0.62.1"
|
||||||
|
|
@ -2666,6 +2742,17 @@ dependencies = [
|
||||||
"windows-strings 0.5.0",
|
"windows-strings 0.5.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-future"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
|
||||||
|
dependencies = [
|
||||||
|
"windows-core 0.61.2",
|
||||||
|
"windows-link 0.1.3",
|
||||||
|
"windows-threading",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows-implement"
|
name = "windows-implement"
|
||||||
version = "0.60.1"
|
version = "0.60.1"
|
||||||
|
|
@ -2700,6 +2787,16 @@ version = "0.2.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "45e46c0661abb7180e7b9c281db115305d49ca1709ab8242adf09666d2173c65"
|
checksum = "45e46c0661abb7180e7b9c281db115305d49ca1709ab8242adf09666d2173c65"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-numerics"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"
|
||||||
|
dependencies = [
|
||||||
|
"windows-core 0.61.2",
|
||||||
|
"windows-link 0.1.3",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows-registry"
|
name = "windows-registry"
|
||||||
version = "0.5.3"
|
version = "0.5.3"
|
||||||
|
|
@ -2790,6 +2887,15 @@ dependencies = [
|
||||||
"windows_x86_64_msvc",
|
"windows_x86_64_msvc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-threading"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6"
|
||||||
|
dependencies = [
|
||||||
|
"windows-link 0.1.3",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_aarch64_gnullvm"
|
name = "windows_aarch64_gnullvm"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
tokio = { version = "*", features = ["full"] }
|
tokio = { version = "*", features = ["full"] }
|
||||||
tokio-tungstenite = "*"
|
tokio-tungstenite = { version = "*" }
|
||||||
tokio-util = { version = "*", features = ["full"] }
|
tokio-util = { version = "*", features = ["full"] }
|
||||||
hyper = { version = "*", features = ["full"] }
|
hyper = { version = "*", features = ["full"] }
|
||||||
futures-util = "*"
|
futures-util = "*"
|
||||||
|
|
@ -41,3 +41,4 @@ dashmap = "*"
|
||||||
warp = { version = "*" }
|
warp = { version = "*" }
|
||||||
chrono = "*"
|
chrono = "*"
|
||||||
tokio-stream = "*"
|
tokio-stream = "*"
|
||||||
|
loom = "0.7.2"
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,9 @@
|
||||||
use crate::data::communication::{CommunicationType, CommunicationValue, DataTypes};
|
use crate::data::communication::{CommunicationType, CommunicationValue, DataTypes};
|
||||||
use crate::util::config_util::CONFIG;
|
use crate::util::config_util::CONFIG;
|
||||||
use hex;
|
|
||||||
use json::JsonValue;
|
|
||||||
use reqwest::header::CONTENT_TYPE;
|
|
||||||
use reqwest::{Client, Response};
|
use reqwest::{Client, Response};
|
||||||
use sha2::{Digest, Sha256};
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct AuthUser {
|
pub struct AuthUser {
|
||||||
pub created_at: i64,
|
pub created_at: i64,
|
||||||
|
|
@ -30,12 +26,12 @@ fn client() -> Client {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_user(user_id: Uuid) -> Option<AuthUser> {
|
pub async fn get_user(user_id: Uuid) -> Option<AuthUser> {
|
||||||
let url = format!("https://auth.tensamin.methanium.net/api/get/{}/", user_id);
|
let url = format!("https://auth.tensamin.methanium.net/api/get/{}", user_id);
|
||||||
let client = client();
|
let client = client();
|
||||||
let res = client.get(&url).send().await.ok()?;
|
let res = client.get(&url).send().await.ok()?;
|
||||||
let json = res.text().await.ok()?;
|
let json = res.text().await.ok()?;
|
||||||
|
|
||||||
let mut cv = CommunicationValue::from_json(&json);
|
let cv = CommunicationValue::from_json(&json);
|
||||||
if cv.comm_type != CommunicationType::success {
|
if cv.comm_type != CommunicationType::success {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
@ -77,10 +73,7 @@ pub async fn get_iota_id(user_id: Uuid) -> Option<Uuid> {
|
||||||
let client = client();
|
let client = client();
|
||||||
let res = client
|
let res = client
|
||||||
.get(&url)
|
.get(&url)
|
||||||
.header(
|
.header("Authorization", CONFIG.lock().await.omikron_id.to_string())
|
||||||
"Authorization",
|
|
||||||
CONFIG.read().unwrap().omikron_id.to_string(),
|
|
||||||
)
|
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
|
|
@ -89,7 +82,7 @@ pub async fn get_iota_id(user_id: Uuid) -> Option<Uuid> {
|
||||||
let json = res.text().await.ok()?;
|
let json = res.text().await.ok()?;
|
||||||
let json = json.replace("iota_uuid", "iota_id");
|
let json = json.replace("iota_uuid", "iota_id");
|
||||||
|
|
||||||
let mut cv = CommunicationValue::from_json(&json);
|
let cv = CommunicationValue::from_json(&json);
|
||||||
if cv.comm_type != CommunicationType::success {
|
if cv.comm_type != CommunicationType::success {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
@ -99,17 +92,15 @@ pub async fn get_iota_id(user_id: Uuid) -> Option<Uuid> {
|
||||||
}
|
}
|
||||||
pub async fn is_private_key_valid(user_id: Uuid, pk_hash: &str) -> bool {
|
pub async fn is_private_key_valid(user_id: Uuid, pk_hash: &str) -> bool {
|
||||||
let url = format!(
|
let url = format!(
|
||||||
"https://auth.tensamin.methanium.net/api/get/private-key-hash/{}",
|
"https://auth.tensamin.methanium.net/api/get/private-key-hash/{}/",
|
||||||
user_id
|
user_id
|
||||||
);
|
);
|
||||||
|
|
||||||
let client = client();
|
let client = client();
|
||||||
|
println!("Auth: {}", CONFIG.lock().await.omikron_id);
|
||||||
let res = client
|
let res = client
|
||||||
.get(&url)
|
.get(&url)
|
||||||
.header(
|
.header("Authorization", CONFIG.lock().await.omikron_id.to_string())
|
||||||
"Authorization",
|
|
||||||
CONFIG.read().unwrap().omikron_id.to_string(),
|
|
||||||
)
|
|
||||||
.header("PrivateKeyHash", pk_hash)
|
.header("PrivateKeyHash", pk_hash)
|
||||||
.header("Accept", "application/json")
|
.header("Accept", "application/json")
|
||||||
.send()
|
.send()
|
||||||
|
|
@ -123,7 +114,8 @@ pub async fn is_private_key_valid(user_id: Uuid, pk_hash: &str) -> bool {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut cv = CommunicationValue::from_json(&body);
|
let cv = CommunicationValue::from_json(&body);
|
||||||
|
println!("Auth: {}", &body);
|
||||||
if cv.comm_type != CommunicationType::success {
|
if cv.comm_type != CommunicationType::success {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
@ -135,7 +127,7 @@ pub async fn is_private_key_valid(user_id: Uuid, pk_hash: &str) -> bool {
|
||||||
}
|
}
|
||||||
pub async fn get_public_key(user_id: Uuid) -> Option<String> {
|
pub async fn get_public_key(user_id: Uuid) -> Option<String> {
|
||||||
let url = format!(
|
let url = format!(
|
||||||
"https://auth.tensamin.methanium.net/api/{}/public-key/",
|
"https://auth.tensamin.methanium.net/api/{}/public-key",
|
||||||
user_id
|
user_id
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
@ -158,12 +150,12 @@ pub async fn get_public_key(user_id: Uuid) -> Option<String> {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_register() -> Option<Uuid> {
|
pub async fn get_register() -> Option<Uuid> {
|
||||||
let url = "https://auth.tensamin.methanium.net/api/register/init/".to_string();
|
let url = "https://auth.tensamin.methanium.net/api/register/init".to_string();
|
||||||
let client = client();
|
let client = client();
|
||||||
let res = client.get(&url).send().await.ok()?;
|
let res = client.get(&url).send().await.ok()?;
|
||||||
let json = res.text().await.ok()?;
|
let json = res.text().await.ok()?;
|
||||||
|
|
||||||
let mut cv = CommunicationValue::from_json(&json);
|
let cv = CommunicationValue::from_json(&json);
|
||||||
Uuid::parse_str(&*cv.get_data(DataTypes::user_id).unwrap().to_string()).ok()
|
Uuid::parse_str(&*cv.get_data(DataTypes::user_id).unwrap().to_string()).ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,15 @@
|
||||||
// part of calls or in your ws-server file
|
|
||||||
|
|
||||||
use std::sync::Arc;
|
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::{
|
use crate::{
|
||||||
calls::{call_group::CallGroup, call_group::Caller, call_manager::CallManagerState},
|
calls::{call_manager::CallManagerState, caller::Caller},
|
||||||
data::communication::{CommunicationType, CommunicationValue, DataTypes},
|
data::communication::{CommunicationType, CommunicationValue, DataTypes},
|
||||||
};
|
};
|
||||||
|
use futures::{SinkExt, StreamExt, lock::Mutex};
|
||||||
|
use json::JsonValue;
|
||||||
|
use tokio::sync::mpsc::UnboundedSender;
|
||||||
|
use tokio::sync::mpsc::unbounded_channel;
|
||||||
|
use tungstenite::Utf8Bytes;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
pub async fn handle_connection(
|
pub async fn handle_connection(
|
||||||
raw_stream: tokio::net::TcpStream,
|
raw_stream: tokio::net::TcpStream,
|
||||||
|
|
@ -21,11 +19,11 @@ pub async fn handle_connection(
|
||||||
.await
|
.await
|
||||||
.expect("Error during the websocket handshake");
|
.expect("Error during the websocket handshake");
|
||||||
|
|
||||||
let (mut outgoing, mut incoming) = ws_stream.split();
|
let (outgoing, mut incoming) = ws_stream.split();
|
||||||
|
|
||||||
// We create a channel so other parts can send to this client
|
// We create a channel so other parts can send to this client
|
||||||
pub type Tx = UnboundedSender<Utf8Bytes>;
|
pub type Tx = UnboundedSender<Utf8Bytes>;
|
||||||
let (tx, mut rx): (_, _) = unbounded_channel();
|
let (tx, mut rx): (UnboundedSender<_>, _) = unbounded_channel();
|
||||||
|
|
||||||
// Spawn a task to forward from rx → outgoing
|
// Spawn a task to forward from rx → outgoing
|
||||||
let mut outgoing_clone = outgoing;
|
let mut outgoing_clone = outgoing;
|
||||||
|
|
@ -48,7 +46,7 @@ pub async fn handle_connection(
|
||||||
};
|
};
|
||||||
if let tokio_tungstenite::tungstenite::Message::Text(s) = msg {
|
if let tokio_tungstenite::tungstenite::Message::Text(s) = msg {
|
||||||
// parse CommunicationValue
|
// parse CommunicationValue
|
||||||
if let mut cv = CommunicationValue::from_json(&s) {
|
let cv = CommunicationValue::from_json(&s);
|
||||||
match cv.comm_type {
|
match cv.comm_type {
|
||||||
CommunicationType::identification => {
|
CommunicationType::identification => {
|
||||||
// extract fields
|
// extract fields
|
||||||
|
|
@ -66,20 +64,19 @@ pub async fn handle_connection(
|
||||||
maybe_user_id = Some(uid);
|
maybe_user_id = Some(uid);
|
||||||
maybe_call_id = Some(cid);
|
maybe_call_id = Some(cid);
|
||||||
// Add to call group
|
// Add to call group
|
||||||
let mut st = state.lock().await;
|
|
||||||
let group = state.lock().await.get_or_create_group(cid, &_secret_sha);
|
let group = state.lock().await.get_or_create_group(cid, &_secret_sha);
|
||||||
group.clone().add_member(uid, tx.clone());
|
group.lock().await.add_member(uid, tx.clone());
|
||||||
|
|
||||||
// Response: identification_response plus states
|
// Response: identification_response plus states
|
||||||
let mut response =
|
let mut response =
|
||||||
CommunicationValue::new(CommunicationType::identification_response)
|
CommunicationValue::new(CommunicationType::identification_response)
|
||||||
.with_id(cv.get_id().clone());
|
.with_id(cv.get_id().clone());
|
||||||
// build user states
|
// build user states
|
||||||
let mut users = JsonValue::new_object();
|
let mut users = JsonValue::new_object();
|
||||||
for c in group.callers.values() {
|
for c in group.lock().await.callers.values() {
|
||||||
let mut user_info = JsonValue::new_object();
|
let mut user_info = JsonValue::new_object();
|
||||||
user_info.insert("state", JsonValue::from("muted".to_string()));
|
let _ = user_info.insert("state", JsonValue::from("muted".to_string()));
|
||||||
user_info.insert("streaming", JsonValue::from(false));
|
let _ = user_info.insert("streaming", JsonValue::from(false));
|
||||||
|
let _ =
|
||||||
users.insert(&c.user_id.to_string(), JsonValue::from(user_info));
|
users.insert(&c.user_id.to_string(), JsonValue::from(user_info));
|
||||||
}
|
}
|
||||||
response = response.add_data(DataTypes::about, JsonValue::from(users));
|
response = response.add_data(DataTypes::about, JsonValue::from(users));
|
||||||
|
|
@ -91,7 +88,7 @@ pub async fn handle_connection(
|
||||||
CommunicationType::ping => {
|
CommunicationType::ping => {
|
||||||
// optionally parse LAST_PING
|
// optionally parse LAST_PING
|
||||||
// reply with PONG with same message_id
|
// reply with PONG with same message_id
|
||||||
let mut resp = CommunicationValue::new(CommunicationType::pong)
|
let resp = CommunicationValue::new(CommunicationType::pong)
|
||||||
.with_id(cv.get_id().clone());
|
.with_id(cv.get_id().clone());
|
||||||
let _ = tx.send(Utf8Bytes::from(resp.to_json().to_string()));
|
let _ = tx.send(Utf8Bytes::from(resp.to_json().to_string()));
|
||||||
}
|
}
|
||||||
|
|
@ -102,10 +99,11 @@ pub async fn handle_connection(
|
||||||
if let Some(cid) = maybe_call_id {
|
if let Some(cid) = maybe_call_id {
|
||||||
{
|
{
|
||||||
let mut st = state.lock().await;
|
let mut st = state.lock().await;
|
||||||
if let Some(group) = st.call_groups.get_mut(&cid) {
|
let mut group =
|
||||||
if let Some(caller) = group.caller_state_mut(&uid) {
|
st.call_groups.get_mut(&cid).unwrap().lock().await;
|
||||||
|
let caller = group.caller_state_mut(&uid).unwrap();
|
||||||
caller_state_change(caller, &state_str);
|
caller_state_change(caller, &state_str);
|
||||||
}
|
|
||||||
let mut bc = cv.clone();
|
let mut bc = cv.clone();
|
||||||
bc = bc.add_data(
|
bc = bc.add_data(
|
||||||
DataTypes::sender_id,
|
DataTypes::sender_id,
|
||||||
|
|
@ -115,7 +113,6 @@ pub async fn handle_connection(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -124,23 +121,19 @@ pub async fn handle_connection(
|
||||||
if let Some(uid) = maybe_user_id {
|
if let Some(uid) = maybe_user_id {
|
||||||
if let Some(cid) = maybe_call_id {
|
if let Some(cid) = maybe_call_id {
|
||||||
let mut st = state.lock().await;
|
let mut st = state.lock().await;
|
||||||
if let Some(group) = st.call_groups.get_mut(&cid) {
|
let mut group = st.call_groups.get_mut(&cid).unwrap().lock().await;
|
||||||
if let Some(caller) = group.caller_state_mut(&uid) {
|
if let Some(caller) = group.caller_state_mut(&uid) {
|
||||||
let streaming =
|
let streaming = cv.comm_type == CommunicationType::start_stream;
|
||||||
cv.comm_type == CommunicationType::start_stream;
|
|
||||||
// set streaming
|
// set streaming
|
||||||
// caller.streaming = streaming; // if you store streaming
|
// caller.streaming = streaming; // if you store streaming
|
||||||
}
|
}
|
||||||
let mut bc = cv.clone();
|
let mut bc = cv.clone();
|
||||||
bc = bc.add_data(
|
bc = bc
|
||||||
DataTypes::sender_id,
|
.add_data(DataTypes::sender_id, JsonValue::String(uid.to_string()));
|
||||||
JsonValue::String(uid.to_string()),
|
|
||||||
);
|
|
||||||
group.broadcast(&bc.to_json().to_string());
|
group.broadcast(&bc.to_json().to_string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
CommunicationType::webrtc_sdp
|
CommunicationType::webrtc_sdp
|
||||||
| CommunicationType::webrtc_ice
|
| CommunicationType::webrtc_ice
|
||||||
|
|
@ -151,14 +144,17 @@ pub async fn handle_connection(
|
||||||
{
|
{
|
||||||
if let Ok(receiver_id) = Uuid::parse_str(&receiver_str) {
|
if let Ok(receiver_id) = Uuid::parse_str(&receiver_str) {
|
||||||
if let Some(cid) = maybe_call_id {
|
if let Some(cid) = maybe_call_id {
|
||||||
let mut st = state.lock().await;
|
let st = state.lock().await;
|
||||||
if let Some(group) = st.call_groups.get(&cid) {
|
if let Some(group) = st.call_groups.get(&cid) {
|
||||||
let mut bc = cv.clone();
|
let mut bc = cv.clone();
|
||||||
bc = bc.add_data(
|
bc = bc.add_data(
|
||||||
DataTypes::sender_id,
|
DataTypes::sender_id,
|
||||||
JsonValue::String(uid.to_string()),
|
JsonValue::String(uid.to_string()),
|
||||||
);
|
);
|
||||||
group.send_to(&receiver_id, &bc.to_json().to_string());
|
group
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.send_to(&receiver_id, &bc.to_json().to_string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -172,15 +168,14 @@ pub async fn handle_connection(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// on close / disconnection:
|
// on close / disconnection:
|
||||||
if let (Some(uid), Some(cid)) = (maybe_user_id, maybe_call_id) {
|
if let (Some(uid), Some(cid)) = (maybe_user_id, maybe_call_id) {
|
||||||
let mut st = state.lock().await;
|
let mut st = state.lock().await;
|
||||||
if let Some(group) = st.call_groups.get_mut(&cid) {
|
if let Some(group) = st.call_groups.get_mut(&cid) {
|
||||||
group.remove_member(&uid);
|
group.lock().await.remove_member(uid);
|
||||||
}
|
}
|
||||||
st.remove_inactive();
|
st.remove_inactive().await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,106 +1,47 @@
|
||||||
use std::{
|
use crate::calls::caller::Caller;
|
||||||
collections::{HashMap, HashSet},
|
use std::collections::HashMap;
|
||||||
sync::Arc,
|
|
||||||
};
|
|
||||||
use tokio::sync::mpsc::UnboundedSender;
|
use tokio::sync::mpsc::UnboundedSender;
|
||||||
|
|
||||||
use json::JsonValue;
|
|
||||||
use tungstenite::Utf8Bytes;
|
use tungstenite::Utf8Bytes;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::data::communication::{CommunicationType, CommunicationValue, DataTypes};
|
|
||||||
|
|
||||||
pub type Tx = UnboundedSender<Utf8Bytes>;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct CallGroup {
|
pub struct CallGroup {
|
||||||
pub call_id: Uuid,
|
pub call_id: Uuid,
|
||||||
secret: String,
|
|
||||||
pub callers: HashMap<Uuid, Caller>,
|
pub callers: HashMap<Uuid, Caller>,
|
||||||
pub inform_on_end: HashSet<Uuid>,
|
|
||||||
pub started_at: u64,
|
|
||||||
pub ended_at: Option<u64>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CallGroup {
|
impl CallGroup {
|
||||||
pub fn new(call_id: Uuid, secret: String) -> Self {
|
pub fn new(call_id: Uuid) -> Self {
|
||||||
CallGroup {
|
Self {
|
||||||
call_id,
|
call_id,
|
||||||
secret,
|
|
||||||
callers: HashMap::new(),
|
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) {
|
pub fn add_member(&mut self, user_id: Uuid, tx: UnboundedSender<Utf8Bytes>) {
|
||||||
// If already present, drop old
|
|
||||||
if let Some(old) = self.callers.remove(&user_id) {
|
|
||||||
// optionally notify or close old
|
|
||||||
// no direct close since we don’t 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 });
|
self.callers.insert(user_id, Caller { user_id, tx });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove_member(&mut self, user_id: &Uuid) {
|
pub fn remove_member(&mut self, user_id: Uuid) {
|
||||||
if self.callers.remove(user_id).is_some() {
|
self.callers.remove(&user_id);
|
||||||
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()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.callers.is_empty()
|
||||||
}
|
}
|
||||||
if self.callers.is_empty() {
|
|
||||||
self.ended_at = Some(chrono::Utc::now().timestamp_millis() as u64);
|
pub fn send_to(&self, user_id: &Uuid, message: &str) {
|
||||||
// Optionally notify inform_on_end
|
if let Some(caller) = self.callers.get(user_id) {
|
||||||
let end_msg = CommunicationValue::new(CommunicationType::end_call)
|
let _ = caller.send(Utf8Bytes::from(message.to_string()));
|
||||||
.add_data(
|
|
||||||
DataTypes::call_id,
|
|
||||||
JsonValue::String(self.call_id.to_string()),
|
|
||||||
)
|
|
||||||
.to_json()
|
|
||||||
.to_string();
|
|
||||||
for &uid in &self.inform_on_end {
|
|
||||||
// here you’d send via your Rho / other channel to user
|
|
||||||
// e.g. RhoManager::message_to(uid, end_msg.clone());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn broadcast(&self, msg: &str) {
|
pub fn broadcast(&self, message: &str) {
|
||||||
for c in self.callers.values() {
|
for caller in self.callers.values() {
|
||||||
let _ = c.tx.send(Utf8Bytes::from(msg.clone()));
|
let _ = caller.send(Utf8Bytes::from(message.to_string()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn send_to(&self, target: &Uuid, msg: &str) {
|
pub fn caller_state_mut(&mut self, user_id: &Uuid) -> Option<&mut Caller> {
|
||||||
if let Some(c) = self.callers.get(target) {
|
self.callers.get_mut(user_id)
|
||||||
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,
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,15 @@
|
||||||
use crate::calls::call_group::CallGroup;
|
use crate::calls::call_group::CallGroup;
|
||||||
use crate::data::communication::{CommunicationType, CommunicationValue, DataTypes};
|
use futures::lock::Mutex;
|
||||||
use futures::{SinkExt, StreamExt};
|
use std::collections::HashMap;
|
||||||
use json::JsonValue;
|
use std::sync::Arc;
|
||||||
use std::collections::{HashMap, HashSet};
|
use tokio::sync::mpsc::UnboundedSender;
|
||||||
use std::sync::{Arc, Mutex};
|
|
||||||
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
|
|
||||||
use tungstenite::Utf8Bytes;
|
use tungstenite::Utf8Bytes;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
use warp::Filter;
|
|
||||||
|
|
||||||
pub type Tx = UnboundedSender<Utf8Bytes>;
|
pub type Tx = UnboundedSender<Utf8Bytes>;
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct CallManagerState {
|
pub struct CallManagerState {
|
||||||
pub call_groups: HashMap<Uuid, Arc<CallGroup>>,
|
pub call_groups: HashMap<Uuid, Arc<Mutex<CallGroup>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CallManagerState {
|
impl CallManagerState {
|
||||||
|
|
@ -23,18 +19,27 @@ impl CallManagerState {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_or_create_group(&mut self, call_id: Uuid, secret: &str) -> Arc<CallGroup> {
|
pub fn get_or_create_group(&mut self, call_id: Uuid, secret: &str) -> Arc<Mutex<CallGroup>> {
|
||||||
let g = self.call_groups.get_mut(&call_id);
|
let g = self.call_groups.get_mut(&call_id);
|
||||||
if let Some(group) = g {
|
if let Some(group) = g {
|
||||||
group.clone()
|
group.clone()
|
||||||
} else {
|
} else {
|
||||||
let cg = Arc::new(CallGroup::new(call_id, secret.to_string()));
|
let cg = Arc::new(Mutex::new(CallGroup::new(call_id)));
|
||||||
self.call_groups.insert(call_id, cg);
|
self.call_groups.insert(call_id, cg);
|
||||||
self.call_groups.get(&call_id).unwrap().clone()
|
self.call_groups.get(&call_id).unwrap().clone()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove_inactive(&mut self) {
|
pub async fn remove_inactive(&mut self) {
|
||||||
self.call_groups.retain(|_k, v| v.callers.len() > 0);
|
let mut rem = Vec::new();
|
||||||
|
for cg in self.call_groups.keys() {
|
||||||
|
let group = self.call_groups.get(cg).unwrap().lock().await;
|
||||||
|
if group.callers.is_empty() {
|
||||||
|
rem.push(cg.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for cg in rem {
|
||||||
|
self.call_groups.remove(&cg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
14
src/calls/caller.rs
Normal file
14
src/calls/caller.rs
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
use tokio::sync::mpsc::UnboundedSender;
|
||||||
|
use tungstenite::Utf8Bytes;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Caller {
|
||||||
|
pub user_id: Uuid,
|
||||||
|
pub tx: UnboundedSender<Utf8Bytes>,
|
||||||
|
}
|
||||||
|
impl Caller {
|
||||||
|
pub fn send(&self, msg: impl Into<Utf8Bytes>) {
|
||||||
|
let _ = self.tx.send(msg.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
pub mod call_connection;
|
pub mod call_connection;
|
||||||
pub mod call_group;
|
pub mod call_group;
|
||||||
pub mod call_manager;
|
pub mod call_manager;
|
||||||
|
pub mod caller;
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,6 @@
|
||||||
use axum::Json;
|
|
||||||
use json::number::Number;
|
use json::number::Number;
|
||||||
use json::{Array, JsonValue, object, parse, stringify};
|
use json::{Array, JsonValue, object, parse};
|
||||||
use std::any::Any;
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::env::VarsOs;
|
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
@ -11,6 +8,7 @@ use uuid::Uuid;
|
||||||
#[derive(Eq, Hash, PartialEq, Clone, Debug)]
|
#[derive(Eq, Hash, PartialEq, Clone, Debug)]
|
||||||
pub enum DataTypes {
|
pub enum DataTypes {
|
||||||
error_type,
|
error_type,
|
||||||
|
accepted_ids,
|
||||||
uuid,
|
uuid,
|
||||||
chat_partner_id,
|
chat_partner_id,
|
||||||
iota_id,
|
iota_id,
|
||||||
|
|
@ -157,6 +155,9 @@ impl DataTypes {
|
||||||
#[derive(PartialEq, Clone, Debug)]
|
#[derive(PartialEq, Clone, Debug)]
|
||||||
pub enum CommunicationType {
|
pub enum CommunicationType {
|
||||||
error,
|
error,
|
||||||
|
error_invalid_user_id,
|
||||||
|
error_no_iota,
|
||||||
|
error_invalid_private_key,
|
||||||
success,
|
success,
|
||||||
message,
|
message,
|
||||||
message_send,
|
message_send,
|
||||||
|
|
@ -366,9 +367,9 @@ impl CommunicationValue {
|
||||||
pub fn ack_message(message_id: Uuid, sender: Uuid) -> CommunicationValue {
|
pub fn ack_message(message_id: Uuid, sender: Uuid) -> CommunicationValue {
|
||||||
let mut cv = CommunicationValue::new(CommunicationType::message).with_id(message_id);
|
let mut cv = CommunicationValue::new(CommunicationType::message).with_id(message_id);
|
||||||
|
|
||||||
if let s = sender {
|
let s = sender;
|
||||||
cv = cv.add_data(DataTypes::send_time, JsonValue::String(s.to_string()));
|
cv = cv.add_data(DataTypes::send_time, JsonValue::String(s.to_string()));
|
||||||
}
|
|
||||||
cv
|
cv
|
||||||
}
|
}
|
||||||
pub fn forward_to_other_iota(original: &mut CommunicationValue) -> CommunicationValue {
|
pub fn forward_to_other_iota(original: &mut CommunicationValue) -> CommunicationValue {
|
||||||
|
|
|
||||||
102
src/main.rs
102
src/main.rs
|
|
@ -5,19 +5,103 @@ mod omega;
|
||||||
mod rho;
|
mod rho;
|
||||||
mod util;
|
mod util;
|
||||||
|
|
||||||
use crate::rho::client_connection;
|
use futures::StreamExt;
|
||||||
use crate::rho::iota_connection;
|
use std::sync::Arc;
|
||||||
use crate::util::config_util::Config;
|
use tokio::net::TcpListener;
|
||||||
use crate::util::file_util;
|
use tokio_tungstenite::accept_hdr_async;
|
||||||
use tokio_websocket_server::socket::{WebSocketMessage, WebsocketServer};
|
use tungstenite::handshake::server::{Request, Response};
|
||||||
use tracing::info;
|
|
||||||
use tracing_subscriber::fmt;
|
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
omega::omega_connection::OmegaConnection,
|
||||||
|
rho::{client_connection::ClientConnection, iota_connection::IotaConnection},
|
||||||
|
};
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
fmt::init();
|
OmegaConnection::new().connect().await;
|
||||||
|
|
||||||
|
let listener = TcpListener::bind("0.0.0.0:959").await.unwrap();
|
||||||
|
println!("WebSocket server listening on 0.0.0.0:959");
|
||||||
|
|
||||||
|
while let Ok((stream, _)) = listener.accept().await {
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut path: String = "/".to_string();
|
||||||
|
let callback = |req: &Request, response: Response| {
|
||||||
|
path = format!("{}", &req.uri().path());
|
||||||
|
Ok(response)
|
||||||
|
};
|
||||||
|
let ws_stream = match accept_hdr_async(stream, callback).await {
|
||||||
|
Ok(ws) => ws,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("WebSocket upgrade failed: {}", e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
println!("New {} connection", path);
|
||||||
|
if path == "/ws/client/" {
|
||||||
|
let client_conn: Arc<ClientConnection> =
|
||||||
|
Arc::from(ClientConnection::new(ws_stream));
|
||||||
loop {
|
loop {
|
||||||
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
|
let msg_result = {
|
||||||
|
let mut session_lock = client_conn.session.lock().await;
|
||||||
|
session_lock.next().await
|
||||||
|
};
|
||||||
|
|
||||||
|
match msg_result {
|
||||||
|
Some(Ok(msg)) => {
|
||||||
|
if msg.is_text() {
|
||||||
|
let text = msg.into_text().unwrap();
|
||||||
|
client_conn.clone().handle_message(text).await;
|
||||||
|
} else if msg.is_close() {
|
||||||
|
println!("Client disconnected");
|
||||||
|
client_conn.handle_close().await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(Err(e)) => {
|
||||||
|
eprintln!("WebSocket error: {}", e);
|
||||||
|
client_conn.handle_close().await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
println!("Client stream ended");
|
||||||
|
client_conn.handle_close().await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if path == "/ws/iota/" {
|
||||||
|
let iota_conn: Arc<IotaConnection> = Arc::from(IotaConnection::new(ws_stream));
|
||||||
|
loop {
|
||||||
|
let msg_result = {
|
||||||
|
let mut session_lock = iota_conn.session.lock().await;
|
||||||
|
session_lock.next().await
|
||||||
|
};
|
||||||
|
|
||||||
|
match msg_result {
|
||||||
|
Some(Ok(msg)) => {
|
||||||
|
if msg.is_text() {
|
||||||
|
let text = msg.into_text().unwrap();
|
||||||
|
iota_conn.clone().handle_message(text).await;
|
||||||
|
} else if msg.is_close() {
|
||||||
|
println!("Iota disconnected");
|
||||||
|
iota_conn.handle_close().await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(Err(e)) => {
|
||||||
|
eprintln!("WebSocket error: {}", e);
|
||||||
|
iota_conn.handle_close().await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
// Stream ended
|
||||||
|
println!("Iota stream ended");
|
||||||
|
iota_conn.handle_close().await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,25 +1,21 @@
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use std::{collections::HashMap, net::TcpStream};
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
data::{
|
data::{
|
||||||
communication::DataTypes,
|
communication::DataTypes,
|
||||||
user::{User, UserStatus},
|
user::{User, UserStatus},
|
||||||
},
|
},
|
||||||
rho::{self, rho_manager},
|
rho::rho_manager,
|
||||||
util::config_util::CONFIG,
|
util::config_util::CONFIG,
|
||||||
};
|
};
|
||||||
use axum::Json;
|
|
||||||
use dashmap::DashMap;
|
use dashmap::DashMap;
|
||||||
use futures::{SinkExt, StreamExt};
|
use futures::{SinkExt, StreamExt};
|
||||||
use json::JsonValue;
|
use json::JsonValue;
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
use tokio::time::sleep;
|
use tokio::time::sleep;
|
||||||
use tokio_tungstenite::{
|
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};
|
||||||
MaybeTlsStream, WebSocketStream, connect_async, tungstenite::protocol::Message,
|
|
||||||
};
|
|
||||||
use tungstenite::Utf8Bytes;
|
use tungstenite::Utf8Bytes;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
|
@ -43,33 +39,26 @@ impl OmegaConnection {
|
||||||
self.connect_internal(0).await;
|
self.connect_internal(0).await;
|
||||||
}
|
}
|
||||||
async fn connect_internal(&self, mut retry: usize) {
|
async fn connect_internal(&self, mut retry: usize) {
|
||||||
let uri = "wss://tensamin.methanium.net/ws/omega/";
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
if retry > 20 {
|
if retry > 5 {
|
||||||
eprintln!("Max retry attempts reached, giving up.");
|
eprintln!("Max retry attempts reached, giving up.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
match connect_async(uri).await {
|
match connect_async("wss://tensamin.methanium.net/ws/omega").await {
|
||||||
Ok((ws_stream, _)) => {
|
Ok((_, _)) => {
|
||||||
let mut guard = Some(ws_stream);
|
retry = 0;
|
||||||
|
|
||||||
// Send IDENTIFICATION
|
|
||||||
let identify_msg = CommunicationValue::new(CommunicationType::identification)
|
let identify_msg = CommunicationValue::new(CommunicationType::identification)
|
||||||
.add_data(
|
.add_data(
|
||||||
DataTypes::uuid,
|
DataTypes::uuid,
|
||||||
JsonValue::String(CONFIG.read().unwrap().omikron_id.to_string()),
|
JsonValue::String(CONFIG.lock().await.omikron_id.to_string()),
|
||||||
);
|
);
|
||||||
self.send_message(&identify_msg).await;
|
self.send_message(&identify_msg).await;
|
||||||
|
|
||||||
// Spawn reader loop
|
|
||||||
let ws_stream_clone = self.ws_stream.clone();
|
let ws_stream_clone = self.ws_stream.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
OmegaConnection::read_loop(ws_stream_clone).await;
|
OmegaConnection::read_loop(ws_stream_clone).await;
|
||||||
});
|
});
|
||||||
|
|
||||||
break; // success, exit the loop
|
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("WebSocket connection failed (attempt {}): {}", retry, e);
|
eprintln!("WebSocket connection failed (attempt {}): {}", retry, e);
|
||||||
|
|
@ -92,7 +81,7 @@ impl OmegaConnection {
|
||||||
|
|
||||||
match ws.next().await {
|
match ws.next().await {
|
||||||
Some(Ok(Message::Text(msg))) => {
|
Some(Ok(Message::Text(msg))) => {
|
||||||
let mut cv = CommunicationValue::from_json(&msg);
|
let cv = CommunicationValue::from_json(&msg);
|
||||||
let msg_id = cv.get_id();
|
let msg_id = cv.get_id();
|
||||||
|
|
||||||
// Handle waiting tasks
|
// Handle waiting tasks
|
||||||
|
|
@ -122,16 +111,14 @@ impl OmegaConnection {
|
||||||
|
|
||||||
let user = User::new(iota_id, user_id, status);
|
let user = User::new(iota_id, user_id, status);
|
||||||
for rho_con in rho_manager::get_all_connections().await {
|
for rho_con in rho_manager::get_all_connections().await {
|
||||||
rho_con.are_they_interested(&user);
|
rho_con.are_they_interested(&user).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(Ok(Message::Close(_))) | None => {
|
Some(Ok(Message::Close(_))) | None => {
|
||||||
OmegaConnection::reconnect();
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
Some(Err(_)) => {
|
Some(Err(_)) => {
|
||||||
OmegaConnection::reconnect();
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
|
|
@ -139,11 +126,6 @@ impl OmegaConnection {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn reconnect() {
|
|
||||||
let conn = OmegaConnection::new();
|
|
||||||
conn.connect().await;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn send_message(&self, cv: &CommunicationValue) {
|
pub async fn send_message(&self, cv: &CommunicationValue) {
|
||||||
let mut guard = self.ws_stream.lock().await;
|
let mut guard = self.ws_stream.lock().await;
|
||||||
if let Some(ws) = guard.as_mut() {
|
if let Some(ws) = guard.as_mut() {
|
||||||
|
|
@ -192,7 +174,7 @@ impl OmegaConnection {
|
||||||
WAITING_TASKS.insert(
|
WAITING_TASKS.insert(
|
||||||
msg_id,
|
msg_id,
|
||||||
Box::new(move |response: CommunicationValue| {
|
Box::new(move |response: CommunicationValue| {
|
||||||
Box::pin(async move |response2: CommunicationValue| {
|
let _ = Box::pin(async move |_: CommunicationValue| {
|
||||||
let rho = rho_manager::get_rho_con_for_user(user_id).await;
|
let rho = rho_manager::get_rho_con_for_user(user_id).await;
|
||||||
if let Some(rho) = rho {
|
if let Some(rho) = rho {
|
||||||
for client in rho.get_client_connections_for_user(user_id).await {
|
for client in rho.get_client_connections_for_user(user_id).await {
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,7 @@
|
||||||
use futures::SinkExt;
|
use futures::SinkExt;
|
||||||
use http::header::AUTHORIZATION;
|
use std::sync::{Arc, Weak};
|
||||||
use std::{
|
use tokio::sync::Mutex;
|
||||||
collections::HashMap,
|
use tokio::sync::RwLock;
|
||||||
sync::{Arc, Weak},
|
|
||||||
};
|
|
||||||
use tokio::sync::{Mutex, RwLock};
|
|
||||||
use tokio_tungstenite::{WebSocketStream, tungstenite::Message};
|
use tokio_tungstenite::{WebSocketStream, tungstenite::Message};
|
||||||
use tungstenite::Utf8Bytes;
|
use tungstenite::Utf8Bytes;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
@ -23,17 +20,17 @@ use crate::{
|
||||||
/// ClientConnection represents a WebSocket connection from a client device
|
/// ClientConnection represents a WebSocket connection from a client device
|
||||||
pub struct ClientConnection {
|
pub struct ClientConnection {
|
||||||
/// WebSocket session
|
/// WebSocket session
|
||||||
session: Arc<Mutex<WebSocketStream<tokio::net::TcpStream>>>,
|
pub session: Arc<Mutex<WebSocketStream<tokio::net::TcpStream>>>,
|
||||||
/// User ID associated with this client
|
/// User ID associated with this client
|
||||||
user_id: Arc<RwLock<Option<Uuid>>>,
|
pub user_id: Arc<RwLock<Option<Uuid>>>,
|
||||||
/// Whether this connection has been identified/authenticated
|
/// Whether this connection has been identified/authenticated
|
||||||
identified: Arc<RwLock<bool>>,
|
pub identified: Arc<RwLock<bool>>,
|
||||||
/// Ping latency tracking
|
/// Ping latency tracking
|
||||||
ping: Arc<RwLock<i64>>,
|
pub ping: Arc<RwLock<i64>>,
|
||||||
/// Weak reference to RhoConnection to avoid circular references
|
/// Weak reference to RhoConnection to avoid circular references
|
||||||
rho_connection: Arc<RwLock<Option<Weak<RhoConnection>>>>,
|
pub rho_connection: Arc<RwLock<Option<Weak<RhoConnection>>>>,
|
||||||
/// List of user IDs this client is interested in receiving updates about
|
/// List of user IDs this client is interested in receiving updates about
|
||||||
interested_users: Arc<RwLock<Vec<Uuid>>>,
|
pub interested_users: Arc<RwLock<Vec<Uuid>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ClientConnection {
|
impl ClientConnection {
|
||||||
|
|
@ -97,7 +94,7 @@ impl ClientConnection {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle incoming message from client
|
/// Handle incoming message from client
|
||||||
pub async fn handle_message(self: Arc<Self>, message: String) {
|
pub async fn handle_message(self: Arc<Self>, message: Utf8Bytes) {
|
||||||
let cv = CommunicationValue::from_json(&message);
|
let cv = CommunicationValue::from_json(&message);
|
||||||
|
|
||||||
// Handle identification
|
// Handle identification
|
||||||
|
|
@ -145,23 +142,16 @@ impl ClientConnection {
|
||||||
Some(id_str) => match Uuid::parse_str(&id_str.to_string()) {
|
Some(id_str) => match Uuid::parse_str(&id_str.to_string()) {
|
||||||
Ok(id) => id,
|
Ok(id) => id,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
self.send_error_response(&cv.get_id(), CommunicationType::error)
|
self.send_error_response(
|
||||||
|
&cv.get_id(),
|
||||||
|
CommunicationType::error_invalid_user_id,
|
||||||
|
)
|
||||||
.await;
|
.await;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
None => {
|
None => {
|
||||||
self.send_error_response(&cv.get_id(), CommunicationType::error)
|
self.send_error_response(&cv.get_id(), CommunicationType::error_invalid_user_id)
|
||||||
.await;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Find RhoConnection for this user
|
|
||||||
let rho_connection = match rho_manager::get_rho_con_for_user(user_id).await {
|
|
||||||
Some(rho) => rho,
|
|
||||||
None => {
|
|
||||||
self.send_error_response(&cv.get_id(), CommunicationType::error)
|
|
||||||
.await;
|
.await;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -169,20 +159,36 @@ impl ClientConnection {
|
||||||
|
|
||||||
// Validate private key
|
// Validate private key
|
||||||
if let Some(private_key_hash) = cv.get_data(DataTypes::private_key_hash) {
|
if let Some(private_key_hash) = cv.get_data(DataTypes::private_key_hash) {
|
||||||
|
println!("private_key_hash: {}", private_key_hash);
|
||||||
let is_valid =
|
let is_valid =
|
||||||
auth_connector::is_private_key_valid(user_id, &private_key_hash.to_string()).await;
|
auth_connector::is_private_key_valid(user_id, &private_key_hash.to_string()).await;
|
||||||
|
|
||||||
if !is_valid {
|
if !is_valid {
|
||||||
self.send_error_response(&cv.get_id(), CommunicationType::error)
|
println!("Invalid private key");
|
||||||
|
self.send_error_response(
|
||||||
|
&cv.get_id(),
|
||||||
|
CommunicationType::error_invalid_private_key,
|
||||||
|
)
|
||||||
.await;
|
.await;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
self.send_error_response(&cv.get_id(), CommunicationType::error)
|
println!("Missing private key");
|
||||||
|
self.send_error_response(&cv.get_id(), CommunicationType::error_invalid_private_key)
|
||||||
.await;
|
.await;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Find RhoConnection for this user
|
||||||
|
let rho_connection = match rho_manager::get_rho_con_for_user(user_id).await {
|
||||||
|
Some(rho) => rho,
|
||||||
|
None => {
|
||||||
|
self.send_error_response(&cv.get_id(), CommunicationType::error_no_iota)
|
||||||
|
.await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Set identification data
|
// Set identification data
|
||||||
{
|
{
|
||||||
let mut user_id_guard = self.user_id.write().await;
|
let mut user_id_guard = self.user_id.write().await;
|
||||||
|
|
@ -193,14 +199,11 @@ impl ClientConnection {
|
||||||
*identified_guard = true;
|
*identified_guard = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set up RhoConnection reference
|
|
||||||
self.set_rho_connection(Arc::downgrade(&rho_connection))
|
self.set_rho_connection(Arc::downgrade(&rho_connection))
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
// Add this client to the RhoConnection
|
|
||||||
rho_connection.add_client_connection(Arc::from(sarc)).await;
|
rho_connection.add_client_connection(Arc::from(sarc)).await;
|
||||||
|
|
||||||
// Send success response
|
|
||||||
let response = CommunicationValue::new(CommunicationType::identification_response)
|
let response = CommunicationValue::new(CommunicationType::identification_response)
|
||||||
.with_id(cv.get_id());
|
.with_id(cv.get_id());
|
||||||
self.send_message(&response).await;
|
self.send_message(&response).await;
|
||||||
|
|
@ -242,14 +245,15 @@ impl ClientConnection {
|
||||||
rho_conn.get_iota_id().await,
|
rho_conn.get_iota_id().await,
|
||||||
user_id,
|
user_id,
|
||||||
user_status,
|
user_status,
|
||||||
);
|
)
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle call invite
|
/// Handle call invite
|
||||||
async fn handle_call_invite(&self, mut cv: CommunicationValue) {
|
async fn handle_call_invite(&self, cv: CommunicationValue) {
|
||||||
let receiver_id = match cv.get_data(DataTypes::receiver_id) {
|
let receiver_id = match cv.get_data(DataTypes::receiver_id) {
|
||||||
Some(id_str) => match Uuid::parse_str(&id_str.to_string()) {
|
Some(id_str) => match Uuid::parse_str(&id_str.to_string()) {
|
||||||
Ok(id) => id,
|
Ok(id) => id,
|
||||||
|
|
@ -470,46 +474,3 @@ impl std::fmt::Debug for ClientConnection {
|
||||||
.finish()
|
.finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use tokio::sync::Mutex;
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn test_client_connection_creation() {
|
|
||||||
// Mock session - in real implementation this would be a proper WebSocket stream
|
|
||||||
let mock_session = tokio_tungstenite::WebSocketStream::from_raw_socket(
|
|
||||||
tokio::net::TcpStream::connect("127.0.0.1:0")
|
|
||||||
.await
|
|
||||||
.unwrap_or_else(|_| {
|
|
||||||
// This is just for testing, create a dummy stream
|
|
||||||
panic!("Cannot create test stream")
|
|
||||||
}),
|
|
||||||
tokio_tungstenite::tungstenite::protocol::Role::Client,
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
// This test would fail in practice due to the mock stream
|
|
||||||
// but shows the intended API
|
|
||||||
// let client_conn = ClientConnection::new(mock_session);
|
|
||||||
|
|
||||||
// assert!(!client_conn.is_identified().await);
|
|
||||||
// assert_eq!(client_conn.get_ping().await, -1);
|
|
||||||
// assert!(client_conn.get_user_id().await.is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn test_interested_users() {
|
|
||||||
// This would also need a proper mock setup
|
|
||||||
// but shows the intended functionality
|
|
||||||
|
|
||||||
// let client_conn = ClientConnection::new(mock_session);
|
|
||||||
// let user_ids = vec![Uuid::new_v4(), Uuid::new_v4()];
|
|
||||||
|
|
||||||
// client_conn.set_interested_users(user_ids.clone()).await;
|
|
||||||
//
|
|
||||||
// // Test would verify that the interested users are stored correctly
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
use futures::SinkExt;
|
use futures::SinkExt;
|
||||||
use json::{JsonValue, number::Number};
|
use json::JsonValue;
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
sync::{Arc, Weak},
|
sync::{Arc, Weak},
|
||||||
|
|
@ -13,21 +13,18 @@ use super::{rho_connection::RhoConnection, rho_manager};
|
||||||
use crate::{
|
use crate::{
|
||||||
auth::auth_connector,
|
auth::auth_connector,
|
||||||
// calls::call_manager::CallManager,
|
// calls::call_manager::CallManager,
|
||||||
data::{
|
data::communication::{CommunicationType, CommunicationValue, DataTypes},
|
||||||
communication::{CommunicationType, CommunicationValue, DataTypes},
|
|
||||||
user::User,
|
|
||||||
},
|
|
||||||
omega::omega_connection::OmegaConnection,
|
omega::omega_connection::OmegaConnection,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// IotaConnection represents a WebSocket connection from an Iota device
|
/// IotaConnection represents a WebSocket connection from an Iota device
|
||||||
pub struct IotaConnection {
|
pub struct IotaConnection {
|
||||||
session: Arc<Mutex<WebSocketStream<tokio::net::TcpStream>>>,
|
pub session: Arc<Mutex<WebSocketStream<tokio::net::TcpStream>>>,
|
||||||
iota_id: Arc<RwLock<Uuid>>,
|
pub iota_id: Arc<RwLock<Uuid>>,
|
||||||
user_ids: Arc<RwLock<Vec<Uuid>>>,
|
pub user_ids: Arc<RwLock<Vec<Uuid>>>,
|
||||||
identified: Arc<RwLock<bool>>,
|
pub identified: Arc<RwLock<bool>>,
|
||||||
ping: Arc<RwLock<i64>>,
|
pub ping: Arc<RwLock<i64>>,
|
||||||
rho_connection: Arc<RwLock<Option<Weak<RhoConnection>>>>,
|
pub rho_connection: Arc<RwLock<Option<Weak<RhoConnection>>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IotaConnection {
|
impl IotaConnection {
|
||||||
|
|
@ -43,22 +40,6 @@ impl IotaConnection {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create with known IDs (for testing)
|
|
||||||
pub fn new_with_ids(
|
|
||||||
iota_id: Uuid,
|
|
||||||
user_ids: Vec<Uuid>,
|
|
||||||
session: Arc<Mutex<WebSocketStream<tokio::net::TcpStream>>>,
|
|
||||||
) -> Arc<Self> {
|
|
||||||
Arc::new(Self {
|
|
||||||
session,
|
|
||||||
iota_id: Arc::new(RwLock::new(iota_id)),
|
|
||||||
user_ids: Arc::new(RwLock::new(user_ids)),
|
|
||||||
identified: Arc::new(RwLock::new(true)),
|
|
||||||
ping: Arc::new(RwLock::new(0)),
|
|
||||||
rho_connection: Arc::new(RwLock::new(None)),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the Iota ID
|
/// Get the Iota ID
|
||||||
pub async fn get_iota_id(&self) -> Uuid {
|
pub async fn get_iota_id(&self) -> Uuid {
|
||||||
*self.iota_id.read().await
|
*self.iota_id.read().await
|
||||||
|
|
@ -98,18 +79,24 @@ impl IotaConnection {
|
||||||
/// Send a message to the Iota
|
/// Send a message to the Iota
|
||||||
pub async fn send_message_str(&self, message: &str) {
|
pub async fn send_message_str(&self, message: &str) {
|
||||||
let mut session = self.session.lock().await;
|
let mut session = self.session.lock().await;
|
||||||
let _ = session
|
if let Err(e) = session
|
||||||
.send(Message::Text(Utf8Bytes::from(message.to_string())))
|
.send(Message::Text(Utf8Bytes::from(message.to_string())))
|
||||||
.await;
|
.await
|
||||||
|
{
|
||||||
|
eprintln!("Failed to send WebSocket message: {:?}", e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send a CommunicationValue to the Iota
|
/// Send a CommunicationValue to the Iota
|
||||||
pub async fn send_message(&self, cv: CommunicationValue) {
|
pub async fn send_message(&self, cv: CommunicationValue) {
|
||||||
|
if !cv.is_type(CommunicationType::pong) {
|
||||||
|
println!("{}", cv.to_json().to_string());
|
||||||
|
}
|
||||||
self.send_message_str(&cv.to_json().to_string()).await;
|
self.send_message_str(&cv.to_json().to_string()).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle incoming message from Iota
|
/// Handle incoming message from Iota
|
||||||
pub async fn handle_message(self: Arc<Self>, message: String) {
|
pub async fn handle_message(self: Arc<Self>, message: Utf8Bytes) {
|
||||||
let cv = CommunicationValue::from_json(&message);
|
let cv = CommunicationValue::from_json(&message);
|
||||||
|
|
||||||
// Handle identification
|
// Handle identification
|
||||||
|
|
@ -149,7 +136,7 @@ impl IotaConnection {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle identification message
|
/// Handle identification message
|
||||||
async fn handle_identification(self: Arc<Self>, mut cv: CommunicationValue) {
|
async fn handle_identification(self: Arc<Self>, cv: CommunicationValue) {
|
||||||
// Parse Iota ID
|
// Parse Iota ID
|
||||||
let iota_id = match cv.get_data(DataTypes::iota_id) {
|
let iota_id = match cv.get_data(DataTypes::iota_id) {
|
||||||
Some(id_str) => match Uuid::parse_str(&id_str.to_string()) {
|
Some(id_str) => match Uuid::parse_str(&id_str.to_string()) {
|
||||||
|
|
@ -166,20 +153,21 @@ impl IotaConnection {
|
||||||
};
|
};
|
||||||
|
|
||||||
// Parse user IDs
|
// Parse user IDs
|
||||||
let mut validated_user_ids = Vec::new();
|
let mut validated_user_ids: Vec<Uuid> = Vec::new();
|
||||||
if let Some(user_ids_str) = cv.get_data(DataTypes::user_ids) {
|
if let Some(user_ids_str) = cv.get_data(DataTypes::user_ids) {
|
||||||
for id_str in user_ids_str.to_string().split(',') {
|
for id_str in user_ids_str.to_string().split(',') {
|
||||||
if id_str.is_empty() {
|
if id_str.is_empty() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if let Ok(user_id) = Uuid::parse_str(id_str.trim()) {
|
if let Ok(user_id) = Uuid::parse_str(id_str.trim()) {
|
||||||
let auth_iota_id = auth_connector::get_iota_id(user_id).await.unwrap();
|
if let Some(auth_iota_id) = auth_connector::get_iota_id(user_id).await {
|
||||||
if auth_iota_id == iota_id {
|
if auth_iota_id == iota_id {
|
||||||
validated_user_ids.push(user_id);
|
validated_user_ids.push(user_id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Set identification data
|
// Set identification data
|
||||||
{
|
{
|
||||||
|
|
@ -214,16 +202,20 @@ impl IotaConnection {
|
||||||
rho_manager::add_rho(rho_connection).await;
|
rho_manager::add_rho(rho_connection).await;
|
||||||
|
|
||||||
// Send response
|
// Send response
|
||||||
|
let mut str = String::new();
|
||||||
|
for id in &validated_user_ids {
|
||||||
|
str.push_str(&format!(",{}", id));
|
||||||
|
}
|
||||||
let response = CommunicationValue::new(CommunicationType::identification_response)
|
let response = CommunicationValue::new(CommunicationType::identification_response)
|
||||||
.with_id(cv.get_id())
|
.with_id(cv.get_id())
|
||||||
|
.add_data_str(DataTypes::accepted_ids, str)
|
||||||
.add_data_str(DataTypes::accepted, validated_user_ids.len().to_string());
|
.add_data_str(DataTypes::accepted, validated_user_ids.len().to_string());
|
||||||
|
|
||||||
self.send_message(response).await;
|
self.send_message(response).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle ping message
|
/// Handle ping message
|
||||||
async fn handle_ping(&self, mut cv: CommunicationValue) {
|
async fn handle_ping(&self, cv: CommunicationValue) {
|
||||||
// Update our ping if provided
|
|
||||||
if let Some(last_ping) = cv.get_data(DataTypes::last_ping) {
|
if let Some(last_ping) = cv.get_data(DataTypes::last_ping) {
|
||||||
if let Ok(ping_val) = last_ping.to_string().parse::<i64>() {
|
if let Ok(ping_val) = last_ping.to_string().parse::<i64>() {
|
||||||
let mut ping_guard = self.ping.write().await;
|
let mut ping_guard = self.ping.write().await;
|
||||||
|
|
@ -231,14 +223,12 @@ impl IotaConnection {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Collect client pings
|
|
||||||
let client_pings = if let Some(rho_conn) = self.get_rho_connection().await {
|
let client_pings = if let Some(rho_conn) = self.get_rho_connection().await {
|
||||||
rho_conn.get_client_pings().await
|
rho_conn.get_client_pings().await
|
||||||
} else {
|
} else {
|
||||||
HashMap::new()
|
HashMap::new()
|
||||||
};
|
};
|
||||||
|
|
||||||
// Send pong response
|
|
||||||
let pings = client_pings
|
let pings = client_pings
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(k, v)| (k, JsonValue::String(v.to_string())))
|
.map(|(k, v)| (k, JsonValue::String(v.to_string())))
|
||||||
|
|
@ -252,18 +242,15 @@ impl IotaConnection {
|
||||||
/// Handle message forwarding to other Iotas
|
/// Handle message forwarding to other Iotas
|
||||||
async fn handle_forward_message(&self, cv: CommunicationValue) {
|
async fn handle_forward_message(&self, cv: CommunicationValue) {
|
||||||
let receiver_id = cv.get_receiver();
|
let receiver_id = cv.get_receiver();
|
||||||
// Validate sender if present
|
|
||||||
let sender_id = cv.get_sender();
|
let sender_id = cv.get_sender();
|
||||||
if !self.get_user_ids().await.contains(&sender_id) {
|
if !self.get_user_ids().await.contains(&sender_id) {
|
||||||
self.send_error_response(&cv.get_id()).await;
|
self.send_error_response(&cv.get_id()).await;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find target RhoConnection
|
|
||||||
if let Some(target_rho) = rho_manager::get_rho_con_for_user(receiver_id).await {
|
if let Some(target_rho) = rho_manager::get_rho_con_for_user(receiver_id).await {
|
||||||
target_rho.message_to_iota(cv).await;
|
target_rho.message_to_iota(cv).await;
|
||||||
} else {
|
} else {
|
||||||
// Send error if target not found
|
|
||||||
let error = CommunicationValue::new(CommunicationType::error)
|
let error = CommunicationValue::new(CommunicationType::error)
|
||||||
.with_id(cv.get_id())
|
.with_id(cv.get_id())
|
||||||
.with_sender(cv.get_sender());
|
.with_sender(cv.get_sender());
|
||||||
|
|
@ -298,7 +285,7 @@ impl IotaConnection {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Notify OmegaConnection about user states
|
// Notify OmegaConnection about user states
|
||||||
OmegaConnection::user_states(receiver_id, interested_ids.clone());
|
OmegaConnection::user_states(receiver_id, interested_ids.clone()).await;
|
||||||
|
|
||||||
// Set interested users in RhoConnection
|
// Set interested users in RhoConnection
|
||||||
if let Some(rho_conn) = self.get_rho_connection().await {
|
if let Some(rho_conn) = self.get_rho_connection().await {
|
||||||
|
|
@ -318,13 +305,11 @@ impl IotaConnection {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send error response
|
|
||||||
async fn send_error_response(&self, message_id: &Uuid) {
|
async fn send_error_response(&self, message_id: &Uuid) {
|
||||||
let error = CommunicationValue::new(CommunicationType::error).with_id(*message_id);
|
let error = CommunicationValue::new(CommunicationType::error).with_id(*message_id);
|
||||||
self.send_message(error).await;
|
self.send_message(error).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle connection close
|
|
||||||
pub async fn handle_close(&self) {
|
pub async fn handle_close(&self) {
|
||||||
if self.is_identified().await {
|
if self.is_identified().await {
|
||||||
if let Some(rho_conn) = self.get_rho_connection().await {
|
if let Some(rho_conn) = self.get_rho_connection().await {
|
||||||
|
|
|
||||||
|
|
@ -1,21 +1,4 @@
|
||||||
//! Rho module - Connection management between Iota and Client connections
|
|
||||||
//!
|
|
||||||
//! This module implements the Rho connection management system that maps
|
|
||||||
//! single Iota connections to multiple Client connections, providing
|
|
||||||
//! bidirectional communication capabilities.
|
|
||||||
|
|
||||||
pub mod client_connection;
|
pub mod client_connection;
|
||||||
pub mod iota_connection;
|
pub mod iota_connection;
|
||||||
pub mod rho_connection;
|
pub mod rho_connection;
|
||||||
pub mod rho_manager;
|
pub mod rho_manager;
|
||||||
|
|
||||||
// Re-export commonly used types for convenience
|
|
||||||
pub use client_connection::ClientConnection;
|
|
||||||
pub use iota_connection::IotaConnection;
|
|
||||||
pub use rho_connection::RhoConnection;
|
|
||||||
|
|
||||||
// Re-export key manager functions
|
|
||||||
pub use rho_manager::{
|
|
||||||
add_rho, connection_count, contains_iota, get_all_connections, get_rho_by_iota,
|
|
||||||
get_rho_con_for_user, remove_rho,
|
|
||||||
};
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
use std::collections::{self, HashMap};
|
use std::collections::HashMap;
|
||||||
use std::sync::{Arc, Weak};
|
use std::sync::Arc;
|
||||||
use tokio::sync::RwLock;
|
use tokio::sync::RwLock;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
|
@ -26,27 +26,23 @@ impl RhoConnection {
|
||||||
};
|
};
|
||||||
|
|
||||||
// Notify OmegaConnection about the new Iota
|
// Notify OmegaConnection about the new Iota
|
||||||
OmegaConnection::connect_iota(rho_connection.get_iota_id().await, user_ids);
|
OmegaConnection::connect_iota(rho_connection.get_iota_id().await, user_ids).await;
|
||||||
|
|
||||||
rho_connection
|
rho_connection
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the Iota ID
|
|
||||||
pub async fn get_iota_id(&self) -> Uuid {
|
pub async fn get_iota_id(&self) -> Uuid {
|
||||||
self.iota_connection.get_iota_id().await
|
self.iota_connection.get_iota_id().await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the user IDs associated with this Rho connection
|
|
||||||
pub fn get_user_ids(&self) -> &Vec<Uuid> {
|
pub fn get_user_ids(&self) -> &Vec<Uuid> {
|
||||||
&self.user_ids
|
&self.user_ids
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get reference to the IotaConnection
|
|
||||||
pub fn get_iota_connection(&self) -> &Arc<IotaConnection> {
|
pub fn get_iota_connection(&self) -> &Arc<IotaConnection> {
|
||||||
&self.iota_connection
|
&self.iota_connection
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get all client connections
|
|
||||||
pub async fn get_client_connections(&self) -> Vec<Arc<ClientConnection>> {
|
pub async fn get_client_connections(&self) -> Vec<Arc<ClientConnection>> {
|
||||||
let connections = self.client_connections.read().await;
|
let connections = self.client_connections.read().await;
|
||||||
connections.clone()
|
connections.clone()
|
||||||
|
|
@ -69,7 +65,6 @@ impl RhoConnection {
|
||||||
|
|
||||||
/// Add a client connection
|
/// Add a client connection
|
||||||
pub async fn add_client_connection(&self, connection: Arc<ClientConnection>) {
|
pub async fn add_client_connection(&self, connection: Arc<ClientConnection>) {
|
||||||
// Notify Iota about new client
|
|
||||||
let notification = CommunicationValue::new(CommunicationType::client_connected)
|
let notification = CommunicationValue::new(CommunicationType::client_connected)
|
||||||
.add_data_str(
|
.add_data_str(
|
||||||
DataTypes::user_id,
|
DataTypes::user_id,
|
||||||
|
|
@ -82,18 +77,17 @@ impl RhoConnection {
|
||||||
|
|
||||||
self.iota_connection.send_message(notification).await;
|
self.iota_connection.send_message(notification).await;
|
||||||
|
|
||||||
// Add to our list
|
|
||||||
{
|
{
|
||||||
let mut connections = self.client_connections.write().await;
|
let mut connections = self.client_connections.write().await;
|
||||||
connections.push(Arc::clone(&connection));
|
connections.push(Arc::clone(&connection));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Notify OmegaConnection
|
|
||||||
OmegaConnection::client_changed(
|
OmegaConnection::client_changed(
|
||||||
self.get_iota_id().await,
|
self.get_iota_id().await,
|
||||||
connection.get_user_id().await.unwrap_or(Uuid::nil()),
|
connection.get_user_id().await.unwrap_or(Uuid::nil()),
|
||||||
UserStatus::online,
|
UserStatus::online,
|
||||||
);
|
)
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remove a client connection
|
/// Remove a client connection
|
||||||
|
|
@ -109,7 +103,6 @@ impl RhoConnection {
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
// Push the new connection
|
|
||||||
connections.push(Arc::clone(&connection));
|
connections.push(Arc::clone(&connection));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -118,7 +111,8 @@ impl RhoConnection {
|
||||||
self.get_iota_id().await,
|
self.get_iota_id().await,
|
||||||
connection.get_user_id().await.unwrap_or(Uuid::nil()),
|
connection.get_user_id().await.unwrap_or(Uuid::nil()),
|
||||||
UserStatus::user_offline,
|
UserStatus::user_offline,
|
||||||
);
|
)
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Close the Iota connection and all associated client connections
|
/// Close the Iota connection and all associated client connections
|
||||||
|
|
@ -133,7 +127,7 @@ impl RhoConnection {
|
||||||
rho_manager::remove_rho(self.get_iota_id().await).await;
|
rho_manager::remove_rho(self.get_iota_id().await).await;
|
||||||
|
|
||||||
// Notify OmegaConnection
|
// Notify OmegaConnection
|
||||||
OmegaConnection::close_iota(self.get_iota_id().await);
|
OmegaConnection::close_iota(self.get_iota_id().await).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send message from Iota to specific client by user ID
|
/// Send message from Iota to specific client by user ID
|
||||||
|
|
@ -220,32 +214,3 @@ impl RhoConnection {
|
||||||
connections.len()
|
connections.len()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use tokio::sync::Mutex;
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn test_rho_connection_creation() {
|
|
||||||
let iota_id = Uuid::new_v4();
|
|
||||||
let user_ids = vec![Uuid::new_v4(), Uuid::new_v4()];
|
|
||||||
|
|
||||||
// Mock session
|
|
||||||
// Create a mock WebSocket stream (this would fail in practice but shows the API)
|
|
||||||
// In real implementation, this would be a proper WebSocketStream
|
|
||||||
let mock_stream =
|
|
||||||
std::ptr::null_mut() as *mut tokio_tungstenite::WebSocketStream<tokio::net::TcpStream>;
|
|
||||||
let mock_stream = unsafe { std::ptr::read(mock_stream) };
|
|
||||||
let iota_conn = IotaConnection::new_with_ids(
|
|
||||||
iota_id,
|
|
||||||
user_ids.clone(),
|
|
||||||
Arc::new(tokio::sync::Mutex::new(mock_stream)),
|
|
||||||
);
|
|
||||||
|
|
||||||
let rho_conn = RhoConnection::new(iota_conn, user_ids.clone()).await;
|
|
||||||
|
|
||||||
assert_eq!(rho_conn.get_iota_id().await, iota_id);
|
|
||||||
assert_eq!(rho_conn.get_user_ids(), &user_ids);
|
|
||||||
assert_eq!(rho_conn.client_count().await, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -7,14 +7,17 @@ use uuid::Uuid;
|
||||||
|
|
||||||
use super::rho_connection::RhoConnection;
|
use super::rho_connection::RhoConnection;
|
||||||
|
|
||||||
// Static storage for RhoConnections, keyed by Iota ID
|
|
||||||
pub static RHO_CONNECTIONS: LazyLock<Arc<RwLock<HashMap<Uuid, Arc<RhoConnection>>>>> =
|
pub static RHO_CONNECTIONS: LazyLock<Arc<RwLock<HashMap<Uuid, Arc<RhoConnection>>>>> =
|
||||||
LazyLock::new(|| Arc::new(RwLock::new(HashMap::new())));
|
LazyLock::new(|| Arc::new(RwLock::new(HashMap::new())));
|
||||||
|
|
||||||
/// Get a RhoConnection for a specific user ID
|
|
||||||
pub async fn get_rho_con_for_user(user_id: Uuid) -> Option<Arc<RhoConnection>> {
|
pub async fn get_rho_con_for_user(user_id: Uuid) -> Option<Arc<RhoConnection>> {
|
||||||
let connections = RHO_CONNECTIONS.read().await;
|
let connections = RHO_CONNECTIONS.read().await;
|
||||||
|
println!("Checking user ID: {:?}", user_id);
|
||||||
for rho_connection in connections.values() {
|
for rho_connection in connections.values() {
|
||||||
|
println!(
|
||||||
|
"Comparing user IDs: {:?}",
|
||||||
|
rho_connection.get_user_ids().to_vec()
|
||||||
|
);
|
||||||
if rho_connection.get_user_ids().contains(&user_id) {
|
if rho_connection.get_user_ids().contains(&user_id) {
|
||||||
return Some(Arc::clone(rho_connection));
|
return Some(Arc::clone(rho_connection));
|
||||||
}
|
}
|
||||||
|
|
@ -22,7 +25,6 @@ pub async fn get_rho_con_for_user(user_id: Uuid) -> Option<Arc<RhoConnection>> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check if an Iota ID exists in the connections
|
|
||||||
pub async fn contains_iota(iota_id: Uuid) -> bool {
|
pub async fn contains_iota(iota_id: Uuid) -> bool {
|
||||||
let connections = RHO_CONNECTIONS.read().await;
|
let connections = RHO_CONNECTIONS.read().await;
|
||||||
connections.contains_key(&iota_id)
|
connections.contains_key(&iota_id)
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,9 @@
|
||||||
use crate::util::file_util::load_file;
|
use crate::util::file_util::load_file;
|
||||||
use json::JsonValue;
|
use futures::lock::Mutex;
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::sync::RwLock;
|
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
const CONFIG_PATH: &str = "";
|
|
||||||
const CONFIG_FILENAME: &str = "config.json";
|
|
||||||
|
|
||||||
// Define the Config structure
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
pub omega_server: String,
|
pub omega_server: String,
|
||||||
|
|
@ -19,13 +15,12 @@ pub struct Config {
|
||||||
pub port: u16,
|
pub port: u16,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Provide default values (similar to Java static defaults)
|
|
||||||
impl Default for Config {
|
impl Default for Config {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
omega_server: "omega.tensamin.methanium.net".into(),
|
omega_server: "omega.tensamin.methanium.net".into(),
|
||||||
auth_server: "auth.tensamin.methanium.net".into(),
|
auth_server: "auth.tensamin.methanium.net".into(),
|
||||||
omikron_id: Uuid::parse_str("a9e92dd6-08a6-4765-abf1-9fa39d0a99f9").unwrap(),
|
omikron_id: Uuid::parse_str("a9e92dd6-08a6-4765-abf1-9fa39d0a99f9").unwrap_or_default(),
|
||||||
keep_people_stored_for: 90,
|
keep_people_stored_for: 90,
|
||||||
max_data: 1000 * 1000 * 1000 * 8,
|
max_data: 1000 * 1000 * 1000 * 8,
|
||||||
ip: "0.0.0.0".into(),
|
ip: "0.0.0.0".into(),
|
||||||
|
|
@ -34,21 +29,22 @@ impl Default for Config {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Global instance with thread-safe read/write access
|
pub static CONFIG: Lazy<Mutex<Config>> = Lazy::new(|| Mutex::new(Config::load()));
|
||||||
pub static CONFIG: Lazy<RwLock<Config>> = Lazy::new(|| {
|
|
||||||
let config = Config::load().unwrap_or_default();
|
|
||||||
RwLock::new(config)
|
|
||||||
});
|
|
||||||
|
|
||||||
impl Config {
|
impl Config {
|
||||||
pub fn load() -> Option<Self> {
|
pub fn load() -> Self {
|
||||||
let content = load_file(CONFIG_PATH, CONFIG_FILENAME);
|
let content = load_file("", "config.json");
|
||||||
if content.trim().is_empty() {
|
if content.trim().is_empty() {
|
||||||
return None;
|
return Config::default();
|
||||||
}
|
}
|
||||||
|
|
||||||
let json = json::parse(&content).ok()?;
|
let json = json::parse(&content).unwrap();
|
||||||
Some(Self {
|
println!("{:?}", json);
|
||||||
|
println!(
|
||||||
|
"{:?}",
|
||||||
|
Uuid::parse_str(json["omikron_id"].as_str().unwrap_or_default()).unwrap_or_default()
|
||||||
|
);
|
||||||
|
Self {
|
||||||
omega_server: json["omega_server"].as_str().unwrap_or_default().into(),
|
omega_server: json["omega_server"].as_str().unwrap_or_default().into(),
|
||||||
auth_server: json["auth_server"].as_str().unwrap_or_default().into(),
|
auth_server: json["auth_server"].as_str().unwrap_or_default().into(),
|
||||||
omikron_id: Uuid::parse_str(json["omikron_id"].as_str().unwrap_or_default())
|
omikron_id: Uuid::parse_str(json["omikron_id"].as_str().unwrap_or_default())
|
||||||
|
|
@ -58,6 +54,6 @@ impl Config {
|
||||||
max_data: json["max_data"].as_u64().unwrap_or_default(),
|
max_data: json["max_data"].as_u64().unwrap_or_default(),
|
||||||
ip: json["ip"].as_str().unwrap_or_default().into(),
|
ip: json["ip"].as_str().unwrap_or_default().into(),
|
||||||
port: json["port"].as_u64().unwrap_or_default() as u16,
|
port: json["port"].as_u64().unwrap_or_default() as u16,
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,7 @@
|
||||||
use std::ffi::OsStr;
|
use std::ffi::OsStr;
|
||||||
use std::fmt::Write as FmtWrite;
|
|
||||||
use std::fs::{self, File};
|
use std::fs::{self, File};
|
||||||
use std::io::{Read, Write};
|
use std::io::Read;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::process;
|
|
||||||
use std::time::SystemTime;
|
|
||||||
use sysinfo::System;
|
use sysinfo::System;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
use walkdir::WalkDir;
|
use walkdir::WalkDir;
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue