Split #3

Merged
alex merged 9 commits from Split into main 2026-04-07 23:28:04 +03:00
83 changed files with 1035 additions and 466 deletions

231
Cargo.lock generated
View file

@ -552,9 +552,9 @@ dependencies = [
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.58" version = "1.2.59"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1e928d4b69e3077709075a938a05ffbedfa53a84c8f766efbf8220bb1ff60e1" checksum = "b7a4d3ec6524d28a329fc53654bbadc9bdd7b0431f5d65f1a56ffb28a1ee5283"
dependencies = [ dependencies = [
"find-msvc-tools", "find-msvc-tools",
"jobserver", "jobserver",
@ -1028,9 +1028,9 @@ dependencies = [
[[package]] [[package]]
name = "fastrand" name = "fastrand"
version = "2.3.0" version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" checksum = "a043dc74da1e37d6afe657061213aa6f425f855399a11d3463c6ecccc4dfda1f"
[[package]] [[package]]
name = "fiat-crypto" name = "fiat-crypto"
@ -1679,9 +1679,9 @@ checksum = "e8a5a9a0ff0086c7a148acb942baaabeadf9504d10400b5a05645853729b9cd2"
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "2.13.0" version = "2.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" checksum = "45a8a2b9cb3e0b0c1803dbb0758ffac5de2f425b23c28f518faabd9d805342ff"
dependencies = [ dependencies = [
"equivalent", "equivalent",
"hashbrown 0.16.1", "hashbrown 0.16.1",
@ -1721,7 +1721,7 @@ dependencies = [
] ]
[[package]] [[package]]
name = "iota" name = "iota-cli"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"actix-web", "actix-web",
@ -1738,8 +1738,14 @@ dependencies = [
"hkdf", "hkdf",
"hyper", "hyper",
"hyper-util", "hyper-util",
"iota-logger",
"iota-state",
"iota-storage",
"iota-terms",
"iota-util",
"json", "json",
"lazy_static", "lazy_static",
"omikron-connector",
"once_cell", "once_cell",
"open", "open",
"pnet", "pnet",
@ -1767,6 +1773,116 @@ dependencies = [
"zip", "zip",
] ]
[[package]]
name = "iota-core"
version = "0.1.0"
dependencies = [
"dashmap",
"iota-cli",
"iota-logger",
"iota-state",
"iota-storage",
"iota-terms",
"iota-util",
"json",
"omikron-connector",
"once_cell",
"pnet",
"ratatui",
"reqwest",
"tokio",
"ttp-core",
"ttp-native",
"web-server",
"web-ui",
]
[[package]]
name = "iota-logger"
version = "0.1.0"
dependencies = [
"iota-state",
"iota-util",
"ratatui",
"ttp-core",
]
[[package]]
name = "iota-state"
version = "0.1.0"
dependencies = [
"dashmap",
"json",
"once_cell",
"sysinfo",
"tokio",
"ttp-core",
]
[[package]]
name = "iota-storage"
version = "0.1.0"
dependencies = [
"aes-gcm",
"base64",
"hex",
"hkdf",
"iota-logger",
"iota-state",
"iota-util",
"json",
"once_cell",
"rand 0.8.5",
"rand_core 0.6.4",
"ratatui",
"reqwest",
"rusqlite",
"sha2",
"sysinfo",
"tokio",
"ttp-core",
"ttp-native",
"uuid",
"walkdir",
"x448",
"zip",
]
[[package]]
name = "iota-terms"
version = "0.1.0"
dependencies = [
"iota-state",
"iota-util",
"json",
"reqwest",
]
[[package]]
name = "iota-util"
version = "0.1.0"
dependencies = [
"aes-gcm",
"base64",
"hex",
"hkdf",
"json",
"once_cell",
"pnet",
"rand_core 0.6.4",
"ratatui",
"reqwest",
"sha2",
"sysinfo",
"tokio",
"ttp-core",
"ttp-native",
"uuid",
"walkdir",
"x448",
"zip",
]
[[package]] [[package]]
name = "ipnet" name = "ipnet"
version = "2.12.0" version = "2.12.0"
@ -2257,6 +2373,27 @@ dependencies = [
"asn1-rs", "asn1-rs",
] ]
[[package]]
name = "omikron-connector"
version = "0.1.0"
dependencies = [
"base64",
"dashmap",
"hex",
"iota-logger",
"iota-state",
"iota-storage",
"iota-util",
"json",
"rand_core 0.6.4",
"sha2",
"tokio",
"ttp-core",
"ttp-native",
"uuid",
"x448",
]
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.21.4" version = "1.21.4"
@ -3224,9 +3361,9 @@ dependencies = [
[[package]] [[package]]
name = "semver" name = "semver"
version = "1.0.27" version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]] [[package]]
name = "serde" name = "serde"
@ -3714,9 +3851,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.50.0" version = "1.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27ad5e34374e03cfffefc301becb44e9dc3c17584f414349ebe29ed26661822d" checksum = "2bd1c4c0fc4a7ab90fc15ef6daaa3ec3b893f004f915f2392557ed23237820cd"
dependencies = [ dependencies = [
"bytes", "bytes",
"libc", "libc",
@ -3731,9 +3868,9 @@ dependencies = [
[[package]] [[package]]
name = "tokio-macros" name = "tokio-macros"
version = "2.6.1" version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c55a2eff8b69ce66c84f85e1da1c233edc36ceb85a2058d11b0d6a3c7e7569c" checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -3873,7 +4010,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]] [[package]]
name = "ttp-core" name = "ttp-core"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/Tensamin/TTP.git#e246d1af6a42c71514d0ccc06fef94d71e4ad167" source = "git+https://git.methanium.net/Tensamin/TTP.git#bacbcb0e38791cf1a38cf5851beb20d5645002ba"
dependencies = [ dependencies = [
"base64", "base64",
"byteorder", "byteorder",
@ -3885,7 +4022,7 @@ dependencies = [
[[package]] [[package]]
name = "ttp-native" name = "ttp-native"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/Tensamin/TTP.git#e246d1af6a42c71514d0ccc06fef94d71e4ad167" source = "git+https://git.methanium.net/Tensamin/TTP.git#bacbcb0e38791cf1a38cf5851beb20d5645002ba"
dependencies = [ dependencies = [
"quinn", "quinn",
"rustls", "rustls",
@ -4204,6 +4341,14 @@ dependencies = [
"semver", "semver",
] ]
[[package]]
name = "web-server"
version = "0.1.0"
dependencies = [
"ttp-core",
"ttp-native",
]
[[package]] [[package]]
name = "web-sys" name = "web-sys"
version = "0.3.94" version = "0.3.94"
@ -4224,6 +4369,58 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "web-ui"
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",
"iota-logger",
"iota-state",
"iota-storage",
"iota-util",
"json",
"lazy_static",
"omikron-connector",
"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 = "webpki-root-certs" name = "webpki-root-certs"
version = "1.0.6" version = "1.0.6"
@ -4769,9 +4966,9 @@ dependencies = [
[[package]] [[package]]
name = "writeable" name = "writeable"
version = "0.6.2" version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
[[package]] [[package]]
name = "wtransport" name = "wtransport"

View file

@ -1,56 +1,2 @@
[package] [workspace]
name = "iota" members = ["iota-storage", "iota-terms", "iota-state", "iota-cli", "iota-core", "omikron-connector", "web-server", "web-ui", "iota-logger", "iota-util"]
version = "0.1.0"
edition = "2024"
[dependencies]
ttp-core = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-core" }
ttp-native = { git = "https://github.com/Tensamin/TTP.git", package = "ttp-native" }
actix-web = { version = "4", features = ["rustls-0_23"] }
actix-web-actors = "4"
aes-gcm = "0.10.3"
base64 = "0.22.1"
crossterm = "*"
futures = "*"
futures-util = "*"
hex = "*"
hkdf = "0.12.4"
hyper-util = { version = "*" }
hyper = { version = "1.8.1", features = [
"capi",
"client",
"full",
"http1",
"http2",
"nightly",
"server",
] }
json = "*"
once_cell = "1.21.3"
rand = "0.8"
rand_core = { version = "0.6", features = ["getrandom", "std"] }
reqwest = "0.13.2"
rustls = { version = "0.23.37", features = ["aws-lc-rs"] }
sha2 = "0.10.9"
sysinfo = "0.38.3"
tokio = { version = "1.50.0", features = ["full"] }
tokio-tungstenite = { version = "*", features = ["native-tls"] }
tungstenite = "*"
uuid = { version = "*", features = ["v4"] }
walkdir = "2.5.0"
warp = "*"
x448 = { version = "*" }
rustls-pemfile = "2.2.0"
async-trait = "0.1.89"
zip = "6.0.0"
pnet = "0.35.0"
dashmap = "6.1.0"
strum = "0.27.2"
strum_macros = "0.27.2"
ratatui = "0.30.0"
open = "5.3.3"
chrono = "0.4.43"
serde_json = "1.0.149"
rusqlite = "0.39.0"
lazy_static = "1.5.0"

2
decentralized/src/lib.rs Normal file
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

@ -0,0 +1,60 @@
[package]
name = "decentralized"
version = "0.1.0"
edition = "2024"
[dependencies]
ttp-core = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-core" }
ttp-native = { git = "https://git.methanium.net/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-actors = "4"
aes-gcm = "0.10.3"
async-trait = "0.1.89"
base64 = "0.22.1"
chrono = "0.4.43"
crossterm = "*"
dashmap = "6.1.0"
futures = "*"
futures-util = "*"
hex = "*"
hkdf = "0.12.4"
hyper = { version = "1.8.1", features = [
"capi",
"client",
"full",
"http1",
"http2",
"nightly",
"server",
] }
hyper-util = { version = "*" }
json = "*"
lazy_static = "1.5.0"
once_cell = "1.21.3"
open = "5.3.3"
pnet = "0.35.0"
rand = "0.8"
rand_core = { version = "0.6", features = ["getrandom", "std"] }
ratatui = "0.30.0"
reqwest = "0.13.2"
rusqlite = "0.39.0"
rustls = { version = "0.23.37", features = ["aws-lc-rs"] }
rustls-pemfile = "2.2.0"
serde_json = "1.0.149"
sha2 = "0.10.9"
strum = "0.27.2"
strum_macros = "0.27.2"
sysinfo = "0.38.3"
tokio = { version = "1.50.0", features = ["full"] }
tokio-tungstenite = { version = "*", features = ["native-tls"] }
tungstenite = "*"
uuid = { version = "*", features = ["v4"] }
walkdir = "2.5.0"
warp = "*"
x448 = { version = "*" }
zip = "6.0.0"

View file

@ -13,8 +13,8 @@ WORKDIR /app
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/* RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/iota . COPY --from=builder /app/target/release/iota-core .
EXPOSE 1984 EXPOSE 1984
CMD ["./iota"] CMD ["./iota-core"]

64
iota-cli/Cargo.toml Normal file
View file

@ -0,0 +1,64 @@
[package]
name = "iota-cli"
version = "0.1.0"
edition = "2024"
[dependencies]
iota-logger = { path = "../iota-logger" }
iota-state = { path = "../iota-state" }
iota-storage = { path = "../iota-storage" }
iota-terms = { path = "../iota-terms" }
iota-util = { path = "../iota-util" }
omikron-connector = { path = "../omikron-connector" }
ttp-core = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-core" }
ttp-native = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-native" }
actix-web = { version = "4", features = ["rustls-0_23"] }
actix-web-actors = "4"
aes-gcm = "0.10.3"
async-trait = "0.1.89"
base64 = "0.22.1"
chrono = "0.4.43"
crossterm = "*"
dashmap = "6.1.0"
futures = "*"
futures-util = "*"
hex = "*"
hkdf = "0.12.4"
hyper = { version = "1.8.1", features = [
"capi",
"client",
"full",
"http1",
"http2",
"nightly",
"server",
] }
hyper-util = { version = "*" }
json = "*"
lazy_static = "1.5.0"
once_cell = "1.21.3"
open = "5.3.3"
pnet = "0.35.0"
rand = "0.8"
rand_core = { version = "0.6", features = ["getrandom", "std"] }
ratatui = "0.30.0"
reqwest = "0.13.2"
rusqlite = "0.39.0"
rustls = { version = "0.23.37", features = ["aws-lc-rs"] }
rustls-pemfile = "2.2.0"
serde_json = "1.0.149"
sha2 = "0.10.9"
strum = "0.27.2"
strum_macros = "0.27.2"
sysinfo = "0.38.3"
tokio = { version = "1.50.0", features = ["full"] }
tokio-tungstenite = { version = "*", features = ["native-tls"] }
tungstenite = "*"
uuid = { version = "*", features = ["v4"] }
walkdir = "2.5.0"
warp = "*"
x448 = { version = "*" }
zip = "6.0.0"

1
iota-cli/src/app_state.rs Executable file
View file

@ -0,0 +1 @@
pub use iota_state::*;

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::gui::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,7 +2,7 @@ use std::fmt::{Debug, Formatter};
use std::future::Future; use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
use crate::gui::screens::screens::Screen; use crate::screens::screens::Screen;
#[allow(unused)] #[allow(unused)]
pub enum InteractionResult { pub enum InteractionResult {

View file

@ -13,6 +13,8 @@ pub mod screens {
} }
pub mod util { pub mod util {
pub mod borders; pub mod borders;
pub mod buttons;
pub mod terms_focus;
} }
pub mod app_state; pub mod app_state;
pub mod input_handler; pub mod input_handler;

View file

@ -1,4 +1,4 @@
use crate::gui::{ use crate::{
elements::{ elements::{
console_card::ConsoleCard, console_card::ConsoleCard,
elements::{InteractableElement, JoinableElement}, elements::{InteractableElement, JoinableElement},

View file

@ -7,7 +7,7 @@ use ratatui::{
}; };
use std::{any::Any, time::Duration}; use std::{any::Any, time::Duration};
use crate::gui::{interaction_result::InteractionResult, screens::screens::Screen}; use crate::{interaction_result::InteractionResult, screens::screens::Screen};
pub struct FileViewer { pub struct FileViewer {
title: String, title: String,

View file

@ -3,7 +3,7 @@ use std::any::Any;
use crossterm::event::KeyEvent; use crossterm::event::KeyEvent;
use ratatui::{Frame, layout::Rect}; use ratatui::{Frame, layout::Rect};
use crate::gui::interaction_result::InteractionResult; use crate::interaction_result::InteractionResult;
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NavDirection { pub enum NavDirection {

View file

@ -1,17 +1,14 @@
use crate::{ use crate::{
gui::{ interaction_result::InteractionResult,
interaction_result::InteractionResult, screens::{md_viewer::FileViewer, screens::Screen},
screens::{md_viewer::FileViewer, screens::Screen}, ui::UI,
ui::UI, util::{
},
terms::{
buttons::{checkbox, draw_buttons}, buttons::{checkbox, draw_buttons},
consent_state::UserChoice, terms_focus::Focus,
focus::Focus,
terms_getter::{Type, get_link, get_terms},
}, },
}; };
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},
@ -22,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>>,
@ -276,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 {
@ -296,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,18 +1,15 @@
use crate::screens::terms_checker::UserChoice;
use crate::{ use crate::{
gui::{ interaction_result::InteractionResult,
interaction_result::InteractionResult, screens::{md_viewer::FileViewer, screens::Screen},
screens::{md_viewer::FileViewer, screens::Screen}, util::{
},
terms::{
buttons::{checkbox, draw_buttons}, buttons::{checkbox, draw_buttons},
consent_state::{UpdateDecision, UserChoice}, terms_focus::Focus,
doc::Doc,
focus::Focus,
terms_getter::{Type, get_newest_link, get_terms},
}, },
}; };
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},
@ -23,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>>,
@ -644,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,
}; };
@ -664,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

@ -1,11 +1,9 @@
use crate::{ use crate::{
ACTIVE_TASKS, SHUTDOWN, input_handler::setup_input_handler, interaction_result::InteractionResult,
gui::{ screens::screens::Screen,
input_handler::setup_input_handler, interaction_result::InteractionResult,
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::{
@ -20,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

@ -5,7 +5,7 @@ use ratatui::{
widgets::{Block, Borders, Paragraph}, widgets::{Block, Borders, Paragraph},
}; };
use crate::terms::focus::Focus; use crate::util::terms_focus::Focus;
#[allow(mismatched_lifetime_syntaxes)] #[allow(mismatched_lifetime_syntaxes)]
pub fn checkbox(label: &str, checked: bool, active: bool, allowed: bool) -> Line { pub fn checkbox(label: &str, checked: bool, active: bool, allowed: bool) -> Line {

26
iota-core/Cargo.toml Normal file
View file

@ -0,0 +1,26 @@
[package]
name = "iota-core"
version = "0.1.0"
edition = "2024"
[dependencies]
iota-cli = { path = "../iota-cli" }
iota-logger = { path = "../iota-logger" }
iota-state = { path = "../iota-state" }
iota-storage = { path = "../iota-storage" }
iota-terms = { path = "../iota-terms" }
iota-util = { path = "../iota-util" }
omikron-connector = { path = "../omikron-connector" }
web-server = { path = "../web-server" }
web-ui = { path = "../web-ui" }
ttp-core = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-core" }
ttp-native = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-native" }
dashmap = "6.1.0"
json = "*"
once_cell = "1.21.3"
pnet = "0.35.0"
ratatui = "0.30.0"
reqwest = "0.13.2"
tokio = { version = "1.50.0", features = ["full"] }

View file

@ -1,19 +1,14 @@
use tokio::sync::oneshot;
use crate::{
gui::{
screens::{terms_checker::TermsCheckerScreen, terms_updater::TermsUpdaterScreen},
ui::UI,
},
terms::{
doc::Doc,
terms_getter::{Type, get_current_docs, get_newest_docs},
},
util::file_util::{load_file, save_file},
};
use std::sync::Arc; use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH}; 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) { pub async fn check(ui: Arc<UI>) -> (bool, bool) {
let mut state = ConsentState::load_state(); let mut state = ConsentState::load_state();
@ -216,19 +211,6 @@ async fn get_updates() -> Option<(
} }
} }
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum UserChoice {
Deny,
AcceptEULA,
AcceptAll,
}
#[derive(Debug, Clone, PartialEq)]
pub enum UpdateDecision {
NoChange,
Future { newest: Doc },
Forced(Doc),
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ConsentState { pub struct ConsentState {

View file

@ -1,39 +1,18 @@
use dashmap::DashSet; mod consent_state;
use once_cell::sync::Lazy;
use pnet::datalink::NetworkInterface; use pnet::datalink::NetworkInterface;
use std::sync::Arc;
use std::sync::LazyLock;
use std::sync::Mutex;
use tokio::sync::RwLock;
use tokio::time::{Duration, sleep}; use tokio::time::{Duration, sleep};
mod auth; use iota_state::{ACTIVE_TASKS, APP_STATE, AppState, RELOAD, SHUTDOWN};
mod gui;
mod langu;
mod omikron;
mod terms;
mod users;
mod util;
use crate::gui::app_state; use iota_cli::screens::main_screen::MainScreen;
use crate::gui::app_state::AppState; use iota_cli::ui::start_tui;
use crate::gui::screens::main_screen::MainScreen; use iota_logger as logger;
use crate::gui::ui::start_tui; use iota_logger::{log, log_t};
use crate::langu::language_creator; use iota_storage::users::user_manager;
use crate::omikron::omikron_connection::OmikronConnection; use iota_storage::util::config_util::CONFIG;
use crate::terms::consent_state; use iota_util::file_util::{download_and_extract_zip, has_dir};
use crate::users::user_manager; use iota_util::langu::language_creator;
use crate::util::config_util::CONFIG; use omikron_connector as omikron;
use crate::util::file_util::download_and_extract_zip;
use crate::util::file_util::has_dir;
use crate::util::logger;
pub static APP_STATE: LazyLock<Arc<Mutex<AppState>>> =
LazyLock::new(|| Arc::new(Mutex::new(AppState::new())));
pub static SHUTDOWN: Lazy<RwLock<bool>> = Lazy::new(|| RwLock::new(false));
pub static RELOAD: Lazy<RwLock<bool>> = Lazy::new(|| RwLock::new(true));
pub static ACTIVE_TASKS: Lazy<DashSet<String>> = Lazy::new(|| DashSet::new());
#[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)]
@ -73,7 +52,7 @@ async fn main() {
println!("You can find this at 'agreements'!"); println!("You can find this at 'agreements'!");
return; return;
} }
app_state::setup(); iota_state::setup();
let main_screen = MainScreen::new(ui.clone()).await; let main_screen = MainScreen::new(ui.clone()).await;
ui.set_screen(Box::new(main_screen)).await; ui.set_screen(Box::new(main_screen)).await;

10
iota-logger/Cargo.toml Normal file
View file

@ -0,0 +1,10 @@
[package]
name = "iota-logger"
version = "0.1.0"
edition = "2024"
[dependencies]
ratatui = "0.30.0"
ttp-core = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-core" }
iota-state = { path = "../iota-state" }
iota-util = { path = "../iota-util" }

67
src/util/logger.rs → iota-logger/src/lib.rs Executable file → Normal file
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)
}; };
} }

12
iota-state/Cargo.toml Normal file
View file

@ -0,0 +1,12 @@
[package]
name = "iota-state"
version = "0.1.0"
edition = "2024"
[dependencies]
dashmap = "6.1.0"
once_cell = "1.21.3"
tokio = { version = "1.50.0", features = ["full"] }
json = "*"
sysinfo = "0.38.3"
ttp-core = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-core" }

79
src/gui/app_state.rs → iota-state/src/lib.rs Executable file → Normal file
View file

@ -1,7 +1,35 @@
use crate::{ACTIVE_TASKS, APP_STATE, SHUTDOWN, gui::elements::log_card::UiLogEntry}; use dashmap::DashSet;
use json::{JsonValue, object}; use json::{JsonValue, object};
use std::{collections::VecDeque, thread, time::Duration}; use once_cell::sync::Lazy;
use std::collections::VecDeque;
use std::sync::{Arc, LazyLock, Mutex, atomic::AtomicBool};
use std::thread;
use std::time::Duration;
use sysinfo::{RefreshKind, System}; use sysinfo::{RefreshKind, System};
use tokio::sync::RwLock;
pub const MAX_POINTS: usize = 1000;
pub const MAX_LOGS: usize = 100;
pub static UNIQUE: AtomicBool = AtomicBool::new(true);
#[derive(Clone, Debug)]
pub struct UiLogEntry {
pub timestamp_ms: u128,
pub sender: String,
pub message: String,
pub is_error: bool,
}
impl UiLogEntry {
pub fn format_timestamp(&self) -> String {
let secs = (self.timestamp_ms / 1000) as i64;
let hours = (secs / 3600) % 24;
let minutes = (secs / 60) % 60;
let seconds = secs % 60;
format!("{:02}:{:02}:{:02}", hours, minutes, seconds)
}
}
#[derive(Clone)] #[derive(Clone)]
pub struct AppState { pub struct AppState {
@ -13,8 +41,6 @@ pub struct AppState {
pub net_down: Vec<(f64, f64)>, pub net_down: Vec<(f64, f64)>,
pub sys_info: String, pub sys_info: String,
} }
const MAX_POINTS: usize = 1000;
const MAX_LOGS: usize = 100;
impl AppState { impl AppState {
pub fn new() -> Self { pub fn new() -> Self {
@ -74,34 +100,17 @@ impl AppState {
self.net_down.remove(0); self.net_down.remove(0);
} }
} }
pub fn to_json(&self) -> JsonValue { pub fn to_json(&self) -> JsonValue {
let json = object! { object! {
"cpu" => self.cpu "cpu" => self.cpu.iter().map(|(_, y)| *y).collect::<Vec<f64>>(),
.iter() "ram" => self.ram.iter().map(|(_, y)| *y).collect::<Vec<f64>>(),
.map(|(_, y)| *y) "ping" => self.ping.iter().map(|(_, y)| *y).collect::<Vec<f64>>(),
.collect::<Vec<f64>>(), "net_up" => self.net_up.iter().map(|(_, y)| *y).collect::<Vec<f64>>(),
"ram" => self.ram "net_down" => self.net_down.iter().map(|(_, y)| *y).collect::<Vec<f64>>(),
.iter() }
.map(|(_, y)| *y)
.collect::<Vec<f64>>(),
"ping" => self
.ping
.iter()
.map(|(_, y)| *y)
.collect::<Vec<f64>>(),
"net_up" => self
.net_up
.iter()
.map(|(_, y)| *y)
.collect::<Vec<f64>>(),
"net_down" => self
.net_down
.iter()
.map(|(_, y)| *y)
.collect::<Vec<f64>>(),
};
json
} }
pub fn with_width(&self, width: u16) -> Self { pub fn with_width(&self, width: u16) -> Self {
let mut new = self.clone(); let mut new = self.clone();
new.cpu = Self::downsample_to_fit_width(&new.cpu, width); new.cpu = Self::downsample_to_fit_width(&new.cpu, width);
@ -128,10 +137,9 @@ impl AppState {
.first() .first()
.map(|(x, _)| x - (dx * pad_len as f64)) .map(|(x, _)| x - (dx * pad_len as f64))
.unwrap_or(0.0); .unwrap_or(0.0);
let _ = data.first().map(|(_, y)| *y).unwrap_or(0.0);
for i in 0..pad_len { for i in 0..pad_len {
result.push((start_x + i as f64 * dx, -1 as f64)); result.push((start_x + i as f64 * dx, -1.0));
} }
result.extend_from_slice(data); result.extend_from_slice(data);
@ -140,6 +148,13 @@ impl AppState {
} }
} }
pub static APP_STATE: LazyLock<Arc<Mutex<AppState>>> =
LazyLock::new(|| Arc::new(Mutex::new(AppState::new())));
pub static SHUTDOWN: Lazy<RwLock<bool>> = Lazy::new(|| RwLock::new(false));
pub static RELOAD: Lazy<RwLock<bool>> = Lazy::new(|| RwLock::new(true));
pub static ACTIVE_TASKS: Lazy<DashSet<String>> = Lazy::new(|| DashSet::new());
pub fn setup() { pub fn setup() {
ACTIVE_TASKS.insert("System info loader".to_string()); ACTIVE_TASKS.insert("System info loader".to_string());
tokio::spawn(async move { tokio::spawn(async move {

31
iota-storage/Cargo.toml Normal file
View file

@ -0,0 +1,31 @@
[package]
name = "iota-storage"
version = "0.1.0"
edition = "2024"
[dependencies]
iota-logger = { path = "../iota-logger" }
iota-state = { path = "../iota-state" }
iota-util = { path = "../iota-util" }
ttp-core = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-core" }
ttp-native = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-native" }
aes-gcm = "0.10.3"
base64 = "0.22.1"
hex = "*"
hkdf = "0.12.4"
json = "*"
once_cell = "1.21.3"
rand = "0.8"
rand_core = { version = "0.6", features = ["getrandom", "std"] }
ratatui = "0.30.0"
reqwest = "0.13.2"
rusqlite = "0.39.0"
sha2 = "0.10.9"
sysinfo = "0.38.3"
tokio = { version = "1.50.0", features = ["full"] }
uuid = { version = "*", features = ["v4"] }
walkdir = "2.5.0"
x448 = { version = "*" }
zip = "6.0.0"

2
iota-storage/src/lib.rs Normal file
View file

@ -0,0 +1,2 @@
pub mod users;
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;
@ -19,11 +19,26 @@ impl ConfigUtil {
} }
pub fn clear(&mut self) { pub fn clear(&mut self) {
self.config = JsonValue::new_object(); self.config = JsonValue::new_object();
self.unique = false;
} }
pub fn load(&mut self) { pub fn load(&mut self) {
let s = load_file("", "config.json"); let s = load_file("", "config.json");
if !s.is_empty() { if s.is_empty() {
self.config = json::parse(&s).unwrap_or(JsonValue::new_object()); // File might be missing or empty/being written.
// We don't want to wipe the current config if it already has data.
// But if it's the first load, it will stay empty.
return;
}
match json::parse(&s) {
Ok(parsed) => {
self.config = parsed;
self.unique = false;
}
Err(e) => {
eprintln!("Failed to parse config.json: {}. Content: '{}'", e, s);
// Keep the current config rather than wiping it.
}
} }
} }
@ -55,6 +70,7 @@ impl ConfigUtil {
pub fn update(&mut self) { pub fn update(&mut self) {
if self.unique { if self.unique {
save_file("", "config.json", &self.config.to_string()); save_file("", "config.json", &self.config.to_string());
self.unique = false;
} }
} }
} }

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;

11
iota-terms/Cargo.toml Normal file
View file

@ -0,0 +1,11 @@
[package]
name = "iota-terms"
version = "0.1.0"
edition = "2024"
[dependencies]
iota-state = { path = "../iota-state" }
iota-util = { path = "../iota-util" }
json = "*"
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)]

14
iota-terms/src/lib.rs Normal file
View file

@ -0,0 +1,14 @@
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 {

27
iota-util/Cargo.toml Normal file
View file

@ -0,0 +1,27 @@
[package]
name = "iota-util"
version = "0.1.0"
edition = "2024"
[dependencies]
ttp-core = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-core" }
ttp-native = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-native" }
json = "*"
pnet = "0.35.0"
ratatui = "0.30.0"
reqwest = "0.13.2"
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,8 +9,6 @@ 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 {
let dir = Path::new(&get_directory()).join(path); let dir = Path::new(&get_directory()).join(path);
@ -23,7 +21,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,
@ -96,17 +94,10 @@ pub fn load_file(path: &str, name: &str) -> String {
let file_path = dir.join(name); let file_path = dir.join(name);
if !dir.exists() { if !dir.exists() {
if let Err(e) = fs::create_dir_all(&dir) {
log!("[IMPORTANT] Couldn't create directories: {}", e);
return String::new();
}
return String::new(); return String::new();
} }
if !file_path.exists() { if !file_path.exists() {
if let Err(e) = File::create(&file_path) {
log!("[IMPORTANT] Couldn't create file: {}", e);
}
return String::new(); return String::new();
} }
@ -130,13 +121,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 +222,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 +305,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 +314,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 +332,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;

4
iota-util/src/lib.rs Normal file
View file

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

View file

@ -0,0 +1,22 @@
[package]
name = "omikron-connector"
version = "0.1.0"
edition = "2024"
[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://git.methanium.net/Tensamin/TTP.git", package = "ttp-core" }
ttp-native = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-native" }
dashmap = "6.1.0"
json = "*"
tokio = { version = "1.50.0", features = ["full"] }
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,13 +1,15 @@
use crate::users::contact::Contact;
use crate::util::chat_files::{MessageState, change_message_state};
use crate::util::chats_util::{get_user, mod_user};
use crate::util::communities_util::CommunitiesUtil;
use crate::util::crypto_util::{DataFormat, SecurePayload};
use crate::util::file_util::{get_children, load_file, save_file};
use crate::util::{chat_files, chats_util};
use crate::util::{config_util::CONFIG, crypto_helper};
use crate::{ACTIVE_TASKS, SHUTDOWN, log, log_cv_in, log_cv_out, log_t};
use dashmap::DashMap; use dashmap::DashMap;
use iota_logger::{log, log_cv_in, log_cv_out, log_t};
use iota_state::{ACTIVE_TASKS, SHUTDOWN};
use iota_storage::users::contact::Contact;
use iota_storage::util::chat_files::{MessageState, change_message_state};
use iota_storage::util::chats_util::{get_user, mod_user};
use iota_storage::util::communities_util::CommunitiesUtil;
use iota_storage::util::config_util::CONFIG;
use iota_storage::util::{chat_files, chats_util};
use iota_util::crypto_helper;
use iota_util::crypto_util::{DataFormat, SecurePayload};
use iota_util::file_util::{get_children, load_file, save_file};
use json::JsonValue; use json::JsonValue;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::{Arc, LazyLock}; use std::sync::{Arc, LazyLock};
@ -223,15 +225,15 @@ impl OmikronConnection {
*self.sender.write().await = Some(sender_arc.clone()); *self.sender.write().await = Some(sender_arc.clone());
*self.state.write().await = ConnectionState::Connected { identified: false }; *self.state.write().await = ConnectionState::Connected { identified: false };
// Handle registration/identification
self.handle_authentication().await;
// Start read loop // Start read loop
let read_self = self.clone(); let read_self = self.clone();
let read_handle = tokio::spawn(async move { let read_handle = tokio::spawn(async move {
read_self.read_loop(&mut receiver).await; read_self.read_loop(&mut receiver).await;
}); });
// Handle registration/identification
self.handle_authentication().await;
// Start heartbeat // Start heartbeat
let heartbeat_self = self.clone(); let heartbeat_self = self.clone();
let heartbeat_handle = tokio::spawn(async move { let heartbeat_handle = tokio::spawn(async move {
@ -278,26 +280,26 @@ impl OmikronConnection {
let private_key = conf.get_private_key(); let private_key = conf.get_private_key();
drop(conf); drop(conf);
if iota_id == 0 || public_key.is_none() || private_key.is_none() { if iota_id == 0 {
log_t!("iota_register_new"); log_t!("iota_register_new");
let key_pair = crypto_helper::generate_keypair(); let (pub_k, priv_k) = if let (Some(pk), Some(sk)) = (public_key, private_key) {
let public_key_base64 = crypto_helper::public_key_to_base64(&key_pair.public); (pk, sk)
let _private_key_base64 = crypto_helper::secret_key_to_base64(&key_pair.secret); } else {
let key_pair = crypto_helper::generate_keypair();
let public_key_base64 = crypto_helper::public_key_to_base64(&key_pair.public);
let private_key_base64 = crypto_helper::secret_key_to_base64(&key_pair.secret);
let mut conf_write = CONFIG.write().await; let mut conf_write = CONFIG.write().await;
// NOTE: conf_write.change("public_key", JsonValue::from(public_key_base64.clone()));
// Intentionally not storing the generated private/public keys directly into the conf_write.change("private_key", JsonValue::from(private_key_base64.clone()));
// config file here to avoid persisting sensitive material in plaintext. If you conf_write.update();
// want to persist them, uncomment the two lines below and accept the security drop(conf_write);
// implications (they will be saved by `conf_write.update()`). (public_key_base64, private_key_base64)
// conf_write.change("public_key", DataValue::Str(public_key_base64.clone())); };
// conf_write.change("private_key", DataValue::Str(private_key_base64));
conf_write.update();
drop(conf_write);
let register_msg = CommunicationValue::new(CommunicationType::register_iota) let register_msg = CommunicationValue::new(CommunicationType::register_iota)
.add_data(DataTypes::public_key, DataValue::Str(public_key_base64)); .add_data(DataTypes::public_key, DataValue::Str(pub_k));
let msg_id = register_msg.get_id(); let msg_id = register_msg.get_id();
@ -309,7 +311,7 @@ impl OmikronConnection {
return false; return false;
} }
let iota_value = cv.get_data(DataTypes::register_id); let iota_value = cv.get_data(DataTypes::iota_id);
let iota_id = iota_value.as_number().unwrap_or(0); let iota_id = iota_value.as_number().unwrap_or(0);
if iota_id != 0 { if iota_id != 0 {
@ -422,6 +424,68 @@ impl OmikronConnection {
return; return;
} }
if cv.is_type(CommunicationType::client_connected) {
let user_id = cv.get_data(DataTypes::user_id).as_number().unwrap_or(0) as i64;
let session_id = cv.get_data(DataTypes::session_id).as_number().unwrap_or(0) as i64;
let mut contacts = chats_util::get_users(user_id);
let mut contacts_array = Vec::new();
for (i, contact) in contacts.iter().enumerate() {
let mut contact_container = Vec::new();
contact_container.push((DataTypes::user_id, DataValue::Number(contact.user_id)));
contact_container.push((
DataTypes::last_message_at,
DataValue::Number(contact.last_message_at.unwrap_or(0)),
));
if let Some(ref name) = contact.user_name {
contact_container.push((DataTypes::username, DataValue::Str(name.clone())));
}
let amount = if i < 10 { 20 } else { 1 };
let messages = chat_files::get_messages(user_id, contact.user_id, 0, amount);
let mut msg_array = Vec::new();
for m in messages.members() {
let message_time = m["message_time"].as_i64().unwrap_or(0);
let content = m["content"].as_str().unwrap_or("").to_string();
let sent_by_self = m["sent_by_self"].as_bool().unwrap_or(false);
let height = m["height"].as_i64().unwrap_or(0);
let message_state = m["message_state"].as_str().unwrap_or("").to_string();
let mut msg_container = Vec::new();
msg_container.push((DataTypes::send_time, DataValue::Number(message_time)));
msg_container.push((DataTypes::content, DataValue::Str(content.clone())));
msg_container.push((DataTypes::message_state, DataValue::Str(message_state)));
msg_container.push((DataTypes::height, DataValue::Number(height)));
msg_container.push((DataTypes::sent_by_self, DataValue::Bool(sent_by_self)));
msg_array.push(DataValue::Container(msg_container));
if msg_array.len() == 1 {
let sender_id = if sent_by_self {
user_id
} else {
contact.user_id
};
let mut last_msg = Vec::new();
last_msg.push((DataTypes::content, DataValue::Str(content)));
last_msg.push((DataTypes::sender_id, DataValue::Number(sender_id)));
contact_container
.push((DataTypes::last_message, DataValue::Container(last_msg)));
}
}
contact_container.push((DataTypes::messages, DataValue::Array(msg_array)));
contacts_array.push(DataValue::Container(contact_container));
}
let resp = CommunicationValue::new(CommunicationType::client_connected)
.with_id(cv.get_id())
.add_data(DataTypes::contacts, DataValue::Array(contacts_array));
self.send_message(&resp).await;
return;
}
if cv.is_type(CommunicationType::identification_response) { if cv.is_type(CommunicationType::identification_response) {
if let Some(_accepted) = cv.get_data(DataTypes::accepted).as_bool() { if let Some(_accepted) = cv.get_data(DataTypes::accepted).as_bool() {
let mut state = self.state.write().await; let mut state = self.state.write().await;
@ -577,7 +641,7 @@ impl OmikronConnection {
.with_sender(receiver_id as u64) .with_sender(receiver_id as u64)
.add_data( .add_data(
DataTypes::chat_partner_id, DataTypes::chat_partner_id,
DataValue::Number(sender_id as i64), DataValue::Number(receiver_id as i64),
) )
.add_data(DataTypes::send_time, DataValue::Number(timestamp_i64)) .add_data(DataTypes::send_time, DataValue::Number(timestamp_i64))
.add_data( .add_data(

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

@ -1,5 +0,0 @@
pub mod buttons;
pub mod consent_state;
pub mod doc;
pub mod focus;
pub mod terms_getter;

9
web-server/Cargo.toml Normal file
View file

@ -0,0 +1,9 @@
[package]
name = "web-server"
version = "0.1.0"
edition = "2024"
[dependencies]
ttp-core = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-core" }
ttp-native = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-native" }

0
web-server/src/lib.rs Normal file
View file

61
web-ui/Cargo.toml Normal file
View file

@ -0,0 +1,61 @@
[package]
name = "web-ui"
version = "0.1.0"
edition = "2024"
[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://git.methanium.net/Tensamin/TTP.git", package = "ttp-core" }
ttp-native = { git = "https://git.methanium.net/Tensamin/TTP.git", package = "ttp-native" }
actix-web = { version = "4", features = ["rustls-0_23"] }
actix-web-actors = "4"
aes-gcm = "0.10.3"
async-trait = "0.1.89"
base64 = "0.22.1"
chrono = "0.4.43"
crossterm = "*"
dashmap = "6.1.0"
futures = "*"
futures-util = "*"
hex = "*"
hkdf = "0.12.4"
hyper = { version = "1.8.1", features = [
"capi",
"client",
"full",
"http1",
"http2",
"nightly",
"server",
] }
hyper-util = { version = "*" }
json = "*"
lazy_static = "1.5.0"
once_cell = "1.21.3"
open = "5.3.3"
pnet = "0.35.0"
rand = "0.8"
rand_core = { version = "0.6", features = ["getrandom", "std"] }
ratatui = "0.30.0"
reqwest = "0.13.2"
rusqlite = "0.39.0"
rustls = { version = "0.23.37", features = ["aws-lc-rs"] }
rustls-pemfile = "2.2.0"
serde_json = "1.0.149"
sha2 = "0.10.9"
strum = "0.27.2"
strum_macros = "0.27.2"
sysinfo = "0.38.3"
tokio = { version = "1.50.0", features = ["full"] }
tokio-tungstenite = { version = "*", features = ["native-tls"] }
tungstenite = "*"
uuid = { version = "*", features = ["v4"] }
walkdir = "2.5.0"
warp = "*"
x448 = { version = "*" }
zip = "6.0.0"

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 {