Logging system, Omikron Reconnection
This commit is contained in:
parent
beea361971
commit
6ae6e85b5a
7 changed files with 71 additions and 113 deletions
|
|
@ -1,13 +1,9 @@
|
|||
use crate::CONFIG;
|
||||
use crate::data::communication::{CommunicationType, CommunicationValue, DataTypes};
|
||||
use crate::gui::log_panel::log_message;
|
||||
use crate::users::user_profile::UserProfile;
|
||||
use hex;
|
||||
use json::JsonValue;
|
||||
use reqwest::header::CONTENT_TYPE;
|
||||
use reqwest::{Client, Response};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
use uuid::Uuid;
|
||||
#[derive(Debug, Clone)]
|
||||
|
|
@ -32,7 +28,7 @@ fn client() -> Client {
|
|||
}
|
||||
|
||||
pub async fn unregister_user(user_id: Uuid, reset_token: &str) -> Option<bool> {
|
||||
let url = format!("https:/auth.tensamin.methanium.net/api/delete/{}/", user_id);
|
||||
let url = format!("https:/auth.tensamin.methanium.net/api/delete/{}", user_id);
|
||||
let client = client();
|
||||
|
||||
let mut payload = JsonValue::new_object();
|
||||
|
|
@ -52,7 +48,7 @@ pub async fn unregister_user(user_id: Uuid, reset_token: &str) -> Option<bool> {
|
|||
|
||||
pub async fn get_uuid(username: &str) -> Option<Uuid> {
|
||||
let url = format!(
|
||||
"https://auth.tensamin.methanium.net/api/get/uuid/{}/",
|
||||
"https://auth.tensamin.methanium.net/api/get/uuid/{}",
|
||||
username
|
||||
);
|
||||
let client = client();
|
||||
|
|
@ -66,7 +62,7 @@ pub async fn get_uuid(username: &str) -> Option<Uuid> {
|
|||
}
|
||||
|
||||
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 res = client.get(&url).send().await.ok()?;
|
||||
let json = res.text().await.ok()?;
|
||||
|
|
@ -105,7 +101,7 @@ pub async fn get_user(user_id: Uuid) -> Option<AuthUser> {
|
|||
}
|
||||
|
||||
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 res = client.get(&url).send().await.ok()?;
|
||||
let json = res.text().await.ok()?;
|
||||
|
|
@ -115,7 +111,7 @@ pub async fn get_register() -> Option<Uuid> {
|
|||
}
|
||||
|
||||
pub async fn complete_register(user_profile: &UserProfile, iota_id: &str) -> bool {
|
||||
let url = "https://auth.tensamin.methanium.net/api/register/complete/";
|
||||
let url = "https://auth.tensamin.methanium.net/api/register/complete";
|
||||
let client = client();
|
||||
|
||||
let mut payload = JsonValue::new_object();
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ use uuid::Uuid;
|
|||
#[derive(Eq, Hash, PartialEq, Clone, Debug)]
|
||||
pub enum DataTypes {
|
||||
error_type,
|
||||
accepted_ids,
|
||||
chat_partner_id,
|
||||
iota_id,
|
||||
user_id,
|
||||
|
|
@ -310,7 +311,7 @@ impl CommunicationValue {
|
|||
self.data.insert(key, JsonValue::Array(value));
|
||||
self
|
||||
}
|
||||
pub fn get_data(&mut self, key: DataTypes) -> Option<&JsonValue> {
|
||||
pub fn get_data(&self, key: DataTypes) -> Option<&JsonValue> {
|
||||
self.data.get(&key)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,38 +1,28 @@
|
|||
use crate::APP_STATE;
|
||||
use crate::gui::ratatui_interface::TERMINAL;
|
||||
use crate::gui::widgets::betterblock::draw_block_joins;
|
||||
use crate::langu::language_manager::format;
|
||||
use crate::langu::language_manager::from_key;
|
||||
use crossterm::{
|
||||
ExecutableCommand, execute,
|
||||
terminal::{
|
||||
Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode,
|
||||
enable_raw_mode,
|
||||
},
|
||||
};
|
||||
|
||||
use futures_util::lock::Mutex;
|
||||
use ratatui::widgets::{
|
||||
BorderType,
|
||||
canvas::{Canvas, Line},
|
||||
};
|
||||
use crate::data::communication::{CommunicationType, CommunicationValue, DataTypes};
|
||||
use json::Array;
|
||||
use ratatui::widgets::canvas::{Canvas, Line};
|
||||
use ratatui::{
|
||||
Terminal,
|
||||
backend::CrosstermBackend,
|
||||
layout::{Constraint, Direction, Layout},
|
||||
style::{Color, Style},
|
||||
symbols,
|
||||
style::Color,
|
||||
widgets::{Block, Borders, List, ListItem, Paragraph},
|
||||
};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
io::{Stdout, Write, stdout},
|
||||
process::Command,
|
||||
sync::{Arc, LazyLock},
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
use std::{thread, time::Duration};
|
||||
use sysinfo::{RefreshKind, System};
|
||||
|
||||
pub fn log_cv(cv: &CommunicationValue) {
|
||||
if cv.is_type(CommunicationType::identification_response) {
|
||||
let args = [cv.get_data(DataTypes::accepted).unwrap().as_str().unwrap()];
|
||||
log_message(format(&"identification_response", &args));
|
||||
} else {
|
||||
log_message_trans(format!("{:?}", &cv.comm_type));
|
||||
}
|
||||
}
|
||||
pub fn log_message_trans(key: impl Into<String>) {
|
||||
APP_STATE.lock().unwrap().push_log(from_key(&key.into()));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,8 +9,8 @@ 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_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 {}");
|
||||
|
|
@ -22,13 +22,13 @@ pub fn create_languages() {
|
|||
);
|
||||
|
||||
// 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("setup_completed", "Launched");
|
||||
|
||||
// DEBUG
|
||||
debug_messages.insert("", "");
|
||||
|
|
|
|||
49
src/main.rs
49
src/main.rs
|
|
@ -3,6 +3,8 @@ use json::{self};
|
|||
use std::sync::Arc;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::Mutex;
|
||||
use sysinfo::User;
|
||||
use tokio::time::{Duration, sleep};
|
||||
use uuid::Uuid;
|
||||
|
||||
mod auth;
|
||||
|
|
@ -49,7 +51,6 @@ async fn main() {
|
|||
|
||||
// USER MANAGEMENT
|
||||
UserManager::load_users().await;
|
||||
|
||||
let mut sb = "".to_string();
|
||||
for up in UserManager::get_users() {
|
||||
sb = sb + "," + &up.user_id.to_string().as_str();
|
||||
|
|
@ -71,25 +72,29 @@ async fn main() {
|
|||
.unwrap()
|
||||
));
|
||||
log_message(format!("User IDS: {}", sb));
|
||||
|
||||
// IDENTIFICATION ON OMIKRON
|
||||
let omikron: OmikronConnection = OmikronConnection::new();
|
||||
omikron.connect().await;
|
||||
omikron
|
||||
.send_message(
|
||||
CommunicationValue::new(CommunicationType::identification)
|
||||
.add_data(DataTypes::user_ids, String(sb.to_string()))
|
||||
.add_data(
|
||||
DataTypes::iota_id,
|
||||
String(CONFIG.lock().unwrap().get_iota_id().to_string()),
|
||||
)
|
||||
.to_json()
|
||||
.to_string()
|
||||
.as_mut()
|
||||
.to_string(),
|
||||
)
|
||||
.await;
|
||||
log_message_trans("SETUP_COMPLETED");
|
||||
|
||||
loop {}
|
||||
loop {
|
||||
let omikron: OmikronConnection = OmikronConnection::new();
|
||||
omikron.connect().await;
|
||||
omikron
|
||||
.send_message(
|
||||
CommunicationValue::new(CommunicationType::identification)
|
||||
.add_data(DataTypes::user_ids, String(sb.to_string()))
|
||||
.add_data(
|
||||
DataTypes::iota_id,
|
||||
String(CONFIG.lock().unwrap().get_iota_id().to_string()),
|
||||
)
|
||||
.to_json()
|
||||
.to_string()
|
||||
.as_mut()
|
||||
.to_string(),
|
||||
)
|
||||
.await;
|
||||
log_message_trans("setup_completed");
|
||||
loop {
|
||||
if !omikron.is_connected().await {
|
||||
break;
|
||||
}
|
||||
sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use crate::data::communication::{CommunicationType, CommunicationValue, DataTypes};
|
||||
use crate::gui::log_panel::log_message;
|
||||
use crate::gui::log_panel::log_message_trans;
|
||||
use crate::gui::log_panel::{log_cv, log_message};
|
||||
use crate::users::contact::Contact;
|
||||
use crate::users::user_community_util::UserCommunityUtil;
|
||||
use crate::util::chat_files::ChatFiles;
|
||||
|
|
@ -33,8 +33,8 @@ pub struct OmikronConnection {
|
|||
>,
|
||||
waiting: Arc<Mutex<HashMap<Uuid, Box<dyn Fn(CommunicationValue) + Send + Sync>>>>, // waiting for responses
|
||||
pingpong: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>, // ping-pong handler
|
||||
pub message_queue: Arc<Mutex<Vec<String>>>,
|
||||
pub message_send_times: Arc<Mutex<HashMap<Uuid, Instant>>>,
|
||||
pub is_connected: Arc<Mutex<bool>>,
|
||||
}
|
||||
|
||||
impl OmikronConnection {
|
||||
|
|
@ -43,14 +43,12 @@ impl OmikronConnection {
|
|||
writer: Arc::new(Mutex::new(None)),
|
||||
waiting: Arc::new(Mutex::new(HashMap::new())),
|
||||
pingpong: Arc::new(Mutex::new(None)),
|
||||
message_queue: Arc::new(Mutex::new(Vec::new())),
|
||||
message_send_times: Arc::new(Mutex::new(HashMap::new())),
|
||||
is_connected: Arc::new(Mutex::new(false)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn reconnect(&self) {
|
||||
self.disconnect().await;
|
||||
self.connect().await;
|
||||
pub async fn is_connected(&self) -> bool {
|
||||
*self.is_connected.lock().await
|
||||
}
|
||||
/// Connect loop with retry
|
||||
pub async fn connect(&self) {
|
||||
|
|
@ -68,11 +66,13 @@ impl OmikronConnection {
|
|||
}
|
||||
});
|
||||
|
||||
*self.is_connected.lock().await = true;
|
||||
*self.pingpong.lock().await = Some(handle);
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
Err(_) => {
|
||||
log_message("CONNECTION FAILED");
|
||||
*self.is_connected.lock().await = false;
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
}
|
||||
}
|
||||
|
|
@ -82,15 +82,6 @@ impl OmikronConnection {
|
|||
Self::send_message_static(&self.writer, msg).await;
|
||||
}
|
||||
|
||||
pub async fn disconnect(&self) {
|
||||
if let Some(handle) = self.pingpong.lock().await.take() {
|
||||
handle.abort();
|
||||
}
|
||||
if let Some(mut ws) = self.writer.lock().await.take() {
|
||||
let _ = ws.close().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Listener for all incoming messages
|
||||
async fn spawn_listener(
|
||||
&self,
|
||||
|
|
@ -100,12 +91,14 @@ impl OmikronConnection {
|
|||
) {
|
||||
let waiting = self.waiting.clone();
|
||||
let writer = self.writer.clone();
|
||||
let is_connected = self.is_connected.clone();
|
||||
let sel = 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)) => {
|
||||
|
|
@ -117,7 +110,7 @@ impl OmikronConnection {
|
|||
// ************************************************ //
|
||||
// Direct messages //
|
||||
// ************************************************ //
|
||||
log_message_trans(format!("{:?}", &cv.comm_type));
|
||||
log_cv(&cv);
|
||||
if cv.is_type(CommunicationType::message_other_iota) {
|
||||
let sender_id = &cv.get_sender();
|
||||
let receiver_id = &cv.get_receiver();
|
||||
|
|
@ -183,12 +176,6 @@ impl OmikronConnection {
|
|||
other_id,
|
||||
&*cv.get_data(DataTypes::content).unwrap().to_string(),
|
||||
);
|
||||
log_message(format!(
|
||||
"Received a message from {} reading {} to {}",
|
||||
my_id,
|
||||
&*cv.get_data(DataTypes::content).unwrap().to_string(),
|
||||
other_id
|
||||
));
|
||||
let ack = CommunicationValue::ack_message(cv.get_id(), my_id);
|
||||
Self::send_message_static(&writer.clone(), ack.to_json().to_string())
|
||||
.await;
|
||||
|
|
@ -219,10 +206,8 @@ impl OmikronConnection {
|
|||
.to_string()
|
||||
.parse::<i64>()
|
||||
.unwrap_or(0);
|
||||
log_message(format!("A:{} O:{}, P:{}", amount, offset, partner_id));
|
||||
let messages =
|
||||
ChatFiles::get_messages(my_id, partner_id, offset, amount);
|
||||
log_message(messages.to_string());
|
||||
let resp = CommunicationValue::new(CommunicationType::messages_get)
|
||||
.with_id(cv.get_id())
|
||||
.with_receiver(my_id)
|
||||
|
|
@ -315,6 +300,7 @@ impl OmikronConnection {
|
|||
}
|
||||
Err(e) => {
|
||||
log_message(format!("[Omikron] Error: {}", e));
|
||||
*is_connected.lock().await = false;
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
|
|
@ -334,14 +320,11 @@ impl OmikronConnection {
|
|||
>,
|
||||
>,
|
||||
msg: String,
|
||||
) -> Result<(), tokio_tungstenite::tungstenite::Error> {
|
||||
) {
|
||||
let mut guard = writer.lock().await;
|
||||
if let Some(writer) = guard.as_mut() {
|
||||
writer.send(Message::Text(msg)).await?;
|
||||
writer.flush().await?;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(tokio_tungstenite::tungstenite::Error::ConnectionClosed)
|
||||
writer.send(Message::Text(msg)).await;
|
||||
writer.flush().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,25 +1,8 @@
|
|||
use crate::APP_STATE;
|
||||
use crate::data::communication::{CommunicationType, CommunicationValue, DataTypes};
|
||||
use crate::gui::log_panel::{log_message, log_message_trans};
|
||||
use crate::omikron::omikron_connection::OmikronConnection;
|
||||
use crate::users::contact::Contact;
|
||||
use crate::users::user_community_util::UserCommunityUtil;
|
||||
use crate::util::chat_files::ChatFiles;
|
||||
use crate::util::chats_util::{get_user, get_users, mod_user};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use json::JsonValue;
|
||||
use json::number::Number;
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Deref;
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::time::{Duration, Instant, sleep};
|
||||
use tokio_tungstenite::{
|
||||
MaybeTlsStream, WebSocketStream, connect_async, tungstenite::protocol::Message,
|
||||
};
|
||||
use tokio::time::Instant;
|
||||
use uuid::Uuid;
|
||||
|
||||
impl OmikronConnection {
|
||||
|
|
|
|||
Loading…
Reference in a new issue