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

View file

@ -9,7 +9,7 @@ edition = "2018"
[dependencies]
ntru = "0.5.6"
rusqlite = {version = "0.24.2", features = ["chrono"]}
toml = "0.5.6"
toml = "0.5.8"
tungstenite = "0.12.0"
tokio = { version = "0.3.3", features = ["full"] }
log = "0.4.14"
@ -24,6 +24,7 @@ async-trait = "0.1.42"
simple_logger = "1.11.0"
chrono = {version = "0.4.19", features = ["serde"]}
uuid = {version = "0.8.2", features = ["serde" , "v4"]}
regex = "1.4.5"
[dependencies.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::UserList;
use super::{
response::{AppStatus, ResponseType},
};
use super::response::{AppStatus, ResponseType};
use crate::api::request::Request;
use crate::chat::init_config;
use crate::chat::types::PackedMessage;
use crate::chat::types::SP;
use crate::db::{self, messages, types, users};
use async_std::io::Result;
use fcpv2::client::fcp_types::{ClientPut, ClientHello};
use fcpv2::client::fcp_types::{ClientHello, ClientPut};
use fcpv2::types::{
traits::{FcpParser, FcpRequest},
SSK,
};
use rusqlite::Connection;
use serde_json::json;
use std::fs::File;
use std::path::Path;
use std::time::SystemTime;
use uuid::Uuid;
use crate::db::types::Id;
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.send(PackedMessage::ToFreenet("\n\
ClientGet\n\
URI=USK@B5CYo9jdAndaZ4IoKdJKCi28bY96f03FhUdY4PO6anY,9AHiE5ZdMJ9BuIXdv7hucus5VbVtwz9tKjj9LcPbtwM,AQACAAE/user-3/0\n\
Identifier=check\n\
ReturnType=direct\n\
EndMessage\n\
\n".to_string())).unwrap();
server_sender
.send(PackedMessage::ToFreenet(
ClientHello::new("start_app_request".to_string(), 2.0).convert(),
))
.unwrap();
let config_path = Path::new(".hole.toml");
match File::open(&config_path) {
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(())
//sending *JSON*, what everything is OK
}
@ -37,7 +50,7 @@ pub fn stop_app(conn: &Connection, server_sender: SP) -> Result<()> {
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)
.unwrap()
.into_iter()
@ -50,7 +63,12 @@ pub fn load_users( conn: &Connection, server_sender: SP) -> Result<()> {
let _ = server_sender.send(PackedMessage::ToClient(users)).unwrap();
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) {
// Add message to DB
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
}
pub fn load_messages(user_id: Id, start_index: u32, count:u32, conn: &Connection, server_sender: SP) -> Result<()> {
let messages = db::messages::select_n_last_messages(
user_id,
start_index,
count,
conn,
)
.unwrap();
pub fn load_messages(
user_id: Id,
start_index: u32,
count: u32,
conn: &Connection,
server_sender: SP,
) -> Result<()> {
let messages = db::messages::select_n_last_messages(user_id, start_index, count, conn).unwrap();
let jsoned = json!(messages);
let _ = server_sender.send(PackedMessage::ToClient(jsoned.to_string()));
Ok(())
@ -100,7 +118,13 @@ pub fn load_messages(user_id: Id, start_index: u32, count:u32, conn: &Connection
//sending *JSON*
}
// 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 {
id: db::types::Id(Uuid::new_v4()),
name: name,

View file

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

View file

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

View file

@ -1,6 +1,7 @@
use super::serv_handler::to_server_sender;
use crate::chat::types::{PackedMessage, RP, SP};
use async_std::task;
use fcpv2::types::traits::FcpParser;
use serde_derive::Deserialize;
use std::env;
use tokio::{
@ -40,13 +41,58 @@ async fn server_responce_getter(mut receiver: OwnedReadHalf, client_sender: SP)
match receiver.read(&mut buffer).await {
Ok(_) => {
// if prev != buffer {
let received = String::from_utf8_lossy(&buffer[..]);
log::debug!("gotted {:?}", &received);
client_sender
.send(PackedMessage::FromFreenet(received.to_string()))
.expect("Falied to send message to client thread");
log::info!("Sended to client! {}", received.chars().count());
// prev = buffer;
let received = String::from_utf8_lossy(&buffer[..]);
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
.send(PackedMessage::FromFreenet(received.to_string()))
.expect("Falied to send message to client thread");
log::info!("Sended to client! {}", received.chars().count());
}
}
// prev = buffer;
// }
}
Err(e) => log::error!("Error: {} ", e),

View file

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

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 api;
pub mod encrypting;
pub mod fcpv2;
//pub mod fcpv2;
pub use chat::front_conn;

View file

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