diff --git a/src/auth/auth_connector.rs b/src/auth/auth_connector.rs index fd48a2d..67c3784 100644 --- a/src/auth/auth_connector.rs +++ b/src/auth/auth_connector.rs @@ -51,7 +51,7 @@ pub async fn get_uuid(username: &str) -> Option { let client = client(); let res = client.get(&url).send().await.ok()?; let json = res.text().await.ok()?; - let mut cv = CommunicationValue::from_json(&json); + let cv = CommunicationValue::from_json(&json); if !cv.is_type(CommunicationType::success) { return None; } @@ -64,7 +64,7 @@ pub async fn get_user(user_id: Uuid) -> Option { let res = client.get(&url).send().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 { return None; } @@ -103,7 +103,7 @@ pub async fn get_register() -> Option { let res = client.get(&url).send().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() } diff --git a/src/auth/crypto_helper.rs b/src/auth/crypto_helper.rs index 5d4f847..f1486b9 100644 --- a/src/auth/crypto_helper.rs +++ b/src/auth/crypto_helper.rs @@ -4,16 +4,8 @@ use aes_gcm::{ aead::{Aead, KeyInit, OsRng}, }; use base64::{Engine as _, engine::general_purpose::STANDARD}; -use base64::{decode as b64_decode, encode as b64_encode}; -use hex; -use json::JsonValue; -use once_cell::sync::Lazy; -use rand::Rng; use rand_core::RngCore; use sha2::{Digest, Sha256}; -use std::io; -use std::sync::Mutex; -use uuid::Uuid; use x448::{PublicKey, Secret, SharedSecret}; // from the `x448` crate /// Errors for crypto operations @@ -47,20 +39,20 @@ pub fn generate_keypair() -> KeyPair { } pub fn public_key_to_base64(pubkey: &PublicKey) -> String { - b64_encode(pubkey.as_bytes().as_ref()) + STANDARD.encode(pubkey.as_bytes().as_ref()) } pub fn secret_key_to_base64(secret: &Secret) -> String { - b64_encode(secret.as_bytes().as_ref()) + STANDARD.encode(secret.as_bytes().as_ref()) } pub fn load_public_key(base64_pub: &str) -> Option { - let bytes = b64_decode(base64_pub).unwrap(); + let bytes = STANDARD.decode(base64_pub).unwrap(); PublicKey::from_bytes(&bytes) } pub fn load_secret_key(base64_secret: &str) -> Option { - let bytes = b64_decode(base64_secret).unwrap(); + let bytes = STANDARD.decode(base64_secret).unwrap(); Secret::from_bytes(&bytes) } @@ -95,7 +87,7 @@ pub fn encrypt( let mut out = Vec::with_capacity(nonce_bytes.len() + ciphertext.len()); out.extend_from_slice(&nonce_bytes); out.extend_from_slice(&ciphertext); - Ok(b64_encode(&out)) + Ok(STANDARD.encode(&out)) } pub fn decrypt( @@ -111,7 +103,7 @@ pub fn decrypt( let key_bytes = derive_aes_key(&shared); let cipher = Aes256Gcm::new_from_slice(&key_bytes).expect("Key length should be correct"); - let encrypted = b64_decode(encrypted_base64)?; + let encrypted = STANDARD.decode(encrypted_base64)?; if encrypted.len() < 12 { return Err(CryptoError::DecryptionError(aes_gcm::Error)); } diff --git a/src/communities/community.rs b/src/communities/community.rs index 26b2337..2902cd1 100644 --- a/src/communities/community.rs +++ b/src/communities/community.rs @@ -1,7 +1,5 @@ use crate::communities::interactables::category::Category; use crate::communities::interactables::registry; -use crate::communities::interactables::text_chat::TextChat; -use crate::communities::interactables::voice_chat::VoiceChat; use crate::communities::{ community_connection::CommunityConnection, interactables::interactable::Interactable, }; @@ -12,8 +10,6 @@ use json::JsonValue; use json::object::Object; use rand::RngCore; use rand_core::OsRng; -use ratatui::text; -use serde::de::value::StringDeserializer; use std::collections::HashMap; use std::sync::Arc; use tokio::sync::RwLock; @@ -127,7 +123,7 @@ impl Community { cv: &CommunicationValue, ) -> CommunicationValue { if path.is_empty() { - let mut target_interactables = &self.interactables.read().await.clone(); + let target_interactables = &self.interactables.read().await.clone(); for interactable in target_interactables.iter() { if interactable.get_name() == name { if interactable.get_codec() == "category" { @@ -183,10 +179,10 @@ impl Community { let mut permissions = JsonValue::new_array(); for perm in self.permissions.get(user).unwrap() { - permissions.push(perm.to_string()); + if let Ok(_) = permissions.push(perm.to_string()) {} } - data.insert("permissions", permissions); + if let Ok(_) = data.insert("permissions", permissions) {} user_data.insert(&user.to_string(), data); } file_util::save_file( @@ -213,7 +209,7 @@ pub async fn load(name: &String) -> Option> { let (str, json): (&str, &JsonValue) = user; let perms_j = &json["permissions"]; let perms = Vec::new(); - for i in perms_j.entries() { + for _ in perms_j.entries() { // let perm_j = i.as_str().unwrap(); // perms.push(perm_j.to_string()); } @@ -225,11 +221,12 @@ pub async fn load(name: &String) -> Option> { } let role_data = file_util::load_file(&format!("communities/{}/", name), "roles.json"); - if let Ok(user_json) = json::parse(&role_data) { + let roles: HashMap> = HashMap::new(); + if let Ok(_) = json::parse(&role_data) { + // Fill roles } else { return None; }; - let mut roles: HashMap> = HashMap::new(); let community = Community { name: json_content["name"].as_str().unwrap().to_string(), @@ -266,15 +263,5 @@ pub async fn load(name: &String) -> Option> { comarc.add_interactable(Arc::new(interactable)).await; } } - let mut text_chat: TextChat = TextChat::new(); - text_chat.load( - comarc.clone(), - String::new(), - String::from("a"), - &JsonValue::Null, - ); - - comarc.add_interactable(Arc::new(Box::new(text_chat))).await; - Some(comarc) } diff --git a/src/communities/community_connection.rs b/src/communities/community_connection.rs index 970ab85..c4cbee4 100644 --- a/src/communities/community_connection.rs +++ b/src/communities/community_connection.rs @@ -8,7 +8,6 @@ use base64::{Engine as _, engine::general_purpose::STANDARD}; use futures::SinkExt; use hkdf::Hkdf; use json::JsonValue; -use json::object::Object; use rand::{Rng, distributions::Alphanumeric}; use sha2::Sha256; use std::sync::Arc; @@ -61,7 +60,8 @@ impl CommunityConnection { } pub async fn handle_message(self: Arc, message: String) { - let cv = CommunicationValue::from_json(&message); + let cv = + CommunicationValue::from_json(&message).with_sender(self.get_user_id().await.unwrap()); if cv.is_type(CommunicationType::identification) && !self.is_identified().await { self.handle_identification(cv).await; @@ -394,7 +394,7 @@ impl CommunityConnection { } pub async fn handle_close(&self) { if self.is_identified().await { - if let Some(user_id) = self.get_user_id().await { + if let Some(_) = self.get_user_id().await { todo!(); } } diff --git a/src/communities/community_manager.rs b/src/communities/community_manager.rs index ae6acab..bb628ed 100644 --- a/src/communities/community_manager.rs +++ b/src/communities/community_manager.rs @@ -5,7 +5,6 @@ use once_cell::sync::Lazy; use std::collections::HashMap; use std::sync::Arc; use tokio::sync::Mutex; -use uuid::Uuid; pub static COMMUNITY_REGISTRY: Lazy>>>> = Lazy::new(|| Arc::new(Mutex::new(HashMap::new()))); diff --git a/src/communities/community_socket.rs b/src/communities/community_socket.rs index c095bd2..2ed427c 100644 --- a/src/communities/community_socket.rs +++ b/src/communities/community_socket.rs @@ -1,6 +1,4 @@ -use crate::communities::{ - community::Community, community_connection::CommunityConnection, community_manager, -}; +use crate::communities::{community_connection::CommunityConnection, community_manager}; use futures::StreamExt; use std::sync::Arc; use tokio::net::TcpListener; @@ -23,7 +21,7 @@ pub async fn start(port: u16) -> bool { }; let ws_stream = match accept_hdr_async(stream, callback).await { Ok(ws) => ws, - Err(e) => { + Err(_) => { return; } }; @@ -48,7 +46,7 @@ pub async fn start(port: u16) -> bool { return; } } - Some(Err(e)) => { + Some(Err(_)) => { community_conn.handle_close().await; return; } diff --git a/src/communities/interactables/category.rs b/src/communities/interactables/category.rs index e352022..d037b3e 100644 --- a/src/communities/interactables/category.rs +++ b/src/communities/interactables/category.rs @@ -2,7 +2,6 @@ use crate::{ communities::{community::Community, interactables::interactable::Interactable}, data::communication::{CommunicationType, CommunicationValue}, }; -use axum::Json; use json::JsonValue; use std::any::Any; use std::sync::Arc; @@ -96,11 +95,11 @@ impl Interactable for Category { let mut v = JsonValue::new_object(); v["children"] = JsonValue::new_array(); for child in &self.children { - v["children"].push(child.to_json()); + let _ = v["children"].push(child.to_json()); } v } - fn load(&mut self, community: Arc, path: String, name: String, json: &JsonValue) { + fn load(&mut self, community: Arc, path: String, name: String, _json: &JsonValue) { self.community = community; self.name = name; self.path = path; diff --git a/src/communities/interactables/interactable.rs b/src/communities/interactables/interactable.rs index 7982a69..54a6515 100644 --- a/src/communities/interactables/interactable.rs +++ b/src/communities/interactables/interactable.rs @@ -1,11 +1,7 @@ -use crate::{ - communities::community::Community, - data::communication::{CommunicationType, CommunicationValue}, -}; -use axum::Json; +use crate::{communities::community::Community, data::communication::CommunicationValue}; use json::JsonValue; +use std::any::Any; use std::sync::Arc; -use std::{any::Any, pin::Pin}; pub type InteractableFactory = fn() -> Box; diff --git a/src/communities/interactables/registry.rs b/src/communities/interactables/registry.rs index d9f6954..67ecf3a 100644 --- a/src/communities/interactables/registry.rs +++ b/src/communities/interactables/registry.rs @@ -3,7 +3,6 @@ use crate::communities::interactables::category::Category; use crate::communities::interactables::interactable::{Interactable, InteractableFactory}; use crate::communities::interactables::text_chat::TextChat; use crate::communities::interactables::voice_chat::VoiceChat; -use crate::gui::log_panel; use crate::util::file_util; use json::JsonValue; use once_cell::sync::Lazy; diff --git a/src/communities/interactables/text_chat.rs b/src/communities/interactables/text_chat.rs index 5bc0ead..2cbe27c 100644 --- a/src/communities/interactables/text_chat.rs +++ b/src/communities/interactables/text_chat.rs @@ -7,16 +7,10 @@ use crate::{ gui::log_panel::log_message, util::file_util::{get_children, load_file, save_file}, }; -use aes_gcm::aead::Payload; -use axum::Json; use json::{JsonValue, array, object}; -use rustls::ClientConnection; use std::sync::Arc; use std::{any::Any, collections::HashMap}; -use std::{ - fs::{self, File}, - pin::Pin, -}; +use std::{fs, pin::Pin}; use uuid::Uuid; pub struct TextChat { name: String, @@ -190,7 +184,7 @@ impl Interactable for TextChat { JsonValue::new_object() } fn run_function(&self, cv: CommunicationValue) -> CommunicationValue { - let ret: Pin + Send>> = Box::pin(async move { + let _: Pin + Send>> = Box::pin(async move { let payload = cv.get_data(DataTypes::payload).unwrap(); if cv.get_data(DataTypes::function).unwrap().as_str().unwrap() == "get_messages" { let amount = payload["amount"].as_i64().unwrap(); @@ -247,10 +241,9 @@ impl Interactable for TextChat { CommunicationValue::new(CommunicationType::error) } fn to_json(&self) -> JsonValue { - let mut v = JsonValue::new_object(); - v + JsonValue::new_object() } - fn load(&mut self, community: Arc, path: String, name: String, json: &JsonValue) { + fn load(&mut self, community: Arc, path: String, name: String, _: &JsonValue) { self.community = community; self.name = name; self.path = path; diff --git a/src/communities/interactables/voice_chat.rs b/src/communities/interactables/voice_chat.rs index 5841e24..b42813d 100644 --- a/src/communities/interactables/voice_chat.rs +++ b/src/communities/interactables/voice_chat.rs @@ -72,10 +72,10 @@ impl Interactable for VoiceChat { CommunicationValue::new(CommunicationType::error) } fn to_json(&self) -> JsonValue { - let mut v = JsonValue::new_object(); + let v = JsonValue::new_object(); v } - fn load(&mut self, community: Arc, path: String, name: String, json: &JsonValue) { + fn load(&mut self, community: Arc, path: String, name: String, _json: &JsonValue) { self.community = community; self.name = name; self.path = path; diff --git a/src/data/communication.rs b/src/data/communication.rs index 4612083..63d7ea6 100644 --- a/src/data/communication.rs +++ b/src/data/communication.rs @@ -393,14 +393,6 @@ impl CommunicationValue { data, } } - pub fn ack_message(message_id: Uuid, sender: Uuid) -> CommunicationValue { - let mut cv = CommunicationValue::new(CommunicationType::message).with_id(message_id); - - if let s = sender { - cv = cv.add_data(DataTypes::send_time, JsonValue::String(s.to_string())); - } - cv - } pub fn forward_to_other_iota(original: &mut CommunicationValue) -> CommunicationValue { let receiver = Uuid::from_str( &*original @@ -420,7 +412,8 @@ impl CommunicationValue { CommunicationValue::new(CommunicationType::message_other_iota) .with_id(original.get_id()) .with_receiver(receiver.unwrap()) - .add_data( DataTypes::receiver_id, + .add_data( + DataTypes::receiver_id, JsonValue::String(receiver.unwrap().to_string()), ) .with_sender(sender.unwrap()) diff --git a/src/eula/eula_checker.rs b/src/eula/eula_checker.rs index 18b3244..b5237de 100644 --- a/src/eula/eula_checker.rs +++ b/src/eula/eula_checker.rs @@ -1,12 +1,11 @@ - use crate::util::file_util::{load_file, save_file}; -pub fn check_eula() -> bool{ +pub fn check_eula() -> bool { let eula = "By changing the value to \"true\" you agree to our end user license agreement and our terms of service!\ - \nYou can find our Terms of service on https://docs.tensamin.methanium.net/legal/terms-of-service/.\ + \nYou can find our Terms of service on https://docs.tensamin.net/legal/terms-of-service/.\ \neula=false"; let file = load_file("", "eula.txt"); - if(file.is_empty()){ + if file.is_empty() { save_file("", "eula.txt", eula); return false; } @@ -19,9 +18,9 @@ pub fn check_eula() -> bool{ false } } -pub fn accept_eula(){ - let eula = "By changing the value to \"true\" you agree to some shit we say on our website IDK this shouldn't be public yet!\ - \nYou also give us all rights to your soul, and we own your dog now.\ +pub fn accept_eula() { + let eula = "By changing the value to \"true\" you agree to our end user license agreement and our terms of service!\ + \nYou can find our Terms of service on https://docs.tensamin.net/legal/terms-of-service/.\ \neula=true"; save_file("", "eula.txt", eula); -} \ No newline at end of file +} diff --git a/src/gui/log_panel.rs b/src/gui/log_panel.rs index 3d3c98c..b388379 100644 --- a/src/gui/log_panel.rs +++ b/src/gui/log_panel.rs @@ -5,7 +5,6 @@ use crate::langu::language_manager::format; use crate::langu::language_manager::from_key; use crate::data::communication::{CommunicationType, CommunicationValue, DataTypes}; -use json::Array; use ratatui::widgets::canvas::{Canvas, Line}; use ratatui::{ layout::{Constraint, Direction, Layout}, @@ -96,8 +95,8 @@ pub fn setup() { } let ram = (sys.used_memory() as f64 / sys.total_memory() as f64) * 100.0; - let mut total_received = 0u64; - let mut total_transmitted = 0u64; + let total_received = 0u64; + let total_transmitted = 0u64; let delta_received = if last_total_received == 0 { 0 diff --git a/src/langu/language_creator.rs b/src/langu/language_creator.rs index 5f45c47..580657d 100644 --- a/src/langu/language_creator.rs +++ b/src/langu/language_creator.rs @@ -1,7 +1,7 @@ -use crate::util::file_util::{self, save_file}; -use json::{self, JsonValue}; +use crate::util::file_util::save_file; +use json::{self, JsonError, JsonValue}; -pub fn create_languages() { +pub fn create_languages() -> Result<(), JsonError> { let mut frontend_messages = JsonValue::new_object(); let mut omikron_messages = JsonValue::new_object(); let mut button_texts = JsonValue::new_object(); @@ -9,40 +9,43 @@ pub fn create_languages() { let mut debug_messages = JsonValue::new_object(); // FRONTEND - frontend_messages.insert("get_chats", "User {} is loading conversations"); - frontend_messages.insert("message_get", "User {} is loading messages"); - frontend_messages.insert("get_communities", "User {} is loading communities"); - frontend_messages.insert("client_connected", "Client {} connected"); - frontend_messages.insert("add_conversation", "User {} added {}"); + frontend_messages.insert("get_chats", "User {} is loading conversations")?; + frontend_messages.insert("message_get", "User {} is loading messages")?; + frontend_messages.insert("get_communities", "User {} is loading communities")?; + frontend_messages.insert("client_connected", "Client {} connected")?; + frontend_messages.insert("add_conversation", "User {} added {}")?; + frontend_messages.insert("message_send", "User {} sent a message")?; // OMIKRON omikron_messages.insert( "identification_response", "IOTA identified on Omikron, {} users!", - ); + )?; + omikron_messages.insert("send_message_failed", "Failed to send message to Omikron")?; // BUTTONS - button_texts.insert("exit", "Exit"); + button_texts.insert("exit", "Exit")?; // GENERAL - general_texts.insert("iota_id", "IOTA ID: {}-####-####-####-############"); - general_texts.insert("user_id", "USER ID: {}"); - general_texts.insert("user_ids", "USER IDS: {}"); - general_texts.insert("setup_completed", "Launched"); + general_texts.insert("iota_id", "IOTA ID: {}-####-####-####-############")?; + general_texts.insert("user_id", "USER ID: {}")?; + general_texts.insert("user_ids", "USER IDS: {}")?; + general_texts.insert("user_load_failed", "Failed to load user data")?; + general_texts.insert("setup_completed", "Launched")?; general_texts.insert( "community_active", "Communities active on ws://0.0.0.0:{}/community/...", - ); + )?; general_texts.insert( "community_start_error", "Failed to start community socket on port {}!", - ); + )?; general_texts.insert( "community_start_error_admin", "Failed to start community socket on port {}! Run with admin privileges", - ); + )?; // DEBUG - debug_messages.insert("", ""); + debug_messages.insert("", "")?; save_file( "languages/en_INT", "frontend.json", @@ -68,4 +71,5 @@ pub fn create_languages() { "general.json", &general_texts.to_string(), ); + Ok(()) } diff --git a/src/langu/language_manager.rs b/src/langu/language_manager.rs index 1ca84f7..8400ac0 100644 --- a/src/langu/language_manager.rs +++ b/src/langu/language_manager.rs @@ -39,7 +39,7 @@ pub fn from_key(key: &str) -> String { pub fn format(key: &str, args: &[&str]) -> String { let message = from_key(key); let mut formatted = String::new(); - let mut parts = message.split("{}"); + let parts = message.split("{}"); for (i, part) in parts.enumerate() { formatted.push_str(part); if i < args.len() { diff --git a/src/main.rs b/src/main.rs index 5aff9df..612ce1c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -29,8 +29,8 @@ use crate::util::config_util::CONFIG; pub static APP_STATE: LazyLock>> = LazyLock::new(|| Arc::new(Mutex::new(AppState::new()))); - -#[tokio::main] +#[tokio::main(flavor = "multi_thread", worker_threads = 8)] +#[allow(unused_must_use, dead_code)] async fn main() { // EULA //if !eula_checker::check_eula() { @@ -38,21 +38,31 @@ async fn main() { // return; //} + // LANGUAGE PACK + if let Err(e) = language_creator::create_languages() { + println!("Language pack creation failed: {}", e); + return; + } + // UI log_panel::setup(); - ratatui_interface::launch(); - // LANGUAGE PACK - language_creator::create_languages(); + if let Err(e) = ratatui_interface::launch() { + println!("Ui launch failed: {}", &e.to_string()); + return; + } // BASIC CONFIGURATION CONFIG.lock().unwrap().load(); if !CONFIG.lock().unwrap().config.has_key("iota_id") { CONFIG.lock().unwrap().change("iota_id", Uuid::new_v4()); - CONFIG.lock().unwrap().save(); + CONFIG.lock().unwrap().update(); } // USER MANAGEMENT - user_manager::load_users().await; + + if let Err(_) = user_manager::load_users().await { + log_message_trans("user_load_failed"); + } let mut sb = "".to_string(); for up in user_manager::get_users() { sb = sb + "," + &up.user_id.to_string().as_str(); diff --git a/src/omikron/omikron_connection.rs b/src/omikron/omikron_connection.rs index aabc526..8f0e0e7 100644 --- a/src/omikron/omikron_connection.rs +++ b/src/omikron/omikron_connection.rs @@ -1,5 +1,5 @@ use crate::data::communication::{CommunicationType, CommunicationValue, DataTypes}; -use crate::gui::log_panel::{log_cv, log_message}; +use crate::gui::log_panel::{log_cv, log_message, log_message_trans}; use crate::users::contact::Contact; use crate::users::user_community_util::UserCommunityUtil; use crate::util::chat_files; @@ -80,7 +80,7 @@ impl OmikronConnection { } } pub async fn send_message(&self, msg: String) { - Self::send_message_static(&self.writer, msg).await; + Self::send_message_static(&self.writer, msg).await } /// Listener for all incoming messages @@ -90,222 +90,249 @@ impl OmikronConnection { WebSocketStream>, >, ) { - let waiting = self.waiting.clone(); - let writer = self.writer.clone(); - let is_connected = self.is_connected.clone(); - let sel = self.clone(); + let waiting_out = self.waiting.clone(); + let writer_out = self.writer.clone(); + let is_connected_out = self.is_connected.clone(); + let sel_out = self.clone(); tokio::spawn(async move { while let Some(msg) = read_half.next().await { - match msg { - Ok(Message::Close(Some(frame))) => { - log_message(format!("[Omikron] Closed: {:?}", frame)); - *is_connected.lock().await = false; - break; - } - Ok(Message::Text(text)) => { - let mut cv = CommunicationValue::from_json(&text); - if cv.is_type(CommunicationType::pong) { - sel.handle_pong(&cv, true).await; - continue; + let waiting = waiting_out.clone(); + let writer = writer_out.clone(); + let is_connected = is_connected_out.clone(); + let sel = sel_out.clone(); + tokio::spawn(async move { + match msg { + Ok(Message::Close(Some(frame))) => { + log_message(format!("[Omikron] Closed: {:?}", frame)); + *is_connected.lock().await = false; + return; } - // ************************************************ // - // Direct messages // - // ************************************************ // - log_cv(&cv); - if cv.is_type(CommunicationType::message_other_iota) { - let sender_id = &cv.get_sender().unwrap(); - let receiver_id = &cv.get_receiver().unwrap(); + Ok(Message::Text(text)) => { + let mut cv = CommunicationValue::from_json(&text); + if cv.is_type(CommunicationType::pong) { + sel.handle_pong(&cv, true).await; + return; + } + // ************************************************ // + // Direct messages // + // ************************************************ // + log_cv(&cv); + if let Some(x) = waiting.lock().await.remove(&cv.get_id()) { + x(cv); + return; + } + if cv.is_type(CommunicationType::message_other_iota) { + let sender_id = &cv.get_sender().unwrap(); + let receiver_id = &cv.get_receiver().unwrap(); - chat_files::add_message( - cv.get_data(DataTypes::send_time) - .unwrap() - .as_i64() - .unwrap_or(0) as u128, - false, - *receiver_id, - *sender_id, - cv.get_data(DataTypes::content).unwrap().as_str().unwrap(), - ); - let response = CommunicationValue::new(CommunicationType::message_live) - .with_id(cv.get_id()) - .with_receiver(cv.get_receiver().unwrap()) - .add_data( - DataTypes::send_time, - cv.get_data(DataTypes::send_time).unwrap().clone(), - ) - .add_data( - DataTypes::message, - cv.get_data(DataTypes::content).unwrap().clone(), - ) - .add_data( - DataTypes::sender_id, - JsonValue::String(cv.get_sender().unwrap().to_string()), + chat_files::add_message( + cv.get_data(DataTypes::send_time) + .unwrap() + .as_i64() + .unwrap_or(0) as u128, + false, + *receiver_id, + *sender_id, + cv.get_data(DataTypes::content).unwrap().as_str().unwrap(), ); - Self::send_message_static( - &writer.clone(), - response.to_json().to_string(), - ) - .await; - continue; - } - - if cv.is_type(CommunicationType::message_send) { - /* DATA CONTAINER: - "sent_by_self": true, - "timestamp": unixTimestamp, - "files": [ // wenn keine files dann weglassen - { - "name": "", - "id": "", - "type": "[ image | image_top_right | file ]" - } - ], - "content": "" - */ - let my_id = cv.get_sender().unwrap(); - let other_id = Uuid::from_str( - &*cv.get_data(DataTypes::receiver_id).unwrap().to_string(), - ) - .unwrap(); - chat_files::add_message( - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_millis() as u128, - true, - my_id, - other_id, - &*cv.get_data(DataTypes::content).unwrap().to_string(), - ); - let ack = CommunicationValue::ack_message(cv.get_id(), my_id); - Self::send_message_static(&writer.clone(), ack.to_json().to_string()) + let response = + CommunicationValue::new(CommunicationType::message_live) + .with_id(cv.get_id()) + .with_receiver(cv.get_receiver().unwrap()) + .add_data( + DataTypes::send_time, + cv.get_data(DataTypes::send_time).unwrap().clone(), + ) + .add_data( + DataTypes::message, + cv.get_data(DataTypes::content).unwrap().clone(), + ) + .add_data( + DataTypes::sender_id, + JsonValue::String(cv.get_sender().unwrap().to_string()), + ); + Self::send_message_static( + &writer.clone(), + response.to_json().to_string(), + ) .await; - let forward = CommunicationValue::forward_to_other_iota(&mut cv); - Self::send_message_static( - &writer.clone(), - forward.to_json().to_string(), - ) - .await; - continue; - } + return; + } - if cv.is_type(CommunicationType::messages_get) { - let my_id = cv.get_sender().unwrap(); - let partner_id = Uuid::from_str( - &*cv.get_data(DataTypes::user_id).unwrap().to_string(), - ) - .unwrap(); - let offset = cv - .get_data(DataTypes::offset) - .unwrap_or(&JsonValue::Null) - .to_string() - .parse::() - .unwrap_or(0); - let amount = cv - .get_data(DataTypes::amount) - .unwrap_or(&JsonValue::Null) - .to_string() - .parse::() - .unwrap_or(0); - let messages = - chat_files::get_messages(my_id, partner_id, offset, amount); - let resp = CommunicationValue::new(CommunicationType::messages_get) - .with_id(cv.get_id()) - .with_receiver(my_id) - .add_data(DataTypes::messages, messages); - - Self::send_message_static(&writer.clone(), resp.to_json().to_string()) - .await; - continue; - } - - if cv.is_type(CommunicationType::get_chats) { - let user_id = cv.get_sender().unwrap(); - let users = get_users(user_id); - let resp = CommunicationValue::new(CommunicationType::get_chats) - .with_id(cv.get_id()) - .with_receiver(user_id) - .add_data(DataTypes::user_ids, users); - Self::send_message_static(&writer.clone(), resp.to_json().to_string()) - .await; - continue; - } - - if cv.is_type(CommunicationType::add_chat) { - let user_id = cv.get_sender().unwrap(); - let other_id = Uuid::from_str( - &*cv.get_data(DataTypes::user_id).unwrap().to_string(), - ) - .unwrap(); - let mut contact = - get_user(user_id, other_id).unwrap_or(Contact::new(other_id)); // needs ChatsUtil + Contact - contact.set_last_message_at( - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_millis() as i64, - ); - mod_user(user_id, &contact); - let resp = CommunicationValue::new(CommunicationType::add_chat) - .with_id(cv.get_id()) - .with_receiver(user_id); - Self::send_message_static(&writer.clone(), resp.to_json().to_string()) - .await; - continue; - } - - if cv.is_type(CommunicationType::add_community) { - UserCommunityUtil::add_community( - cv.get_sender().unwrap(), - cv.get_data(DataTypes::community_address) - .unwrap() - .to_string(), - cv.get_data(DataTypes::community_title).unwrap().to_string(), - cv.get_data(DataTypes::position).unwrap().to_string(), - ); - let resp = CommunicationValue::new(CommunicationType::add_community) - .with_id(cv.get_id()) - .with_receiver(cv.get_sender().unwrap()); - Self::send_message_static(&writer.clone(), resp.to_json().to_string()) - .await; - continue; - } - - if cv.is_type(CommunicationType::get_communities) { - let resp = CommunicationValue::new(CommunicationType::get_communities) - .with_id(cv.get_id()) - .with_receiver(cv.get_sender().unwrap()) - .add_array( - DataTypes::communities, - UserCommunityUtil::get_communities(cv.get_sender().unwrap()), + if cv.is_type(CommunicationType::message_send) { + let my_id = cv.get_sender().unwrap(); + let other_id = Uuid::from_str( + &*cv.get_data(DataTypes::receiver_id).unwrap().to_string(), + ) + .unwrap(); + chat_files::add_message( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() as u128, + true, + my_id, + other_id, + &*cv.get_data(DataTypes::content).unwrap().to_string(), ); - Self::send_message_static(&writer.clone(), resp.to_json().to_string()) + let ack = CommunicationValue::new(CommunicationType::message) + .with_id(cv.get_id()) + .with_receiver(my_id); + Self::send_message_static( + &writer.clone(), + ack.to_json().to_string(), + ) .await; - continue; - } + let forward = CommunicationValue::forward_to_other_iota(&mut cv); + Self::send_message_static( + &writer.clone(), + forward.to_json().to_string(), + ) + .await; + return; + } - if cv.is_type(CommunicationType::remove_community) { - UserCommunityUtil::remove_community( - cv.get_sender().unwrap(), - cv.get_data(DataTypes::community_address) - .unwrap() - .to_string(), - ); // needs UserCommunityUtil - let resp = CommunicationValue::new(CommunicationType::remove_community) - .with_id(cv.get_id()) - .with_receiver(cv.get_sender().unwrap()); - Self::send_message_static(&writer.clone(), resp.to_json().to_string()) + if cv.is_type(CommunicationType::messages_get) { + let my_id = cv.get_sender().unwrap(); + let partner_id = Uuid::from_str( + &*cv.get_data(DataTypes::user_id).unwrap().to_string(), + ) + .unwrap(); + let offset = cv + .get_data(DataTypes::offset) + .unwrap_or(&JsonValue::Null) + .to_string() + .parse::() + .unwrap_or(0); + let amount = cv + .get_data(DataTypes::amount) + .unwrap_or(&JsonValue::Null) + .to_string() + .parse::() + .unwrap_or(0); + let messages = + chat_files::get_messages(my_id, partner_id, offset, amount); + let resp = CommunicationValue::new(CommunicationType::messages_get) + .with_id(cv.get_id()) + .with_receiver(my_id) + .add_data(DataTypes::messages, messages); + + Self::send_message_static( + &writer.clone(), + resp.to_json().to_string(), + ) .await; - continue; + return; + } + + if cv.is_type(CommunicationType::get_chats) { + let user_id = cv.get_sender().unwrap(); + let users = get_users(user_id); + let resp = CommunicationValue::new(CommunicationType::get_chats) + .with_id(cv.get_id()) + .with_receiver(user_id) + .add_data(DataTypes::user_ids, users); + Self::send_message_static( + &writer.clone(), + resp.to_json().to_string(), + ) + .await; + return; + } + + if cv.is_type(CommunicationType::add_chat) { + let user_id = cv.get_sender().unwrap(); + let other_id = Uuid::from_str( + &*cv.get_data(DataTypes::user_id).unwrap().to_string(), + ) + .unwrap(); + let mut contact = + get_user(user_id, other_id).unwrap_or(Contact::new(other_id)); // needs ChatsUtil + Contact + contact.set_last_message_at( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() as i64, + ); + mod_user(user_id, &contact); + let resp = CommunicationValue::new(CommunicationType::add_chat) + .with_id(cv.get_id()) + .with_receiver(user_id); + Self::send_message_static( + &writer.clone(), + resp.to_json().to_string(), + ) + .await; + return; + } + + if cv.is_type(CommunicationType::add_community) { + UserCommunityUtil::add_community( + cv.get_sender().unwrap(), + cv.get_data(DataTypes::community_address) + .unwrap() + .to_string(), + cv.get_data(DataTypes::community_title).unwrap().to_string(), + cv.get_data(DataTypes::position).unwrap().to_string(), + ); + let resp = + CommunicationValue::new(CommunicationType::add_community) + .with_id(cv.get_id()) + .with_receiver(cv.get_sender().unwrap()); + Self::send_message_static( + &writer.clone(), + resp.to_json().to_string(), + ) + .await; + return; + } + + if cv.is_type(CommunicationType::get_communities) { + let resp = + CommunicationValue::new(CommunicationType::get_communities) + .with_id(cv.get_id()) + .with_receiver(cv.get_sender().unwrap()) + .add_array( + DataTypes::communities, + UserCommunityUtil::get_communities( + cv.get_sender().unwrap(), + ), + ); + Self::send_message_static( + &writer.clone(), + resp.to_json().to_string(), + ) + .await; + return; + } + + if cv.is_type(CommunicationType::remove_community) { + UserCommunityUtil::remove_community( + cv.get_sender().unwrap(), + cv.get_data(DataTypes::community_address) + .unwrap() + .to_string(), + ); // needs UserCommunityUtil + let resp = + CommunicationValue::new(CommunicationType::remove_community) + .with_id(cv.get_id()) + .with_receiver(cv.get_sender().unwrap()); + Self::send_message_static( + &writer.clone(), + resp.to_json().to_string(), + ) + .await; + return; + } } + Err(e) => { + log_message(format!("[Omikron] Error: {}", e)); + *is_connected.lock().await = false; + return; + } + _ => {} } - Err(e) => { - log_message(format!("[Omikron] Error: {}", e)); - *is_connected.lock().await = false; - break; - } - _ => {} - } + }); } }); } @@ -324,8 +351,12 @@ impl OmikronConnection { ) { let mut guard = writer.lock().await; if let Some(writer) = guard.as_mut() { - writer.send(Message::Text(msg)).await; - writer.flush().await; + if let Ok(_) = writer.send(Message::Text(msg)).await { + if let Ok(_) = writer.flush().await { + return; + } + } } + log_message_trans("send_message_failed"); } } diff --git a/src/omikron/ping_pong_task.rs b/src/omikron/ping_pong_task.rs index f44f483..5a96a5a 100644 --- a/src/omikron/ping_pong_task.rs +++ b/src/omikron/ping_pong_task.rs @@ -1,9 +1,7 @@ use crate::APP_STATE; use crate::data::communication::{CommunicationType, CommunicationValue, DataTypes}; use crate::omikron::omikron_connection::OmikronConnection; -use json::JsonValue; use json::number::Number; -use std::sync::Arc; use tokio::time::Instant; use uuid::Uuid; diff --git a/src/users/contact.rs b/src/users/contact.rs index bc241cb..ea6ac47 100644 --- a/src/users/contact.rs +++ b/src/users/contact.rs @@ -7,18 +7,6 @@ pub struct Contact { pub user_id: Option, pub user_name: Option, pub last_message_at: Option, - pub user_status: UserStatus, - pub about: Option, -} - -#[derive(Debug, Clone)] -pub enum UserStatus { - Online, - Do_Not_Disturb, - WC, - Away, - User_Offline, - Iota_Offline, } impl Default for Contact { @@ -31,30 +19,16 @@ impl Default for Contact { user_id: None, user_name: None, last_message_at: Some(now), - user_status: UserStatus::User_Offline, - about: None, } } } impl Contact { - pub fn new_with_time(last_message_at: i64, user_id: Uuid) -> Self { - Contact { - user_id: Some(user_id), - user_name: None, - last_message_at: Some(last_message_at), - user_status: UserStatus::User_Offline, - about: None, - } - } - pub fn new(user_id: Uuid) -> Self { Contact { user_id: Some(user_id), user_name: None, last_message_at: None, - user_status: UserStatus::User_Offline, - about: None, } } pub fn set_last_message_at(&mut self, p0: i64) { @@ -74,12 +48,6 @@ impl Contact { } obj } - - pub fn from_string(s: &str) -> Contact { - let parsed: JsonValue = JsonValue::from(s); - Self::from_json(&parsed) - } - pub fn from_json(o: &JsonValue) -> Contact { let user_id = o["user_id"].as_str().and_then(|s| Uuid::parse_str(s).ok()); @@ -91,51 +59,6 @@ impl Contact { user_id, user_name, last_message_at, - user_status: UserStatus::User_Offline, // default - about: None, } } - pub fn info(&self) -> JsonValue { - let mut obj = self.to_json(); - if let Some(id) = &self.user_id { - obj["user_id"] = JsonValue::from(id.to_string()); - } - if let Some(name) = &self.user_name { - obj["user_name"] = JsonValue::from(name.as_str()); - } - obj - } - - // getters & setters - pub fn get_about(&self) -> Option<&String> { - self.about.as_ref() - } - - pub fn set_about(&mut self, about: String) { - self.about = Some(about); - } - - pub fn get_user_id(&self) -> Option { - self.user_id - } - - pub fn set_user_id(&mut self, id: Uuid) { - self.user_id = Some(id); - } - - pub fn get_user_name(&self) -> Option<&String> { - self.user_name.as_ref() - } - - pub fn set_user_name(&mut self, name: String) { - self.user_name = Some(name); - } - - pub fn get_user_status(&self) -> &UserStatus { - &self.user_status - } - - pub fn set_user_status(&mut self, status: UserStatus) { - self.user_status = status; - } } diff --git a/src/users/user_manager.rs b/src/users/user_manager.rs index 33ba9df..518003b 100644 --- a/src/users/user_manager.rs +++ b/src/users/user_manager.rs @@ -75,13 +75,6 @@ pub fn get_users() -> Vec { USERS.lock().unwrap().clone() } -pub fn add_user(up: UserProfile) { - let mut users = USERS.lock().unwrap(); - users.retain(|u| u.user_id != up.user_id); - users.push(up); - *UNIQUE.lock().unwrap() = true; -} - pub fn remove_user(user_id: Uuid) { let mut users = USERS.lock().unwrap(); users.retain(|u| u.user_id != user_id); diff --git a/src/util/config_util.rs b/src/util/config_util.rs index 6659598..7a99460 100644 --- a/src/util/config_util.rs +++ b/src/util/config_util.rs @@ -45,11 +45,7 @@ impl ConfigUtil { pub fn update(&mut self) { if self.unique { - let _ = self.save(); + save_file("", "config.json", &self.config.to_string()); } } - - pub fn save(&self) { - save_file("", "config.json", &self.config.to_string()); - } }