add user config

This commit is contained in:
Horhik 2021-04-20 22:23:04 +03:00
parent 93874ee3ed
commit 044c393e92
16 changed files with 180 additions and 82 deletions

19
Cargo.lock generated
View file

@ -639,6 +639,7 @@ dependencies = [
"futures-util", "futures-util",
"log", "log",
"ntru", "ntru",
"regex",
"rusqlite", "rusqlite",
"serde", "serde",
"serde_derive", "serde_derive",
@ -1165,14 +1166,13 @@ checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce"
[[package]] [[package]]
name = "regex" name = "regex"
version = "1.4.3" version = "1.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9251239e129e16308e70d853559389de218ac275b515068abc96829d05b948a" checksum = "957056ecddbeba1b26965114e191d2e8589ce74db242b6ea25fc4062427a5c19"
dependencies = [ dependencies = [
"aho-corasick", "aho-corasick",
"memchr", "memchr",
"regex-syntax", "regex-syntax",
"thread_local",
] ]
[[package]] [[package]]
@ -1423,15 +1423,6 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "thread_local"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8018d24e04c95ac8790716a5987d0fec4f8b27249ffa0f7d33f1369bdfb88cbd"
dependencies = [
"once_cell",
]
[[package]] [[package]]
name = "time" name = "time"
version = "0.1.44" version = "0.1.44"
@ -1506,9 +1497,9 @@ dependencies = [
[[package]] [[package]]
name = "toml" name = "toml"
version = "0.5.6" version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffc92d160b1eef40665be3a05630d003936a3bc7da7421277846c2613e92c71a" checksum = "a31142970826733df8241ef35dc040ef98c679ab14d7c3e54d827099b3acecaa"
dependencies = [ dependencies = [
"serde", "serde",
] ]

View file

@ -9,7 +9,7 @@ edition = "2018"
[dependencies] [dependencies]
ntru = "0.5.6" ntru = "0.5.6"
rusqlite = {version = "0.24.2", features = ["chrono"]} rusqlite = {version = "0.24.2", features = ["chrono"]}
toml = "0.5.6" toml = "0.5.8"
tungstenite = "0.12.0" tungstenite = "0.12.0"
tokio = { version = "0.3.3", features = ["full"] } tokio = { version = "0.3.3", features = ["full"] }
log = "0.4.14" log = "0.4.14"
@ -24,6 +24,7 @@ async-trait = "0.1.42"
simple_logger = "1.11.0" simple_logger = "1.11.0"
chrono = {version = "0.4.19", features = ["serde"]} chrono = {version = "0.4.19", features = ["serde"]}
uuid = {version = "0.8.2", features = ["serde" , "v4"]} uuid = {version = "0.8.2", features = ["serde" , "v4"]}
regex = "1.4.5"
[dependencies.fcpv2] [dependencies.fcpv2]
path = "../FCPv2" path = "../FCPv2"

3
src/.fcpv2/mod.rs Normal file
View file

@ -0,0 +1,3 @@
mod types;
use types::test;

View file

@ -1,34 +1,47 @@
use super::response::User; use super::response::User;
use super::response::UserList; use super::response::UserList;
use super::{ use super::response::{AppStatus, ResponseType};
response::{AppStatus, ResponseType},
};
use crate::api::request::Request; use crate::api::request::Request;
use crate::chat::init_config;
use crate::chat::types::PackedMessage; use crate::chat::types::PackedMessage;
use crate::chat::types::SP; use crate::chat::types::SP;
use crate::db::{self, messages, types, users}; use crate::db::{self, messages, types, users};
use async_std::io::Result; use async_std::io::Result;
use fcpv2::client::fcp_types::{ClientPut, ClientHello}; use fcpv2::client::fcp_types::{ClientHello, ClientPut};
use fcpv2::types::{ use fcpv2::types::{
traits::{FcpParser, FcpRequest}, traits::{FcpParser, FcpRequest},
SSK, SSK,
}; };
use rusqlite::Connection; use rusqlite::Connection;
use serde_json::json; use serde_json::json;
use std::fs::File;
use std::path::Path;
use std::time::SystemTime; use std::time::SystemTime;
use uuid::Uuid; use uuid::Uuid;
use crate::db::types::Id; use crate::db::types::Id;
pub fn start_app(server_sender: SP) -> Result<()> { pub fn start_app(server_sender: SP) -> Result<()> {
server_sender.send(PackedMessage::ToFreenet(ClientHello::new("start_app_request".to_string(), 2.0).convert())).unwrap(); server_sender
server_sender.send(PackedMessage::ToFreenet("\n\ .send(PackedMessage::ToFreenet(
ClientGet\n\ ClientHello::new("start_app_request".to_string(), 2.0).convert(),
URI=USK@B5CYo9jdAndaZ4IoKdJKCi28bY96f03FhUdY4PO6anY,9AHiE5ZdMJ9BuIXdv7hucus5VbVtwz9tKjj9LcPbtwM,AQACAAE/user-3/0\n\ ))
Identifier=check\n\ .unwrap();
ReturnType=direct\n\ let config_path = Path::new(".hole.toml");
EndMessage\n\ match File::open(&config_path) {
\n".to_string())).unwrap(); Err(e) => {
log::debug!("creating new config file...");
// std::fs::File::create(&config_path).unwrap();
server_sender.send(PackedMessage::ToFreenet(
fcpv2::client::fcp_types::GenerateSSK {
identifier: Some("config-SSK".to_string()),
}
.convert()
)).unwrap()}
,
Ok(res) => {} // TODO converting file from TOML to JSON and sending it to frontend
};
Ok(()) Ok(())
//sending *JSON*, what everything is OK //sending *JSON*, what everything is OK
} }
@ -37,7 +50,7 @@ pub fn stop_app(conn: &Connection, server_sender: SP) -> Result<()> {
std::process::exit(0) std::process::exit(0)
} }
pub fn load_users( conn: &Connection, server_sender: SP) -> Result<()> { pub fn load_users(conn: &Connection, server_sender: SP) -> Result<()> {
let jsoned_users: Vec<_> = users::load_all_users(conn) let jsoned_users: Vec<_> = users::load_all_users(conn)
.unwrap() .unwrap()
.into_iter() .into_iter()
@ -50,7 +63,12 @@ pub fn load_users( conn: &Connection, server_sender: SP) -> Result<()> {
let _ = server_sender.send(PackedMessage::ToClient(users)).unwrap(); let _ = server_sender.send(PackedMessage::ToClient(users)).unwrap();
Ok(()) Ok(())
} }
pub fn send_message(user_id: Id, message: String, conn: &Connection, server_sender: SP) -> Result<()> { pub fn send_message(
user_id: Id,
message: String,
conn: &Connection,
server_sender: SP,
) -> Result<()> {
if let Ok(user_data) = db::users::get_user_by_id(user_id, conn) { if let Ok(user_data) = db::users::get_user_by_id(user_id, conn) {
// Add message to DB // Add message to DB
let key = user_data.insert_key; let key = user_data.insert_key;
@ -85,14 +103,14 @@ pub fn send_message(user_id: Id, message: String, conn: &Connection, server_send
//sending FCP request //sending FCP request
} }
pub fn load_messages(user_id: Id, start_index: u32, count:u32, conn: &Connection, server_sender: SP) -> Result<()> { pub fn load_messages(
let messages = db::messages::select_n_last_messages( user_id: Id,
user_id, start_index: u32,
start_index, count: u32,
count, conn: &Connection,
conn, server_sender: SP,
) ) -> Result<()> {
.unwrap(); let messages = db::messages::select_n_last_messages(user_id, start_index, count, conn).unwrap();
let jsoned = json!(messages); let jsoned = json!(messages);
let _ = server_sender.send(PackedMessage::ToClient(jsoned.to_string())); let _ = server_sender.send(PackedMessage::ToClient(jsoned.to_string()));
Ok(()) Ok(())
@ -100,7 +118,13 @@ pub fn load_messages(user_id: Id, start_index: u32, count:u32, conn: &Connection
//sending *JSON* //sending *JSON*
} }
// Adding user to DB // Adding user to DB
pub fn add_user(name: String, insert_key: String, sign_key: String, conn: &Connection, server_sender: SP) -> Result<()> { pub fn add_user(
name: String,
insert_key: String,
sign_key: String,
conn: &Connection,
server_sender: SP,
) -> Result<()> {
let user = db::types::User { let user = db::types::User {
id: db::types::Id(Uuid::new_v4()), id: db::types::Id(Uuid::new_v4()),
name: name, name: name,

View file

@ -1,10 +1,12 @@
use crate::db::types::SignKey;
use crate::db::types::User as SqliteUser; use crate::db::types::User as SqliteUser;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use tungstenite::http::Response; use tungstenite::http::Response;
use crate::db::types::SignKey;
pub type InsertKey = String; pub type InsertKey = String;
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize, Debug, PartialEq)]
pub enum ResponseType{ #[serde(rename_all = "camelCase")]
#[serde(tag = "type")]
pub enum ResponseType {
Error, Error,
NewMessage, NewMessage,
UserList, UserList,
@ -12,29 +14,31 @@ pub enum ResponseType{
FetchedMessages, FetchedMessages,
InstanceCreated, InstanceCreated,
InstanceAccepted, InstanceAccepted,
UserAdded UserAdded,
InitialConfig {
id: crate::db::types::Id,
public_key: fcpv2::types::SSK,
private_key: fcpv2::types::SSK,
},
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub enum ErrorType{ pub enum ErrorType {
WrongKey, WrongKey,
FailedToAddUser, FailedToAddUser,
WrongUserId WrongUserId,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct AppError{ pub struct AppError {
pub res_type: ErrorType, pub res_type: ErrorType,
} }
// Status of last requested action. Like `Create Instance` or `LoadUsers` // Status of last requested action. Like `Create Instance` or `LoadUsers`
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct AppStatus{ pub struct AppStatus {
pub res_type: ResponseType pub res_type: ResponseType,
} }
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
pub struct User { pub struct User {
pub id: String, pub id: String,
@ -44,8 +48,7 @@ pub struct User {
pub messages_count: u32, pub messages_count: u32,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct UserList{ pub struct UserList {
pub users: Vec<User> pub users: Vec<User>,
} }

View file

@ -1,5 +1,4 @@
use crate::chat::types::PackedMessage; use crate::chat::types::PackedMessage;
use std::sync::{Arc, Mutex};
use crate::db; use crate::db;
use async_std::{ use async_std::{
io, io,
@ -14,6 +13,7 @@ use futures::{
use serde_derive::Deserialize; use serde_derive::Deserialize;
use std::env; use std::env;
use std::sync::mpsc::{Receiver, Sender}; use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex};
use super::stay_awake::request_repeater; use super::stay_awake::request_repeater;
@ -95,16 +95,18 @@ async fn connection_for_receiving(
// log::debug!("they are different"); // log::debug!("they are different");
match res { match res {
PackedMessage::FromCore(json) => { PackedMessage::FromCore(json) => {
async_std::task::block_on(sender async_std::task::block_on(sender.send(Message::Text(json)))
.send(Message::Text(json))).expect("Couldn't send message") .expect("Couldn't send message")
} }
PackedMessage::FromFreenet(response) => { PackedMessage::FromFreenet(response) => {
let r = response.clone(); let r = response.clone();
log::debug!("Got:\n {}", &response); log::debug!("Got:\n {}", &response);
async_std::task::block_on(sender async_std::task::block_on(
sender
// TODO freenet_response_handler // TODO freenet_response_handler
.send(Message::Text(r.to_string()))); .send(Message::Text(r.to_string())),
)
.expect("Couldn't send messge");
// .await // .await
// .expect("Couldn't send messge"); // .expect("Couldn't send messge");
} }

25
src/chat/init.rs Normal file
View file

@ -0,0 +1,25 @@
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use async_std::io;
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Config {
pub id: crate::db::types::Id,
pub public_key: fcpv2::types::SSK,
pub private_key: fcpv2::types::SSK,
}
pub fn init_config(path: &Path) -> io::Result<File> {
let config = File::create(&path).unwrap();
return Ok(config);
}
pub fn update_config(path: &Path, val: &str) -> io::Result<()> {
let mut f = std::fs::File::create(&path)?;
log::debug!("write \n {}", &val);
f.write_all(&val.as_bytes())?;
Ok(())
}

View file

@ -4,3 +4,6 @@ pub mod serv_conn;
pub mod stay_awake; pub mod stay_awake;
pub mod serv_handler; pub mod serv_handler;
pub mod types; pub mod types;
mod init;
pub use init::*;

View file

@ -1,6 +1,7 @@
use super::serv_handler::to_server_sender; use super::serv_handler::to_server_sender;
use crate::chat::types::{PackedMessage, RP, SP}; use crate::chat::types::{PackedMessage, RP, SP};
use async_std::task; use async_std::task;
use fcpv2::types::traits::FcpParser;
use serde_derive::Deserialize; use serde_derive::Deserialize;
use std::env; use std::env;
use tokio::{ use tokio::{
@ -40,12 +41,57 @@ async fn server_responce_getter(mut receiver: OwnedReadHalf, client_sender: SP)
match receiver.read(&mut buffer).await { match receiver.read(&mut buffer).await {
Ok(_) => { Ok(_) => {
// if prev != buffer { // if prev != buffer {
let received = String::from_utf8_lossy(&buffer[..]); let received = String::from_utf8_lossy(&buffer[..]);
log::debug!("gotted {:?}", &received);
let req = received.lines().next().unwrap();
match req {
"SSKKeypair" => {
log::debug!("parsing keypair: {:?}", &req);
let keypair = fcpv2::types::SSKKeypair::parse(&received).unwrap();
match &keypair.identifier[..] {
"config-SSK" => {
log::debug!("got SSKKeypair: {:?}", &keypair);
// TODO generating UUID and inserting it into .hole.toml
let id = uuid::Uuid::new_v4();
let conf = crate::chat::Config {
id: crate::db::types::Id(id),
public_key: keypair.insert_uri.clone(),
private_key: keypair.request_uri.clone(),
};
let config_str = toml::to_string(&conf).unwrap();
log::debug!("create toml config");
let config_json =
crate::api::response::ResponseType::InitialConfig {
id: crate::db::types::Id(id),
public_key: keypair.insert_uri.clone(),
private_key: keypair.request_uri.clone(),
};
log::debug!("create json config");
let config_path = std::path::Path::new(".hole.toml");
// writing new data to .hole.toml
crate::chat::update_config(&config_path, &config_str).unwrap();
log::debug!("rewrite config");
client_sender
.send(PackedMessage::ToClient(
serde_json::to_string(&config_json).unwrap(),
))
.unwrap();
log::debug!("sended config to client");
}
_ => {}
}
}
_ => {
log::debug!("unhandled: {}", &req);
client_sender client_sender
.send(PackedMessage::FromFreenet(received.to_string())) .send(PackedMessage::FromFreenet(received.to_string()))
.expect("Falied to send message to client thread"); .expect("Falied to send message to client thread");
log::info!("Sended to client! {}", received.chars().count()); log::info!("Sended to client! {}", received.chars().count());
}
}
// prev = buffer; // prev = buffer;
// } // }
} }

View file

@ -7,26 +7,29 @@ use std::sync::mpsc::Sender;
type SP = Sender<PackedMessage>; type SP = Sender<PackedMessage>;
pub async fn request_repeater(ss: SP) -> io::Result<()> { pub async fn request_repeater(ss: SP) -> io::Result<()> {
let db = crate::db::start_db().unwrap();
// loop { // loop {
//TODO create a field with tracked users //TODO create a field with tracked users
log::debug!("Request Repeater Started!"); log::debug!("Request Repeater Started!");
loop { loop {
let users: Vec<crate::db::types::User> = crate::db::users::load_all_users(&db).unwrap();
let time = std::time::Duration::from_millis(1300); let time = std::time::Duration::from_millis(1300);
std::thread::sleep(time); std::thread::sleep(time);
log::debug!("enough sleep"); log::debug!("enough sleep");
for user in users {
let id = user.id.0.to_string();
let index = user.messages_count + 1;
match ss.send(PackedMessage::ToFreenet( match ss.send(PackedMessage::ToFreenet(
ClientGet::new_default( ClientGet::new_default(
KEY::USK( KEY::USK(
USK { USK {
ssk: SSK { ssk: user.insert_key,
sign_key: "B5CYo9jdAndaZ4IoKdJKCi28bY96f03FhUdY4PO6anY".to_string(), path: format!("{}/{}", &id, &index),
decrypt_key: "9AHiE5ZdMJ9BuIXdv7hucus5VbVtwz9tKjj9LcPbtwM".to_string(),
settings: Some("AQACAAE".to_string()),
},
path: "user-3/0".to_string(),
} }
), ),
"check", &format!("rec;{};{}", &id, &index)[..], // TODO create Identifier type
ReturnType::Direct, ReturnType::Direct,
) )
.convert(), .convert(),
@ -35,6 +38,7 @@ pub async fn request_repeater(ss: SP) -> io::Result<()> {
Err(e) => continue , Err(e) => continue ,
} }
} }
}
} }
//} //}
// message: format!( // message: format!(

View file

@ -1,3 +0,0 @@
mod types;
pub use types::test;

BIN
src/hole.db Normal file

Binary file not shown.

View file

@ -2,5 +2,5 @@ mod chat;
pub mod db; pub mod db;
pub mod api; pub mod api;
pub mod encrypting; pub mod encrypting;
pub mod fcpv2; //pub mod fcpv2;
pub use chat::front_conn; pub use chat::front_conn;

View file

@ -1,15 +1,13 @@
mod api;
mod chat; mod chat;
mod db; mod db;
mod encrypting; mod encrypting;
mod api;
use async_std::io; use async_std::io;
use chat::front_conn::listen_client; use chat::front_conn::listen_client;
use chat::serv_conn::listen_server; use chat::serv_conn::listen_server;
use chat::types::PackedMessage; use chat::types::PackedMessage;
use chrono::Utc;
use db::users;
use fcpv2::types::{traits::FcpParser, SSK};
use log; use log;
use serde_derive::Deserialize;
use simple_logger::SimpleLogger; use simple_logger::SimpleLogger;
use std::{ use std::{
sync::{ sync::{
@ -46,6 +44,7 @@ use std::{
+-----------------------------------------------------------------------------------+ +-----------------------------------------------------------------------------------+
*/ */
fn main() -> io::Result<()> { fn main() -> io::Result<()> {
SimpleLogger::new().init().unwrap(); SimpleLogger::new().init().unwrap();