Split #3

Merged
alex merged 9 commits from Split into main 2026-04-07 23:28:04 +03:00
49 changed files with 869 additions and 289 deletions
Showing only changes of commit 1ea0b97f6d - Show all commits
Alex Emmet 2026-04-05 00:03:19 +02:00

83
Cargo.lock generated
View file

@ -847,53 +847,6 @@ version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea" checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea"
[[package]]
name = "decentralized"
version = "0.1.0"
dependencies = [
"actix-web",
"actix-web-actors",
"aes-gcm",
"async-trait",
"base64",
"chrono",
"crossterm",
"dashmap",
"futures",
"futures-util",
"hex",
"hkdf",
"hyper",
"hyper-util",
"json",
"lazy_static",
"once_cell",
"open",
"pnet",
"rand 0.8.5",
"rand_core 0.6.4",
"ratatui",
"reqwest",
"rusqlite",
"rustls",
"rustls-pemfile",
"serde_json",
"sha2",
"strum 0.27.2",
"strum_macros 0.27.2",
"sysinfo",
"tokio",
"tokio-tungstenite",
"ttp-core",
"ttp-native",
"tungstenite",
"uuid",
"walkdir",
"warp",
"x448",
"zip",
]
[[package]] [[package]]
name = "deflate64" name = "deflate64"
version = "0.1.12" version = "0.1.12"
@ -1847,6 +1800,12 @@ dependencies = [
[[package]] [[package]]
name = "iota-logger" name = "iota-logger"
version = "0.1.0" version = "0.1.0"
dependencies = [
"iota-state",
"iota-util",
"ratatui",
"ttp-core",
]
[[package]] [[package]]
name = "iota-state" name = "iota-state"
@ -1868,6 +1827,9 @@ dependencies = [
"base64", "base64",
"hex", "hex",
"hkdf", "hkdf",
"iota-logger",
"iota-state",
"iota-util",
"json", "json",
"once_cell", "once_cell",
"rand 0.8.5", "rand 0.8.5",
@ -1891,6 +1853,7 @@ name = "iota-terms"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"iota-state", "iota-state",
"iota-util",
"json", "json",
"reqwest", "reqwest",
] ]
@ -1899,13 +1862,25 @@ dependencies = [
name = "iota-util" name = "iota-util"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"aes-gcm",
"base64",
"hex",
"hkdf",
"json", "json",
"once_cell",
"pnet", "pnet",
"rand_core 0.6.4",
"ratatui", "ratatui",
"reqwest", "reqwest",
"sha2",
"sysinfo",
"tokio", "tokio",
"ttp-core", "ttp-core",
"ttp-native", "ttp-native",
"uuid",
"walkdir",
"x448",
"zip",
] ]
[[package]] [[package]]
@ -2402,12 +2377,21 @@ dependencies = [
name = "omikron-connector" name = "omikron-connector"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"base64",
"dashmap", "dashmap",
"hex",
"iota-logger",
"iota-state",
"iota-storage",
"iota-util",
"json", "json",
"rand_core 0.6.4",
"sha2",
"tokio", "tokio",
"ttp-core", "ttp-core",
"ttp-native", "ttp-native",
"uuid", "uuid",
"x448",
] ]
[[package]] [[package]]
@ -4403,8 +4387,13 @@ dependencies = [
"hkdf", "hkdf",
"hyper", "hyper",
"hyper-util", "hyper-util",
"iota-logger",
"iota-state",
"iota-storage",
"iota-util",
"json", "json",
"lazy_static", "lazy_static",
"omikron-connector",
"once_cell", "once_cell",
"open", "open",
"pnet", "pnet",

View file

@ -1,2 +1,2 @@
[workspace] [workspace]
members = ["iota-storage", "iota-terms", "iota-state", "iota-cli", "iota-core", "omikron-connector", "web-server", "web-ui", "decentralized", "iota-logger"] members = ["iota-storage", "iota-terms", "iota-state", "iota-cli", "iota-core", "omikron-connector", "web-server", "web-ui", "iota-logger", "iota-util"]

View file

@ -0,0 +1,2 @@
pub mod communities;
pub mod local_auth;

View file

@ -1,6 +1,6 @@
use json::JsonValue; use json::JsonValue;
use crate::util::file_util::load_file; use iota_iota_util::file_util::load_file;
// NOT USED AT MOMENT // NOT USED AT MOMENT
pub fn is_private_key_valid(user_id: &i64, key_hash: &str) -> bool { pub fn is_private_key_valid(user_id: &i64, key_hash: &str) -> bool {
let file_contents = load_file("", "users.json"); let file_contents = load_file("", "users.json");

View file

@ -6,6 +6,10 @@ edition = "2024"
[dependencies] [dependencies]
ttp-core = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-core" } ttp-core = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-core" }
ttp-native = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-native" } ttp-native = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-native" }
iota-logger = { path = "../iota-logger" }
iota-util = { path = "../iota-util" }
iota-storage = { path = "../iota-storage" }
iota-state = { path = "../iota-state" }
actix-web = { version = "4", features = ["rustls-0_23"] } actix-web = { version = "4", features = ["rustls-0_23"] }
actix-web-actors = "4" actix-web-actors = "4"

View file

@ -1,4 +1,9 @@
use crossterm::event::{KeyCode, KeyEvent}; use crossterm::event::{KeyCode, KeyEvent};
use iota_logger::{log, log_command, log_cv};
use iota_state::{ACTIVE_TASKS, RELOAD, SHUTDOWN};
use iota_storage::users::{user_manager, user_profile::UserProfile};
use iota_util::file_util;
use omikron_connector::omikron_connection::OMIKRON_CONNECTION;
use ratatui::{ use ratatui::{
Frame, Frame,
layout::Rect, layout::Rect,
@ -9,19 +14,6 @@ use ratatui::{
use ttp_core::{CommunicationType, CommunicationValue}; use ttp_core::{CommunicationType, CommunicationValue};
use uuid::Uuid; use uuid::Uuid;
use crate::{
ACTIVE_TASKS, RELOAD, SHUTDOWN,
gui::{
elements::elements::{Element, InteractableElement, JoinableElement},
interaction_result::InteractionResult,
ui::FPS,
util::borders::draw_block_joins,
},
log, log_command, log_cv,
omikron::omikron_connection::OMIKRON_CONNECTION,
users::{user_manager, user_profile::UserProfile},
util::file_util,
};
use std::{ use std::{
any::Any, any::Any,
sync::{Arc, Mutex}, sync::{Arc, Mutex},
@ -29,6 +21,13 @@ use std::{
}; };
use tokio::time::Instant; use tokio::time::Instant;
use crate::{
elements::elements::{Element, InteractableElement, JoinableElement},
interaction_result::InteractionResult,
ui::FPS,
util::borders::draw_block_joins,
};
pub struct ConsoleCard { pub struct ConsoleCard {
focused: bool, focused: bool,
pub title: String, pub title: String,
@ -425,7 +424,8 @@ pub async fn run_command(command: &str) {
ping(time).await; ping(time).await;
} }
["user", "add", username] => { ["user", "add", username] => {
if let (Some(user), Some(_)) = user_manager::create_user(username).await { if let (Some(user), Some(_)) = omikron_connector::user_ops::create_user(username).await
{
log!("Created user {}", user.user_id); log!("Created user {}", user.user_id);
} else { } else {
log!("Failed to create user"); log!("Failed to create user");

View file

@ -3,7 +3,7 @@ use std::any::Any;
use crossterm::event::KeyEvent; use crossterm::event::KeyEvent;
use ratatui::{Frame, layout::Rect, widgets::Borders}; use ratatui::{Frame, layout::Rect, widgets::Borders};
use crate::gui::{interaction_result::InteractionResult, screens::screens::Screen}; use crate::{interaction_result::InteractionResult, screens::screens::Screen};
#[allow(unused)] #[allow(unused)]
pub trait Element: Send + Sync + Any { pub trait Element: Send + Sync + Any {

View file

@ -1,6 +1,7 @@
use std::{any::Any, sync::Arc}; use std::{any::Any, sync::Arc};
use crossterm::event::KeyEvent; use crossterm::event::KeyEvent;
use iota_state::APP_STATE;
use ratatui::{ use ratatui::{
Frame, Frame,
layout::Rect, layout::Rect,
@ -12,13 +13,10 @@ use ratatui::{
}; };
use crate::{ use crate::{
APP_STATE, elements::elements::{Element, InteractableElement, JoinableElement},
gui::{ interaction_result::InteractionResult,
elements::elements::{Element, InteractableElement, JoinableElement}, ui::UI,
interaction_result::InteractionResult, util::borders::draw_block_joins,
ui::UI,
util::borders::draw_block_joins,
},
}; };
pub enum GRAPHS { pub enum GRAPHS {

View file

@ -1,9 +1,9 @@
use crate::APP_STATE; use crate::app_state::APP_STATE;
use crate::gui::elements::elements::{Element, InteractableElement, JoinableElement}; use crate::elements::elements::{Element, InteractableElement, JoinableElement};
use crate::gui::interaction_result::InteractionResult; use crate::interaction_result::InteractionResult;
use crate::gui::util::borders::draw_block_joins; use crate::util::borders::draw_block_joins;
use crate::util::logger::PrintType;
use crossterm::event::{KeyCode, KeyEvent}; use crossterm::event::{KeyCode, KeyEvent};
use iota_logger::PrintType;
use ratatui::{ use ratatui::{
Frame, Frame,
layout::Rect, layout::Rect,
@ -90,7 +90,24 @@ impl LogCard {
fn get_logs(&self) -> Vec<UiLogEntry> { fn get_logs(&self) -> Vec<UiLogEntry> {
let state = APP_STATE.lock().unwrap(); let state = APP_STATE.lock().unwrap();
state.get_logs().iter().cloned().collect() state
.get_logs()
.iter()
.map(|e| UiLogEntry {
timestamp_ms: e.timestamp_ms,
sender: match e.sender.as_str() {
"Call" => PrintType::Call,
"Client" => PrintType::Client,
"Iota" => PrintType::Iota,
"Omikron" => PrintType::Omikron,
"Omega" => PrintType::Omega,
"Command" => PrintType::Command,
_ => PrintType::General,
},
message: e.message.clone(),
is_error: e.is_error,
})
.collect()
} }
fn find_split_point(s: &str, max_width: usize) -> usize { fn find_split_point(s: &str, max_width: usize) -> usize {

View file

@ -1,6 +1,6 @@
use crate::ui::{UI, UNIQUE}; use crate::ui::UI;
use crate::{RELOAD, SHUTDOWN};
use crossterm::event::{Event, KeyEvent, KeyEventKind, KeyModifiers, poll, read}; use crossterm::event::{Event, KeyEvent, KeyEventKind, KeyModifiers, poll, read};
use iota_state::{RELOAD, SHUTDOWN, UNIQUE};
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::Ordering; use std::sync::atomic::Ordering;
use std::time::Duration; use std::time::Duration;

View file

@ -2,8 +2,13 @@ use crate::{
interaction_result::InteractionResult, interaction_result::InteractionResult,
screens::{md_viewer::FileViewer, screens::Screen}, screens::{md_viewer::FileViewer, screens::Screen},
ui::UI, ui::UI,
util::{
buttons::{checkbox, draw_buttons},
terms_focus::Focus,
},
}; };
use crossterm::event::{KeyCode, KeyEvent}; use crossterm::event::{KeyCode, KeyEvent};
use iota_terms::{TermsType, get_link, get_terms};
use ratatui::{ use ratatui::{
Frame, Frame,
layout::{Alignment, Constraint, Direction, Layout, Rect}, layout::{Alignment, Constraint, Direction, Layout, Rect},
@ -14,6 +19,13 @@ use ratatui::{
use std::{any::Any, pin::Pin, sync::Arc}; use std::{any::Any, pin::Pin, sync::Arc};
use tokio::sync::oneshot; use tokio::sync::oneshot;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UserChoice {
Deny,
AcceptEULA,
AcceptAll,
}
pub struct TermsCheckerScreen { pub struct TermsCheckerScreen {
ui: Arc<UI>, ui: Arc<UI>,
sender: Option<oneshot::Sender<UserChoice>>, sender: Option<oneshot::Sender<UserChoice>>,
@ -268,9 +280,9 @@ impl Screen for TermsCheckerScreen {
} }
KeyCode::Char('o') | KeyCode::Char('O') => { KeyCode::Char('o') | KeyCode::Char('O') => {
let terms_type = match self.focus { let terms_type = match self.focus {
Focus::Eula => Some(Type::EULA), Focus::Eula => Some(TermsType::EULA),
Focus::Tos => Some(Type::TOS), Focus::Tos => Some(TermsType::TOS),
Focus::Pp => Some(Type::PP), Focus::Pp => Some(TermsType::PP),
_ => None, _ => None,
}; };
if let Some(terms_type) = terms_type { if let Some(terms_type) = terms_type {
@ -288,15 +300,15 @@ impl Screen for TermsCheckerScreen {
} }
KeyCode::Char('l') | KeyCode::Char('L') => match self.focus { KeyCode::Char('l') | KeyCode::Char('L') => match self.focus {
Focus::Eula => { Focus::Eula => {
let _ = open::that(get_link(Type::EULA)); let _ = open::that(get_link(TermsType::EULA));
InteractionResult::Handled InteractionResult::Handled
} }
Focus::Tos => { Focus::Tos => {
let _ = open::that(get_link(Type::TOS)); let _ = open::that(get_link(TermsType::TOS));
InteractionResult::Handled InteractionResult::Handled
} }
Focus::Pp => { Focus::Pp => {
let _ = open::that(get_link(Type::PP)); let _ = open::that(get_link(TermsType::PP));
InteractionResult::Handled InteractionResult::Handled
} }
_ => InteractionResult::Unhandled, _ => InteractionResult::Unhandled,

View file

@ -1,9 +1,15 @@
use crate::screens::terms_checker::UserChoice;
use crate::{ use crate::{
interaction_result::InteractionResult, interaction_result::InteractionResult,
screens::{md_viewer::FileViewer, screens::Screen}, screens::{md_viewer::FileViewer, screens::Screen},
util::{
buttons::{checkbox, draw_buttons},
terms_focus::Focus,
},
}; };
use chrono::{Local, TimeZone, Utc}; use chrono::{Local, TimeZone, Utc};
use crossterm::event::{KeyCode, KeyEvent}; use crossterm::event::{KeyCode, KeyEvent};
use iota_terms::{Doc, TermsType, get_newest_link, get_terms};
use ratatui::{ use ratatui::{
Frame, Frame,
layout::{Alignment, Constraint, Direction, Layout, Rect}, layout::{Alignment, Constraint, Direction, Layout, Rect},
@ -14,6 +20,13 @@ use ratatui::{
use std::any::Any; use std::any::Any;
use tokio::sync::oneshot; use tokio::sync::oneshot;
#[derive(Debug, Clone)]
pub enum UpdateDecision {
NoChange,
Future { newest: Doc },
Forced(Doc),
}
pub struct TermsUpdaterScreen { pub struct TermsUpdaterScreen {
sender: Option<oneshot::Sender<UserChoice>>, sender: Option<oneshot::Sender<UserChoice>>,
@ -635,9 +648,9 @@ impl Screen for TermsUpdaterScreen {
}, },
KeyCode::Char('o') | KeyCode::Char('O') => { KeyCode::Char('o') | KeyCode::Char('O') => {
let terms_type = match self.focus { let terms_type = match self.focus {
Focus::Eula => Some(Type::EULA), Focus::Eula => Some(TermsType::EULA),
Focus::Tos => Some(Type::TOS), Focus::Tos => Some(TermsType::TOS),
Focus::Pp => Some(Type::PP), Focus::Pp => Some(TermsType::PP),
_ => None, _ => None,
}; };
@ -655,15 +668,15 @@ impl Screen for TermsUpdaterScreen {
} }
KeyCode::Char('l') | KeyCode::Char('L') => match self.focus { KeyCode::Char('l') | KeyCode::Char('L') => match self.focus {
Focus::Eula => { Focus::Eula => {
let _ = open::that(get_newest_link(Type::EULA)); let _ = open::that(get_newest_link(TermsType::EULA));
InteractionResult::Handled InteractionResult::Handled
} }
Focus::Tos => { Focus::Tos => {
let _ = open::that(get_newest_link(Type::TOS)); let _ = open::that(get_newest_link(TermsType::TOS));
InteractionResult::Handled InteractionResult::Handled
} }
Focus::Pp => { Focus::Pp => {
let _ = open::that(get_newest_link(Type::PP)); let _ = open::that(get_newest_link(TermsType::PP));
InteractionResult::Handled InteractionResult::Handled
} }
_ => InteractionResult::Unhandled, _ => InteractionResult::Unhandled,

View file

@ -3,6 +3,7 @@ use crate::{
screens::screens::Screen, screens::screens::Screen,
}; };
use crossterm::event::KeyEvent; use crossterm::event::KeyEvent;
use iota_state::{ACTIVE_TASKS, SHUTDOWN, UNIQUE};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use ratatui::{Terminal, backend::CrosstermBackend, init}; use ratatui::{Terminal, backend::CrosstermBackend, init};
use std::{ use std::{
@ -17,7 +18,6 @@ use std::{
use tokio::{sync::RwLock, time::Instant}; use tokio::{sync::RwLock, time::Instant};
/// UI state and rendering /// UI state and rendering
pub static UNIQUE: AtomicBool = AtomicBool::new(true);
pub static FPS: Lazy<RwLock<(f64, f64)>> = Lazy::new(|| RwLock::new((0.0, 0.0))); pub static FPS: Lazy<RwLock<(f64, f64)>> = Lazy::new(|| RwLock::new((0.0, 0.0)));

View file

@ -0,0 +1,473 @@
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::oneshot;
use iota_cli::ui::UI;
use iota_cli::screens::terms_checker::{TermsCheckerScreen, UserChoice};
use iota_cli::screens::terms_updater::{TermsUpdaterScreen, UpdateDecision};
use iota_terms::{Doc, get_current_docs, get_newest_docs, TermsType as Type};
use iota_util::file_util::{load_file, save_file};
pub async fn check(ui: Arc<UI>) -> (bool, bool) {
let mut state = ConsentState::load_state();
if ensure_initial_consent(ui.clone(), &mut state)
.await
.is_err()
{
return (false, false);
}
if ensure_updates(ui, &mut state).await.is_err() {
return (false, false);
};
state = state.sanitize();
state.save_state();
(state.accepted_eula, state.accepted_tos && state.accepted_pp)
}
async fn ensure_initial_consent(ui: Arc<UI>, state: &mut ConsentState) -> Result<(), ()> {
if state.accepted_eula {
return Ok(());
}
let (tx, rx) = oneshot::channel();
ui.set_screen(Box::new(TermsCheckerScreen::new(ui.clone(), Some(tx))))
.await;
let result = rx.await.unwrap_or(UserChoice::Deny);
match result {
UserChoice::AcceptEULA | UserChoice::AcceptAll => {
if let Some((eula, tos, privacy)) = get_current_docs().await {
state.accepted_eula = true;
state.eula = Some(eula);
if matches!(result, UserChoice::AcceptAll) {
state.accepted_tos = true;
state.accepted_pp = true;
state.tos = Some(tos);
state.privacy = Some(privacy);
}
}
let _ = &state.save_state();
Ok(())
}
UserChoice::Deny => Err(()),
}
}
async fn ensure_updates(ui: Arc<UI>, state: &mut ConsentState) -> Result<(), ()> {
let Some((eula_update, tos_update, privacy_update)) = get_updates().await else {
return Ok(());
};
let is_forced = matches!(eula_update, UpdateDecision::Forced(_))
|| matches!(tos_update, UpdateDecision::Forced(_))
|| matches!(privacy_update, UpdateDecision::Forced(_));
let (tx, rx) = oneshot::channel();
ui.set_screen(Box::new(TermsUpdaterScreen::new(
eula_update.clone(),
tos_update.clone(),
privacy_update.clone(),
Some(tx),
)))
.await;
let result = rx.await.unwrap_or(UserChoice::Deny);
if is_forced {
match result {
UserChoice::AcceptAll => {
state.accepted_eula = true;
state.accepted_tos = true;
state.accepted_pp = true;
}
UserChoice::AcceptEULA => {
state.accepted_eula = true;
}
UserChoice::Deny => return Err(()),
}
} else {
apply_future_updates(state, result, eula_update, tos_update, privacy_update);
}
state.save_state();
Ok(())
}
fn apply_future_updates(
state: &mut ConsentState,
result: UserChoice,
eula_update: UpdateDecision,
tos_update: UpdateDecision,
privacy_update: UpdateDecision,
) {
match result {
UserChoice::AcceptAll => {
if let UpdateDecision::Future { newest } = eula_update {
state.future_eula = Some(newest);
}
if let UpdateDecision::Future { newest } = tos_update {
state.future_tos = Some(newest);
}
if let UpdateDecision::Future { newest } = privacy_update {
state.future_privacy = Some(newest);
}
}
UserChoice::AcceptEULA => {
if let UpdateDecision::Future { newest } = eula_update {
state.future_eula = Some(newest);
}
}
UserChoice::Deny => {}
}
}
async fn get_updates() -> Option<(
// Ok(None) indicates no update
// Ok(Some) Indicates a future update
// Err indicates a update that has to be accepted before the programm can continue
UpdateDecision,
UpdateDecision,
UpdateDecision,
)> {
if let (
Some((current_eula, current_tos, current_privacy)),
Some((newest_eula, newest_tos, newest_privacy)),
) = (get_current_docs().await, get_newest_docs().await)
{
let file = load_file("", "agreements");
let accepted_state = ConsentState::from_str(&file).sanitize();
save_file("", "agreements", &accepted_state.to_string());
let eula_update: UpdateDecision = if current_eula.equals_some(&accepted_state.eula) {
if current_eula.equals(&newest_eula) {
UpdateDecision::NoChange
} else {
if newest_eula.equals_some(&accepted_state.future_eula) {
UpdateDecision::NoChange
} else {
UpdateDecision::Future {
newest: newest_eula,
}
}
}
} else if newest_eula.equals_some(&accepted_state.eula) {
UpdateDecision::NoChange
} else {
UpdateDecision::Forced(current_eula)
};
let tos_update: UpdateDecision =
if !accepted_state.accepted_tos || newest_tos.equals_some(&accepted_state.tos) {
UpdateDecision::NoChange
} else if accepted_state.accepted_tos && current_tos.equals_some(&accepted_state.tos) {
if current_tos.equals(&newest_tos) {
UpdateDecision::NoChange
} else {
if newest_tos.equals_some(&accepted_state.future_tos) {
UpdateDecision::NoChange
} else {
UpdateDecision::Future { newest: newest_tos }
}
}
} else {
UpdateDecision::Forced(current_tos)
};
let privacy_update: UpdateDecision = if !accepted_state.accepted_pp
|| newest_privacy.equals_some(&accepted_state.privacy)
{
UpdateDecision::NoChange
} else if accepted_state.accepted_pp && current_privacy.equals_some(&accepted_state.privacy)
{
if current_privacy.equals(&newest_privacy) {
UpdateDecision::NoChange
} else {
if newest_privacy.equals_some(&accepted_state.future_privacy) {
UpdateDecision::NoChange
} else {
UpdateDecision::Future {
newest: newest_privacy,
}
}
}
} else {
UpdateDecision::Forced(current_privacy)
};
match (&eula_update, &tos_update, &privacy_update) {
(&UpdateDecision::NoChange, &UpdateDecision::NoChange, &UpdateDecision::NoChange) => {
None
}
_ => Some((eula_update, tos_update, privacy_update)),
}
} else {
None
}
}
#[derive(Debug, Clone)]
pub struct ConsentState {
pub eula: Option<Doc>,
pub accepted_eula: bool,
pub future_eula: Option<Doc>,
pub tos: Option<Doc>,
pub accepted_tos: bool,
pub future_tos: Option<Doc>,
pub privacy: Option<Doc>,
pub accepted_pp: bool,
pub future_privacy: Option<Doc>,
}
impl ConsentState {
fn sanitize(mut self) -> Self {
let current_secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
if let Some(future_eula) = self.future_eula.clone() {
if future_eula.get_time() < current_secs {
self.eula = Some(future_eula);
self.future_eula = None;
}
}
if let Some(future_tos) = self.future_tos.clone() {
if future_tos.get_time() < current_secs {
self.tos = Some(future_tos);
self.future_tos = None;
}
}
if let Some(future_privacy) = self.future_privacy.clone() {
if future_privacy.get_time() < current_secs {
self.privacy = Some(future_privacy);
self.future_privacy = None;
}
}
if !self.accepted_eula {
self.accepted_tos = false;
self.accepted_pp = false;
}
self
}
pub fn load_state() -> ConsentState {
let file = load_file("", "agreements");
ConsentState::from_str(&file).sanitize()
}
pub fn save_state(&self) {
save_file("", "agreements", &self.to_string());
}
fn to_string(&self) -> String {
let current_secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let mut file_out: String = format!(
"This file reflects the current consent state used by the application.\
\nIt may be regenerated or overwritten by the application.\
\nThis file was last edited by Tensamin at:\
\nUNIX-SECOND={}",
current_secs
);
if let Some(eula) = &self.eula {
file_out.push_str(&format!("\
\n\"EULA=true\" indicates that you read, understood and accepted Tensamin's End User Licence agreement. You can find our EULA at https://legal.tensamin.net/eula/\
\nEULA={}\
\nEULA-VERSION={}\
\nEULA-HASH={}\
", self.accepted_eula, eula.get_version(), eula.get_hash()));
if self.accepted_tos
&& let Some(tos) = &self.tos
{
file_out.push_str(&format!("\
\n\"Terms-of-Service=true\" indicates that you read, understood and accepted Tensamin's Terms of Service. You can find our Terms of Serivce at https://legal.tensamin.net/tos/\
\nTerms-of-Service={}\
\nTerms-of-Service-VERSION={}\
\nTerms-of-Service-HASH={}\
", self.accepted_tos, tos.get_version(), tos.get_hash()));
}
if self.accepted_pp
&& let Some(pp) = &self.privacy
{
file_out.push_str(&format!("\
\n\"Privacy-Policy=true\" indicates that you read, understood and accepted Tensamin's Privacy Policy. You can find our Privacy Policy at https://legal.tensamin.net/privacy/\
\nPrivacy-Policy={}\
\nPrivacy-Policy-VERSION={}\
\nPrivacy-Policy-HASH={}\
", self.accepted_pp, pp.get_version(), pp.get_hash()));
}
} else {
file_out.push_str("\
\n\"EULA=true\" indicates that you read, understood and accepted Tensamin's End User Licence Agreement. You can find Tensamin's EULA at https://legal.tensamin.net/eula/\
\nEULA=false\
");
}
if let Some(eula) = &self.future_eula {
file_out.push_str(&format!(
"\
\nFUTURE-EULA-VERSION={}\
\nFUTURE-EULA-HASH={}\
\nFUTURE-EULA-TIME={}\
",
eula.get_version(),
eula.get_hash(),
eula.get_time()
));
}
if let Some(tos) = &self.future_tos {
file_out.push_str(&format!(
"\
\nFUTURE-Terms-of-Service-VERSION={}\
\nFUTURE-Terms-of-Service-HASH={}\
\nFUTURE-Terms-of-Service-TIME={}\
",
tos.get_version(),
tos.get_hash(),
tos.get_time()
));
}
if let Some(pp) = &self.future_privacy {
file_out.push_str(&format!(
"\
\nFUTURE-Privacy-Policy-VERSION={}\
\nFUTURE-Privacy-Policy-HASH={}\
\nFUTURE-Privacy-Policy-TIME={}\
",
pp.get_version(),
pp.get_hash(),
pp.get_time()
));
}
file_out
}
fn from_str(s: &str) -> Self {
let mut eula = false;
let mut eula_version = String::new();
let mut eula_hash = String::new();
let mut pp = false;
let mut pp_version = String::new();
let mut pp_hash = String::new();
let mut tos = false;
let mut tos_version = String::new();
let mut tos_hash = String::new();
let mut future_eula_version = String::new();
let mut future_eula_hash = String::new();
let mut future_eula_time = String::new();
let mut future_tos_version = String::new();
let mut future_tos_hash = String::new();
let mut future_tos_time = String::new();
let mut future_pp_version = String::new();
let mut future_pp_hash = String::new();
let mut future_pp_time = String::new();
let mut unix = String::new();
for line in s.lines() {
if let Some(v) = line.strip_prefix("EULA=") {
eula = v == "true";
} else if let Some(v) = line.strip_prefix("EULA-VERSION=") {
eula_version = v.to_string();
} else if let Some(v) = line.strip_prefix("EULA-HASH=") {
eula_hash = v.to_string();
} else if let Some(v) = line.strip_prefix("Terms-of-Service=") {
tos = v == "true";
} else if let Some(v) = line.strip_prefix("Terms-of-Service-VERSION=") {
tos_version = v.to_string();
} else if let Some(v) = line.strip_prefix("Terms-of-Service-HASH=") {
tos_hash = v.to_string();
} else if let Some(v) = line.strip_prefix("Privacy-Policy=") {
pp = v == "true";
} else if let Some(v) = line.strip_prefix("Privacy-Policy-VERSION=") {
pp_version = v.to_string();
} else if let Some(v) = line.strip_prefix("Privacy-Policy-HASH=") {
pp_hash = v.to_string();
} else if let Some(v) = line.strip_prefix("UNIX-SECOND=") {
unix = v.to_string();
} else if let Some(v) = line.strip_prefix("FUTURE-EULA-VERSION=") {
future_eula_version = v.to_string();
} else if let Some(v) = line.strip_prefix("FUTURE-EULA-HASH=") {
future_eula_hash = v.to_string();
} else if let Some(v) = line.strip_prefix("FUTURE-EULA-TIME=") {
future_eula_time = v.to_string();
} else if let Some(v) = line.strip_prefix("FUTURE-Terms-of-Service-VERSION=") {
future_tos_version = v.to_string();
} else if let Some(v) = line.strip_prefix("FUTURE-Terms-of-Service-HASH=") {
future_tos_hash = v.to_string();
} else if let Some(v) = line.strip_prefix("FUTURE-Terms-of-Service-TIME=") {
future_tos_time = v.to_string();
} else if let Some(v) = line.strip_prefix("FUTURE-Privacy-Policy-VERSION=") {
future_pp_version = v.to_string();
} else if let Some(v) = line.strip_prefix("FUTURE-Privacy-Policy-HASH=") {
future_pp_hash = v.to_string();
} else if let Some(v) = line.strip_prefix("FUTURE-Privacy-Policy-TIME=") {
future_pp_time = v.to_string();
}
}
let unix: u64 = unix.parse::<u64>().unwrap_or(0);
let future_eula_time = future_eula_time.parse::<u64>().unwrap_or(0);
let future_tos_time = future_tos_time.parse::<u64>().unwrap_or(0);
let future_pp_time = future_pp_time.parse::<u64>().unwrap_or(0);
let state = Self {
accepted_eula: eula,
eula: Some(Doc::new(eula_version, eula_hash, Type::EULA, unix)),
accepted_pp: pp,
privacy: Some(Doc::new(pp_version, pp_hash, Type::PP, unix)),
accepted_tos: tos,
tos: Some(Doc::new(tos_version, tos_hash, Type::TOS, unix)),
future_eula: if !future_eula_version.is_empty() {
Some(Doc::new(
future_eula_version,
future_eula_hash,
Type::EULA,
future_eula_time,
))
} else {
None
},
future_tos: if !future_tos_version.is_empty() {
Some(Doc::new(
future_tos_version,
future_tos_hash,
Type::TOS,
future_tos_time,
))
} else {
None
},
future_privacy: if !future_pp_version.is_empty() {
Some(Doc::new(
future_pp_version,
future_pp_hash,
Type::PP,
future_pp_time,
))
} else {
None
},
}
.sanitize();
state
}
}

View file

@ -1,8 +1,19 @@
mod consent_state;
use pnet::datalink::NetworkInterface; use pnet::datalink::NetworkInterface;
use tokio::time::{Duration, sleep}; use tokio::time::{Duration, sleep};
use iota_state::{ACTIVE_TASKS, APP_STATE, AppState, RELOAD, SHUTDOWN}; use iota_state::{ACTIVE_TASKS, APP_STATE, AppState, RELOAD, SHUTDOWN};
use iota_cli::screens::main_screen::MainScreen;
use iota_cli::ui::start_tui;
use iota_logger as logger;
use iota_logger::{log, log_t};
use iota_storage::users::user_manager;
use iota_storage::util::config_util::CONFIG;
use iota_util::file_util::{download_and_extract_zip, has_dir};
use iota_util::langu::language_creator;
use omikron_connector as omikron;
#[tokio::main(flavor = "multi_thread", worker_threads = 16)] #[tokio::main(flavor = "multi_thread", worker_threads = 16)]
#[allow(unused_must_use, dead_code)] #[allow(unused_must_use, dead_code)]
async fn main() { async fn main() {

View file

@ -4,3 +4,7 @@ version = "0.1.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
ratatui = "0.30.0"
ttp-core = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-core" }
iota-state = { path = "../iota-state" }
iota-util = { path = "../iota-util" }

View file

@ -11,11 +11,8 @@ use std::{
use ratatui::style::Color; use ratatui::style::Color;
use ttp_core::{CommunicationValue, DataTypes, DataValue}; use ttp_core::{CommunicationValue, DataTypes, DataValue};
use crate::{ use iota_state::{APP_STATE, UNIQUE, UiLogEntry};
APP_STATE, use iota_util::langu::language_manager;
gui::{elements::log_card::LogEntry, ui::UNIQUE},
langu::language_manager,
};
static LOGGER: OnceLock<mpsc::Sender<LogMessage>> = OnceLock::new(); static LOGGER: OnceLock<mpsc::Sender<LogMessage>> = OnceLock::new();
@ -83,7 +80,6 @@ pub fn startup() {
}; };
let timestamp = format_timestamp_inline(msg.timestamp_ms); let timestamp = format_timestamp_inline(msg.timestamp_ms);
let entry = LogEntry::new(msg.kind, resolved_message, msg.is_error);
let prefix = if msg.prefix.is_empty() { let prefix = if msg.prefix.is_empty() {
String::new() String::new()
@ -96,13 +92,20 @@ pub fn startup() {
"{} {}{}", "{} {}{}",
fixed_box(&msg.timestamp_ms.to_string(), 13), fixed_box(&msg.timestamp_ms.to_string(), 13),
prefix, prefix,
entry.message resolved_message
); );
let _ = writeln!(file, " {}", timestamp); let _ = writeln!(file, " {}", timestamp);
let entry = UiLogEntry {
timestamp_ms: msg.timestamp_ms,
sender: format!("{:?}", msg.kind),
message: resolved_message,
is_error: msg.is_error,
};
let mut state = APP_STATE.lock().unwrap(); let mut state = APP_STATE.lock().unwrap();
state.push_log(entry.into()); state.push_log(entry);
} }
}); });
} }
@ -186,8 +189,8 @@ pub fn log_internal(kind: PrintType, prefix: String, is_error: bool, message: St
#[macro_export] #[macro_export]
macro_rules! log_t { macro_rules! log_t {
($key:expr) => { ($key:expr) => {
$crate::util::logger::log_internal_translated( $crate::log_internal_translated(
$crate::util::logger::PrintType::General, $crate::PrintType::General,
"".to_string(), "".to_string(),
false, false,
$key, $key,
@ -196,8 +199,8 @@ macro_rules! log_t {
}; };
($key:expr, $($arg:expr),+) => { ($key:expr, $($arg:expr),+) => {
$crate::util::logger::log_internal_translated( $crate::log_internal_translated(
$crate::util::logger::PrintType::General, $crate::PrintType::General,
"".to_string(), "".to_string(),
false, false,
$key, $key,
@ -209,8 +212,8 @@ macro_rules! log_t {
#[macro_export] #[macro_export]
macro_rules! log_t_err { macro_rules! log_t_err {
($key:expr) => { ($key:expr) => {
$crate::util::logger::log_internal_translated( $crate::log_internal_translated(
$crate::util::logger::PrintType::General, $crate::PrintType::General,
"".to_string(), "".to_string(),
true, true,
$key, $key,
@ -219,8 +222,8 @@ macro_rules! log_t_err {
}; };
($key:expr, $($arg:expr),+) => { ($key:expr, $($arg:expr),+) => {
$crate::util::logger::log_internal_translated( $crate::log_internal_translated(
$crate::util::logger::PrintType::General, $crate::PrintType::General,
"".to_string(), "".to_string(),
true, true,
$key, $key,
@ -233,8 +236,8 @@ macro_rules! log_t_err {
#[macro_export] #[macro_export]
macro_rules! log_command { macro_rules! log_command {
($($arg:tt)*) => { ($($arg:tt)*) => {
$crate::util::logger::log_internal( $crate::log_internal(
$crate::util::logger::PrintType::Command, $crate::PrintType::Command,
"".to_string(), "".to_string(),
false, false,
format!($($arg)*) format!($($arg)*)
@ -246,8 +249,8 @@ macro_rules! log_command {
#[macro_export] #[macro_export]
macro_rules! log { macro_rules! log {
($($arg:tt)*) => { ($($arg:tt)*) => {
$crate::util::logger::log_internal( $crate::log_internal(
$crate::util::logger::PrintType::General, $crate::PrintType::General,
"".to_string(), "".to_string(),
false, false,
format!($($arg)*) format!($($arg)*)
@ -259,8 +262,8 @@ macro_rules! log {
#[macro_export] #[macro_export]
macro_rules! log_in { macro_rules! log_in {
($($arg:tt)*) => { ($($arg:tt)*) => {
$crate::util::logger::log_internal( $crate::log_internal(
$crate::util::logger::PrintType::General, $crate::PrintType::General,
">".to_string(), ">".to_string(),
false, false,
format!($($arg)*) format!($($arg)*)
@ -272,8 +275,8 @@ macro_rules! log_in {
#[macro_export] #[macro_export]
macro_rules! log_out { macro_rules! log_out {
($($arg:tt)*) => { ($($arg:tt)*) => {
$crate::util::logger::log_internal( $crate::log_internal(
$crate::util::logger::PrintType::General, $crate::PrintType::General,
"<".to_string(), "<".to_string(),
false, false,
format!($($arg)*) format!($($arg)*)
@ -285,8 +288,8 @@ macro_rules! log_out {
#[macro_export] #[macro_export]
macro_rules! log_err { macro_rules! log_err {
($($arg:tt)*) => { ($($arg:tt)*) => {
$crate::util::logger::log_internal( $crate::log_internal(
$crate::util::logger::PrintType::General, $crate::PrintType::General,
">>".to_string(), ">>".to_string(),
true, true,
format!($($arg)*) format!($($arg)*)
@ -404,29 +407,29 @@ fn format_array(arr: Vec<DataValue>) -> String {
#[macro_export] #[macro_export]
macro_rules! log_cv { macro_rules! log_cv {
($kind:expr, $cv:expr) => { ($kind:expr, $cv:expr) => {
$crate::util::logger::log_cv_internal("", &$cv, Some($kind)) $crate::log_cv_internal("", &$cv, Some($kind))
}; };
($cv:expr) => { ($cv:expr) => {
$crate::util::logger::log_cv_internal("", &$cv, None) $crate::log_cv_internal("", &$cv, None)
}; };
} }
#[macro_export] #[macro_export]
macro_rules! log_cv_in { macro_rules! log_cv_in {
($kind:expr, $cv:expr) => { ($kind:expr, $cv:expr) => {
$crate::util::logger::log_cv_internal("> ", &$cv, Some($kind)) $crate::log_cv_internal("> ", &$cv, Some($kind))
}; };
($cv:expr) => { ($cv:expr) => {
$crate::util::logger::log_cv_internal("> ", &$cv, None) $crate::log_cv_internal("> ", &$cv, None)
}; };
} }
#[macro_export] #[macro_export]
macro_rules! log_cv_out { macro_rules! log_cv_out {
($kind:expr, $cv:expr) => { ($kind:expr, $cv:expr) => {
$crate::util::logger::log_cv_internal("< ", &$cv, Some($kind)) $crate::log_cv_internal("< ", &$cv, Some($kind))
}; };
($cv:expr) => { ($cv:expr) => {
$crate::util::logger::log_cv_internal("< ", &$cv, None) $crate::log_cv_internal("< ", &$cv, None)
}; };
} }

View file

@ -2,7 +2,7 @@ use dashmap::DashSet;
use json::{JsonValue, object}; use json::{JsonValue, object};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::sync::{Arc, LazyLock, Mutex}; use std::sync::{Arc, LazyLock, Mutex, atomic::AtomicBool};
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
use sysinfo::{RefreshKind, System}; use sysinfo::{RefreshKind, System};
@ -11,6 +11,8 @@ use tokio::sync::RwLock;
pub const MAX_POINTS: usize = 1000; pub const MAX_POINTS: usize = 1000;
pub const MAX_LOGS: usize = 100; pub const MAX_LOGS: usize = 100;
pub static UNIQUE: AtomicBool = AtomicBool::new(true);
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct UiLogEntry { pub struct UiLogEntry {
pub timestamp_ms: u128, pub timestamp_ms: u128,

View file

@ -4,6 +4,10 @@ version = "0.1.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
iota-logger = { path = "../iota-logger" }
iota-state = { path = "../iota-state" }
iota-util = { path = "../iota-util" }
ttp-core = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-core" } ttp-core = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-core" }
ttp-native = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-native" } ttp-native = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-native" }

View file

@ -1,2 +1,2 @@
mod users; pub mod users;
mod util; pub mod util;

View file

@ -1,4 +1,4 @@
use crate::util::file_util::save_file; use iota_util::file_util::save_file;
use json::{self, Array, JsonValue}; use json::{self, Array, JsonValue};
use std::fs; use std::fs;
use std::path::Path; use std::path::Path;

View file

@ -1,12 +1,9 @@
use crate::omikron::omikron_connection::OMIKRON_CONNECTION;
use crate::users::user_profile::UserProfile; use crate::users::user_profile::UserProfile;
use crate::util::crypto_helper::{self, public_key_to_base64};
use crate::util::file_util::{load_file, save_file};
use crate::util::logger::PrintType;
use crate::{RELOAD, SHUTDOWN};
use crate::{log, log_cv};
use base64::{Engine as _, engine::general_purpose::STANDARD}; use base64::{Engine as _, engine::general_purpose::STANDARD};
use hex::{self}; use hex::{self};
use iota_logger::{log, log_cv};
use iota_util::crypto_helper::{self, public_key_to_base64};
use iota_util::file_util::{load_file, save_file};
use json::JsonValue; use json::JsonValue;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use rand::Rng; use rand::Rng;
@ -48,84 +45,7 @@ pub async fn load_from_tu(username: &str) -> Result<(), ()> {
Ok(()) Ok(())
} }
pub async fn create_user(username: &str) -> (Option<UserProfile>, Option<String>) { pub fn add_user(user: UserProfile) { USERS.lock().unwrap().push(user); }
let register_cv = CommunicationValue::new(CommunicationType::get_register);
let conn = OMIKRON_CONNECTION.clone();
let response_cv = match conn
.await_response(&register_cv, Some(Duration::from_secs(20)))
.await
{
Ok(cv) => cv,
Err(_) => return (None, None),
};
log_cv!(PrintType::Omega, response_cv);
let user_id = match response_cv.get_data(DataTypes::user_id).as_number() {
Some(id) => id,
None => return (None, None),
};
let mut buf = [0u8; 56];
let mut rng = OsRng;
rng.fill_bytes(&mut buf);
let private_key = Secret::from_bytes(&buf).unwrap();
let public_key = PublicKey::from(&private_key);
let mut hasher = Sha256::new();
hasher.update(&STANDARD.encode(&private_key.as_bytes()).as_bytes());
let result = hasher.finalize();
let private_key_hash = hex::encode(result);
let mut bytes = [0u8; 192];
OsRng.fill(bytes.as_mut());
let reset_token = STANDARD.encode(&bytes);
let up = UserProfile::new(
user_id,
username.to_string(),
None,
STANDARD.encode(&public_key.as_bytes()),
private_key_hash,
reset_token.clone(),
);
let cv = CommunicationValue::new(CommunicationType::complete_register_user)
.add_data(DataTypes::user_id, DataValue::Number(user_id))
.add_data(DataTypes::username, DataValue::Str(username.to_string()))
.add_data(
DataTypes::public_key,
DataValue::Str(public_key_to_base64(&public_key)),
)
.add_data(DataTypes::iota_id, DataValue::Number(user_id))
.add_data(DataTypes::reset_token, DataValue::Str(reset_token));
let response_cv = conn
.await_response(&cv, Some(Duration::from_secs(20)))
.await;
if let Ok(resp) = response_cv {
log_cv!(PrintType::Omega, resp);
if !resp.is_type(CommunicationType::success) {
return (None, None);
}
} else {
return (None, None);
}
*SHUTDOWN.write().await = true;
*RELOAD.write().await = true;
log!("Created User");
save_file(
"",
&format!("{}.tu", username),
&format!("{}::{}", user_id, STANDARD.encode(&private_key.as_bytes())),
);
USERS.lock().unwrap().push(up.clone());
save_users();
(Some(up), Some(STANDARD.encode(&private_key.as_bytes())))
}
pub fn get_user_by_username(username: &str) -> Option<UserProfile> { pub fn get_user_by_username(username: &str) -> Option<UserProfile> {
USERS USERS
.lock() .lock()

View file

@ -1,6 +1,6 @@
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use crate::util::file_util::{has_file, load_file, used_dir_space}; use iota_util::file_util::{has_file, load_file, used_dir_space};
use base64::{Engine as _, engine::general_purpose}; use base64::{Engine as _, engine::general_purpose};
use json::{JsonValue, object}; use json::{JsonValue, object};
use rand::Rng; use rand::Rng;

View file

@ -1,5 +1,5 @@
use crate::log;
use crate::util::db; use crate::util::db;
use iota_logger::log;
use json::{JsonValue, array, object}; use json::{JsonValue, array, object};
use rusqlite::params; use rusqlite::params;
use std::io; use std::io;

View file

@ -1,4 +1,4 @@
use crate::util::file_util::{load_file, save_file}; use iota_util::file_util::{load_file, save_file};
use json::JsonValue; use json::JsonValue;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use tokio::sync::RwLock; use tokio::sync::RwLock;

View file

@ -5,7 +5,7 @@
//! reuse. The goal is to centralize the "open and initialize" logic and //! reuse. The goal is to centralize the "open and initialize" logic and
//! provide small convenience helpers used by other util modules. //! provide small convenience helpers used by other util modules.
use crate::util::file_util::get_directory; use iota_util::file_util::get_directory;
use rusqlite::{Connection, Error as RusqliteError}; use rusqlite::{Connection, Error as RusqliteError};
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};

View file

@ -2,8 +2,4 @@ pub mod chat_files;
pub mod chats_util; pub mod chats_util;
pub mod communities_util; pub mod communities_util;
pub mod config_util; pub mod config_util;
pub mod crypto_helper;
pub mod crypto_util;
pub mod db; pub mod db;
pub mod file_util;
pub mod logger;

View file

@ -5,6 +5,7 @@ edition = "2024"
[dependencies] [dependencies]
iota-state = { path = "../iota-state" } iota-state = { path = "../iota-state" }
iota-util = { path = "../iota-util" }
json = "*" json = "*"
reqwest = "0.13.2" reqwest = "0.13.2"

View file

@ -1,6 +1,7 @@
use json::{JsonValue, object::Object}; use json::{JsonValue, object::Object};
use crate::{terms::terms_getter::Type, util::file_util::load_file}; use crate::terms_getter::Type;
use iota_util::file_util::load_file;
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
#[allow(unused)] #[allow(unused)]

View file

@ -1,2 +1,14 @@
pub mod doc;
pub mod terms_getter; pub mod terms_getter;
pub use terms_getter::Type as TermsType;
pub use terms_getter::get_current_docs;
pub use terms_getter::get_link;
pub use terms_getter::get_newest_docs;
pub use terms_getter::get_newest_link;
pub use terms_getter::get_terms;
pub mod doc;
pub use doc::Doc;

View file

@ -1,6 +1,6 @@
use json::JsonValue::Object; use json::JsonValue::Object;
use crate::terms::doc::Doc; use crate::doc::Doc;
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Type { pub enum Type {

View file

@ -13,3 +13,15 @@ pnet = "0.35.0"
ratatui = "0.30.0" ratatui = "0.30.0"
reqwest = "0.13.2" reqwest = "0.13.2"
tokio = { version = "1.50.0", features = ["full"] } tokio = { version = "1.50.0", features = ["full"] }
sysinfo = "0.38.3"
uuid = { version = "*", features = ["v4"] }
walkdir = "2.5.0"
zip = "6.0.0"
aes-gcm = "0.10.3"
base64 = "0.22.1"
rand_core = { version = "0.6", features = ["getrandom", "std"] }
sha2 = "0.10.9"
x448 = { version = "*" }
hkdf = "0.12.4"
once_cell = "1.21.3"
hex = "*"

View file

@ -9,7 +9,7 @@ use uuid::Uuid;
use walkdir::WalkDir; use walkdir::WalkDir;
use zip::ZipArchive; use zip::ZipArchive;
use crate::log;
#[allow(dead_code)] #[allow(dead_code)]
pub fn delete_directory(path: &str) -> bool { pub fn delete_directory(path: &str) -> bool {
@ -23,7 +23,7 @@ fn delete_dir_recursive(directory: &Path) -> bool {
return false; return false;
} }
if let Err(e) = fs::remove_dir_all(directory) { if let Err(e) = fs::remove_dir_all(directory) {
log!( println!(
"[IMPORTANT] Couldn't delete directory {}: {}", "[IMPORTANT] Couldn't delete directory {}: {}",
directory.display(), directory.display(),
e, e,
@ -97,7 +97,7 @@ pub fn load_file(path: &str, name: &str) -> String {
if !dir.exists() { if !dir.exists() {
if let Err(e) = fs::create_dir_all(&dir) { if let Err(e) = fs::create_dir_all(&dir) {
log!("[IMPORTANT] Couldn't create directories: {}", e); println!("[IMPORTANT] Couldn't create directories: {}", e);
return String::new(); return String::new();
} }
return String::new(); return String::new();
@ -105,7 +105,7 @@ pub fn load_file(path: &str, name: &str) -> String {
if !file_path.exists() { if !file_path.exists() {
if let Err(e) = File::create(&file_path) { if let Err(e) = File::create(&file_path) {
log!("[IMPORTANT] Couldn't create file: {}", e); println!("[IMPORTANT] Couldn't create file: {}", e);
} }
return String::new(); return String::new();
} }
@ -130,13 +130,13 @@ pub fn save_file(path: &str, name: &str, value: &str) {
if !dir.exists() { if !dir.exists() {
if let Err(e) = fs::create_dir_all(&dir) { if let Err(e) = fs::create_dir_all(&dir) {
log!("[IMPORTANT] Couldn't create directories: {}", e); println!("[IMPORTANT] Couldn't create directories: {}", e);
return; return;
} }
} }
if let Err(e) = fs::write(&file_path, value) { if let Err(e) = fs::write(&file_path, value) {
log!( println!(
"[IMPORTANT] Couldn't write file {}: {}", "[IMPORTANT] Couldn't write file {}: {}",
file_path.display(), file_path.display(),
e e
@ -231,7 +231,7 @@ pub async fn download_zip(url: &str, zip_path: &Path) -> Result<(), Box<dyn std:
if !response.status().is_success() { if !response.status().is_success() {
let err_msg = format!("Failed to download file: Status {}", response.status()); let err_msg = format!("Failed to download file: Status {}", response.status());
log!("{}", err_msg.clone()); println!("{}", err_msg.clone());
return Err(err_msg.into()); return Err(err_msg.into());
} }
@ -314,7 +314,7 @@ fn extract_zip_contents_to_folder(
} }
} }
log!("Extracting directly (no single root folder detected)."); println!("Extracting directly (no single root folder detected).");
let _ = fs::remove_dir_all(target_dir); let _ = fs::remove_dir_all(target_dir);
fs::rename(&staging_dir, target_dir)?; fs::rename(&staging_dir, target_dir)?;
@ -323,14 +323,14 @@ fn extract_zip_contents_to_folder(
#[allow(dead_code)] #[allow(dead_code)]
pub async fn download_and_extract_zip(url: &str, as_name: &str) { pub async fn download_and_extract_zip(url: &str, as_name: &str) {
log!("Downloading ZIP file..."); println!("Downloading ZIP file...");
let base_dir = PathBuf::from(get_directory()); let base_dir = PathBuf::from(get_directory());
let zip_filename = format!("{}.zip", Uuid::new_v4()); let zip_filename = format!("{}.zip", Uuid::new_v4());
let zip_path = base_dir.join(&zip_filename); let zip_path = base_dir.join(&zip_filename);
let target_dir = base_dir.join(as_name); let target_dir = base_dir.join(as_name);
if let Err(e) = download_zip(url, &zip_path).await { if let Err(e) = download_zip(url, &zip_path).await {
log!("Error downloading file: {}", e); println!("Error downloading file: {}", e);
return; return;
} }
@ -341,14 +341,14 @@ pub async fn download_and_extract_zip(url: &str, as_name: &str) {
let successful = match extract_result { let successful = match extract_result {
Ok(()) => true, Ok(()) => true,
Err(e) => { Err(e) => {
log!("Error during ZIP extraction: {}", e); println!("Error during ZIP extraction: {}", e);
false false
} }
}; };
if let Err(e) = tokio::fs::remove_file(&zip_path).await { if let Err(e) = tokio::fs::remove_file(&zip_path).await {
log!("Error cleaning up ZIP file {}: {}", zip_path.display(), e); println!("Error cleaning up ZIP file {}: {}", zip_path.display(), e);
} else if successful { } else if successful {
log!("Downloaded and extracted ZIP file successfully."); println!("Downloaded and extracted ZIP file successfully.");
} }
} }

View file

@ -1,4 +1,4 @@
use crate::util::file_util::save_file; use crate::file_util::save_file;
use json::{self, JsonError, JsonValue}; use json::{self, JsonError, JsonValue};
pub fn create_languages() -> Result<(), JsonError> { pub fn create_languages() -> Result<(), JsonError> {

View file

@ -1,4 +1,4 @@
use crate::util::file_util::{self}; use crate::file_util::{self};
use json::parse; use json::parse;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use std::collections::HashMap; use std::collections::HashMap;

View file

@ -0,0 +1,4 @@
pub mod crypto_helper;
pub mod crypto_util;
pub mod file_util;
pub mod langu;

View file

@ -4,6 +4,10 @@ version = "0.1.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
iota-logger = { path = "../iota-logger" }
iota-state = { path = "../iota-state" }
iota-storage = { path = "../iota-storage" }
iota-util = { path = "../iota-util" }
ttp-core = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-core" } ttp-core = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-core" }
ttp-native = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-native" } ttp-native = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-native" }
@ -11,3 +15,8 @@ dashmap = "6.1.0"
json = "*" json = "*"
tokio = { version = "1.50.0", features = ["full"] } tokio = { version = "1.50.0", features = ["full"] }
uuid = { version = "*", features = ["v4"] } uuid = { version = "*", features = ["v4"] }
base64 = "0.22.1"
hex = "*"
rand_core = { version = "0.6", features = ["getrandom", "std"] }
sha2 = "0.10.9"
x448 = { version = "*" }

View file

@ -1,2 +1,3 @@
pub mod omikron_connection; pub mod omikron_connection;
pub mod ping_pong_task; pub mod ping_pong_task;
pub mod user_ops;

View file

@ -1,12 +1,14 @@
use crate::users::contact::Contact; use iota_storage::users::contact::Contact;
use crate::util::chat_files::{MessageState, change_message_state}; use iota_storage::util::chat_files::{MessageState, change_message_state};
use crate::util::chats_util::{get_user, mod_user}; use iota_storage::util::chats_util::{get_user, mod_user};
use crate::util::communities_util::CommunitiesUtil; use iota_storage::util::communities_util::CommunitiesUtil;
use crate::util::crypto_util::{DataFormat, SecurePayload}; use iota_util::crypto_util::{DataFormat, SecurePayload};
use crate::util::file_util::{get_children, load_file, save_file}; use iota_util::file_util::{get_children, load_file, save_file};
use crate::util::{chat_files, chats_util}; use iota_storage::util::{chat_files, chats_util};
use crate::util::{config_util::CONFIG, crypto_helper}; use iota_storage::util::config_util::CONFIG;
use crate::{ACTIVE_TASKS, SHUTDOWN, log, log_cv_in, log_cv_out, log_t}; use iota_util::crypto_helper;
use iota_state::{ACTIVE_TASKS, SHUTDOWN};
use iota_logger::{log, log_cv_in, log_cv_out, log_t};
use dashmap::DashMap; use dashmap::DashMap;
use json::JsonValue; use json::JsonValue;
use std::collections::HashMap; use std::collections::HashMap;

View file

@ -1,5 +1,6 @@
use crate::omikron::omikron_connection::OmikronConnection; use crate::omikron_connection::OmikronConnection;
use crate::{APP_STATE, log}; use iota_state::APP_STATE;
use iota_logger::log;
use dashmap::DashMap; use dashmap::DashMap;
use std::sync::LazyLock; use std::sync::LazyLock;
use std::time::Instant; use std::time::Instant;

View file

@ -0,0 +1,93 @@
use base64::{Engine as _, engine::general_purpose::STANDARD};
use hex;
use iota_logger::{PrintType, log, log_cv};
use iota_state::{RELOAD, SHUTDOWN};
use iota_storage::users::user_manager::{add_user, save_users};
use iota_storage::users::user_profile::UserProfile;
use iota_util::crypto_helper::public_key_to_base64;
use iota_util::file_util::save_file;
use rand_core::{OsRng, RngCore};
use sha2::{Digest, Sha256};
use std::time::Duration;
use ttp_core::{CommunicationType, CommunicationValue, DataTypes, DataValue};
use x448::{PublicKey, Secret};
use crate::omikron_connection::OMIKRON_CONNECTION;
pub async fn create_user(username: &str) -> (Option<UserProfile>, Option<String>) {
let register_cv = CommunicationValue::new(CommunicationType::get_register);
let conn = OMIKRON_CONNECTION.clone();
let response_cv = match conn
.await_response(&register_cv, Some(Duration::from_secs(20)))
.await
{
Ok(cv) => cv,
Err(_) => return (None, None),
};
log_cv!(PrintType::Omega, response_cv);
let user_id = match response_cv.get_data(DataTypes::user_id).as_number() {
Some(id) => id,
None => return (None, None),
};
let mut buf = [0u8; 56];
let mut rng = OsRng;
rng.fill_bytes(&mut buf);
let private_key = Secret::from_bytes(&buf).unwrap();
let public_key = PublicKey::from(&private_key);
let mut hasher = Sha256::new();
hasher.update(&STANDARD.encode(&private_key.as_bytes()).as_bytes());
let result = hasher.finalize();
let private_key_hash = hex::encode(result);
let mut bytes = [0u8; 192];
OsRng.fill_bytes(&mut bytes);
let reset_token = STANDARD.encode(&bytes);
let up = UserProfile::new(
user_id,
username.to_string(),
None,
STANDARD.encode(&public_key.as_bytes()),
private_key_hash,
reset_token.clone(),
);
let cv = CommunicationValue::new(CommunicationType::complete_register_user)
.add_data(DataTypes::user_id, DataValue::Number(user_id))
.add_data(DataTypes::username, DataValue::Str(username.to_string()))
.add_data(
DataTypes::public_key,
DataValue::Str(public_key_to_base64(&public_key)),
)
.add_data(DataTypes::iota_id, DataValue::Number(user_id))
.add_data(DataTypes::reset_token, DataValue::Str(reset_token));
let response_cv = conn
.await_response(&cv, Some(Duration::from_secs(20)))
.await;
if let Ok(resp) = response_cv {
log_cv!(PrintType::Omega, resp);
if !resp.is_type(CommunicationType::success) {
return (None, None);
}
} else {
return (None, None);
}
*SHUTDOWN.write().await = true;
*RELOAD.write().await = true;
log!("Created User");
save_file(
"",
&format!("{}.tu", username),
&format!("{}::{}", user_id, STANDARD.encode(&private_key.as_bytes())),
);
add_user(up.clone());
save_users();
(Some(up), Some(STANDARD.encode(&private_key.as_bytes())))
}

View file

@ -4,6 +4,11 @@ version = "0.1.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
omikron-connector = { path = "../omikron-connector" }
iota-storage = { path = "../iota-storage" }
iota-state = { path = "../iota-state" }
iota-util = { path = "../iota-util" }
iota-logger = { path = "../iota-logger" }
ttp-core = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-core" } ttp-core = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-core" }
ttp-native = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-native" } ttp-native = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-native" }

View file

@ -1,6 +1,6 @@
use crate::server::server::is_local_network; use crate::server::is_local_network;
use crate::util::config_util::CONFIG;
use actix_web::{HttpRequest, HttpResponse, Responder, web}; use actix_web::{HttpRequest, HttpResponse, Responder, web};
use iota_storage::util::config_util::CONFIG;
use serde_json::{Value, json}; use serde_json::{Value, json};
use std::net::SocketAddr; use std::net::SocketAddr;
use std::sync::Arc; use std::sync::Arc;
@ -56,15 +56,15 @@ async fn communities_get(req: HttpRequest, ssl: web::Data<bool>) -> impl Respond
return forbidden(); return forbidden();
} }
let communities = crate::communities::community_manager::get_communities().await; // let communities = decentralized::communities::community_manager::get_communities().await;
let mut list = Vec::new(); let list: Vec<Value> = Vec::new();
for c in communities { // for c in communities {
let val = c.frontend().await; // let val = c.frontend().await.to_string();
let s_val: Value = serde_json::to_value(val.to_string()).unwrap(); // let s_val: Value = serde_json::from_str(&val).unwrap_or(Value::Null);
list.push(s_val); // list.push(s_val);
} // }
HttpResponse::Ok().json(list) HttpResponse::Ok().json(list)
} }
@ -77,12 +77,13 @@ async fn communities_add(
return forbidden(); return forbidden();
} }
let name = payload["name"].as_str().unwrap_or("").to_string(); // let name = payload["name"].as_str().unwrap_or("").to_string();
let owner = payload["owner"].as_i64().unwrap_or(0); // let owner = payload["owner"].as_i64().unwrap_or(0);
let community = Arc::new(crate::communities::community::Community::create(name, owner).await); // let community =
// Arc::new(decentralized::communities::community::Community::create(name, owner).await);
crate::communities::community_manager::add_community(community).await; // decentralized::communities::community_manager::add_community(community).await;
success() success()
} }
@ -92,13 +93,13 @@ async fn users_get(req: HttpRequest, ssl: web::Data<bool>) -> impl Responder {
return forbidden(); return forbidden();
} }
let users = crate::users::user_manager::get_users(); let users = iota_storage::users::user_manager::get_users();
let list: Vec<_> = users let list: Vec<_> = users
.into_iter() .into_iter()
.map(|u| { .map(|u| {
let val = u.frontend(); let val = u.frontend().to_string();
serde_json::to_value(val.to_string()).unwrap() serde_json::from_str(&val).unwrap_or(Value::Null)
}) })
.collect(); .collect();
@ -116,8 +117,8 @@ async fn users_remove(
let uuid = payload.get("uuid").and_then(|v| v.as_i64()).unwrap_or(0); let uuid = payload.get("uuid").and_then(|v| v.as_i64()).unwrap_or(0);
crate::users::user_manager::remove_user(uuid); iota_storage::users::user_manager::remove_user(uuid);
crate::users::user_manager::save_users(); iota_storage::users::user_manager::save_users();
success() success()
} }
@ -136,9 +137,9 @@ async fn users_add(
_ => return error(), _ => return error(),
}; };
if let (Some(user), Some(_)) = crate::users::user_manager::create_user(username).await { if let (Some(user), Some(_)) = omikron_connector::user_ops::create_user(username).await {
let val = user.frontend(); let val = user.frontend().to_string();
let s_val: Value = serde_json::to_value(val.to_string()).unwrap(); let s_val: Value = serde_json::from_str(&val).unwrap_or(Value::Null);
HttpResponse::Ok().json(s_val) HttpResponse::Ok().json(s_val)
} else { } else {
error() error()
@ -150,7 +151,7 @@ async fn shutdown(req: HttpRequest, ssl: web::Data<bool>) -> impl Responder {
return forbidden(); return forbidden();
} }
*crate::SHUTDOWN.write().await = true; *iota_state::SHUTDOWN.write().await = true;
success() success()
} }
@ -159,8 +160,8 @@ async fn reload(req: HttpRequest, ssl: web::Data<bool>) -> impl Responder {
return forbidden(); return forbidden();
} }
*crate::SHUTDOWN.write().await = true; *iota_state::SHUTDOWN.write().await = true;
*crate::RELOAD.write().await = true; *iota_state::RELOAD.write().await = true;
success() success()
} }

View file

@ -1,10 +1,9 @@
use crate::log; use crate::api::api_config;
use crate::server::api::api_config; use crate::web_path_parser;
use crate::server::web_path_parser;
use crate::util::file_util::load_file_buf;
use crate::{ACTIVE_TASKS, SHUTDOWN};
use actix_web::{App, Error, HttpRequest, HttpServer, Responder, dev::ServerHandle, web}; use actix_web::{App, Error, HttpRequest, HttpServer, Responder, dev::ServerHandle, web};
use actix_web_actors::ws; use iota_logger::log;
use iota_state::{ACTIVE_TASKS, SHUTDOWN};
use iota_util::file_util::load_file_buf;
use rustls::ServerConfig; use rustls::ServerConfig;
use rustls::pki_types::{CertificateDer, PrivateKeyDer}; use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use std::{ use std::{
@ -15,13 +14,6 @@ use std::{
time::Duration, time::Duration,
}; };
async fn ws_handler(req: HttpRequest, stream: web::Payload) -> Result<impl Responder, Error> {
let path = req.path().to_string();
log!("WS connection from {:?}", req.peer_addr());
let session = WsSession::new(path);
ws::start(session, &req, stream)
}
use tokio::sync::oneshot; use tokio::sync::oneshot;
pub async fn start(port: u16) -> bool { pub async fn start(port: u16) -> bool {
@ -36,7 +28,6 @@ pub async fn start(port: u16) -> bool {
App::new() App::new()
.app_data(web::Data::new(true)) .app_data(web::Data::new(true))
.configure(api_config) .configure(api_config)
.service(web::resource("/ws/{path:.*}").route(web::get().to(ws_handler)))
.default_service(web::to(web_path_parser::handle)) .default_service(web::to(web_path_parser::handle))
}) })
.bind(("0.0.0.0", port)) .bind(("0.0.0.0", port))
@ -49,7 +40,6 @@ pub async fn start(port: u16) -> bool {
App::new() App::new()
.app_data(web::Data::new(false)) .app_data(web::Data::new(false))
.configure(api_config) .configure(api_config)
.service(web::resource("/ws/{path:.*}").route(web::get().to(ws_handler)))
.default_service(web::to(web_path_parser::handle)) .default_service(web::to(web_path_parser::handle))
}) })
.bind(("0.0.0.0", port)) .bind(("0.0.0.0", port))

0
web-ui/src/socket.rs Normal file
View file

View file

@ -1,7 +1,7 @@
use actix_web::{HttpRequest, HttpResponse}; use actix_web::{HttpRequest, HttpResponse};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use crate::util::file_util::load_file_vec; use iota_util::file_util::load_file_vec;
fn codec_for_ext(ext: &str) -> &'static str { fn codec_for_ext(ext: &str) -> &'static str {
match ext { match ext {