handle add_user function

This commit is contained in:
Horhik 2021-03-31 07:12:26 +03:00
parent e582194b25
commit b2f8474c97
10 changed files with 113 additions and 39 deletions

View file

@ -13,22 +13,18 @@
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Cargo.lock" beforeDir="false" afterPath="$PROJECT_DIR$/Cargo.lock" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Cargo.toml" beforeDir="false" afterPath="$PROJECT_DIR$/Cargo.toml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/chat/front_conn.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/chat/front_conn.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/chat/mod.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/chat/mod.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/api/handlers.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/api/handlers.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/api/request.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/api/request.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/api/response.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/api/response.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/chat/serv_conn.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/chat/serv_conn.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/chat/types.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/chat/types.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/db/mod.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/db/mod.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/lib.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/lib.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/main.rs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/db/types.rs" beforeDir="false" afterPath="$PROJECT_DIR$/src/db/types.rs" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ClangdSettings">
<option name="formatViaClangd" value="false" />
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
@ -46,7 +42,7 @@
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="cf.first.check.clang-format" value="false" />
<property name="last_opened_file_path" value="$PROJECT_DIR$/../../../olymp/mosh" />
<property name="last_opened_file_path" value="$PROJECT_DIR$" />
<property name="nodejs_package_manager_path" value="npm" />
<property name="org.rust.cargo.project.model.PROJECT_DISCOVERY" value="true" />
</component>
@ -88,6 +84,7 @@
<workItem from="1613570542642" duration="4470000" />
<workItem from="1614190476350" duration="9000" />
<workItem from="1614277959074" duration="31000" />
<workItem from="1617097697890" duration="1371000" />
</task>
<servers />
</component>

11
Cargo.lock generated
View file

@ -647,6 +647,7 @@ dependencies = [
"tokio 0.3.6",
"toml",
"tungstenite 0.12.0",
"uuid",
]
[[package]]
@ -1605,6 +1606,16 @@ version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05e42f7c18b8f902290b009cde6d651262f956c98bc51bca4cd1d511c9cd85c7"
[[package]]
name = "uuid"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7"
dependencies = [
"getrandom 0.2.1",
"serde",
]
[[package]]
name = "value-bag"
version = "1.0.0-alpha.6"

View file

@ -23,6 +23,7 @@ serde_derive = "1.0.116"
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"]}
[dependencies.fcpv2]
path = "../FCPv2"

View file

@ -1,12 +1,14 @@
use super::request::*;
use super::{request::*, response::{AppStatus, ResponseType}};
use super::response::User;
use super::response::UserList;
use crate::chat::types::PackedMessage;
use crate::chat::types::SP;
use crate::db::{messages, users};
use crate::db::{self, messages, types, users};
use async_std::io::Result;
use fcpv2::types::{traits::FcpParser, SSK};
use rusqlite::Connection;
use serde_json::json;
use uuid::Uuid;
pub fn start_app(request: StartAppReq, server_sender: &SP) -> Result<()> {
Ok(())
//sending *JSON*, what everything is OK
@ -24,8 +26,9 @@ pub fn load_users(request: LoadUsersReq, conn: &Connection, server_sender: &SP)
.collect();
let users: String = serde_json::to_string(&UserList {
users: jsoned_users,
}).unwrap();
let _ =server_sender.send(PackedMessage::ToClient(users)).unwrap();
})
.unwrap();
let _ = server_sender.send(PackedMessage::ToClient(users)).unwrap();
Ok(())
}
pub fn send_message(request: SendMessageReq, conn: &Connection, server_sender: &SP) -> Result<()> {
@ -42,6 +45,14 @@ pub fn load_messages(
//sending *JSON*
}
pub fn add_user(request: AddUserReq, conn: &Connection, server_sender: &SP) -> Result<()> {
unimplemented!()
//sending *JSON* what user is created
let user = db::types::User {
id: db::types::Id(Uuid::new_v4()),
name: request.name,
sign_key: request.sign_key,
insert_key: SSK::parse(&request.insert_key[..]).unwrap(),
messages_count: 0,
};
db::users::add_user(user, &conn).unwrap();
server_sender.send(PackedMessage::ToClient(json!(AppStatus{res_type: ResponseType::UserAdded}).to_string())).unwrap();
Ok(())
}

View file

@ -62,6 +62,7 @@ pub struct LoadMessagesReq {
#[derive(Deserialize, Debug)]
pub struct AddUserReq {
pub req_type: AddUser,
pub name: String,
pub sign_key: String,
pub insert_key: String,
}

View file

@ -1,9 +1,10 @@
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)]
enum ResponseType{
pub enum ResponseType{
Error,
NewMessage,
UserList,
@ -11,27 +12,30 @@ enum ResponseType{
FetchedMessages,
InstanceCreated,
InstanceAccepted,
UserAdded
}
#[derive(Serialize, Deserialize)]
enum ErrorType{
WrongKey
pub enum ErrorType{
WrongKey,
FailedToAddUser
}
#[derive(Serialize, Deserialize)]
struct AppError{
res_type: ResponseType,
pub struct AppError{
pub res_type: ErrorType,
}
// Status of last requested action. Like `Create Instance` or `LoadUsers`
struct ActionStatus{
#[derive(Serialize, Deserialize)]
pub struct AppStatus{
pub res_type: ResponseType
}
#[derive(Debug, Deserialize, Serialize)]
pub struct User {
pub id: u32,
pub id: String,
pub name: String,
pub sign_key: SignKey,
pub insert_key: InsertKey,

View file

@ -1,7 +1,11 @@
use crate::chat::types::SP;
use crate::chat::types::{PackedMessage, SP};
use rusqlite;
use super::{request::*, handlers};
use super::{
handlers,
request::*,
response::{AppError, ErrorType, ResponseType},
};
use async_std::io::Result;
use rusqlite::Connection;
use serde_json::from_str;
@ -12,12 +16,11 @@ pub async fn request_selector(json: String, server_sender: &SP, conn: &Connectio
//TODO v0.3 Add Instances return Ok(());
// }
if let Ok(res) = from_str::<StartAppReq>(&json) {
handlers::start_app(res, server_sender)?
if let Ok(res) = from_str::<StartAppReq>(&json) {
handlers::start_app(res, server_sender)?
}
if let Ok(res) = from_str::<StopAppReq>(&json) {
handlers::stop_app(res, conn, server_sender)?
}
if let Ok(res) = from_str::<LoadUsersReq>(&json) {
handlers::load_users(res, conn, server_sender)?
@ -29,11 +32,22 @@ pub async fn request_selector(json: String, server_sender: &SP, conn: &Connectio
handlers::load_messages(res, conn, server_sender)?
}
if let Ok(res) = from_str::<AddUserReq>(&json) {
handlers::add_user(res, conn, server_sender)?
match handlers::add_user(res, conn, server_sender) {
Ok(_) => {},
Err(e) => {
let _ = server_sender
.send(PackedMessage::ToClient(
json!(AppError {
res_type: ErrorType::FailedToAddUser
})
.to_string(),
))
.unwrap();
}
}
}
Err(async_std::io::Error::new(
async_std::io::ErrorKind::InvalidData,
"Wrong request",
))
}

View file

@ -30,6 +30,8 @@ async fn connect_to_server(client_sender: SP, server_receiver: RP) -> io::Result
}
async fn server_responce_getter(mut receiver: OwnedReadHalf, client_sender: SP) -> io::Result<()> {
loop {
// each freenet responce have an identifier and program will define what to do with request by this identifier
//TODO create handle_fcp_response function
let mut buffer = [0; 1024];
match receiver.read(&mut buffer).await {
Ok(_) => {

View file

@ -1,6 +1,13 @@
use std::io;
use chrono::prelude::*;
use fcpv2::types::{traits::FcpRequest, SSK};
use serde_derive::{Serialize, Deserialize};
use fcpv2::types::{traits::{FcpRequest, FcpParser}, SSK};
use rusqlite::{
types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef},
Result, ToSql,
};
use serde_derive::{Deserialize, Serialize};
use uuid::Uuid;
use crate::api::response::User as JsonableUser;
@ -8,26 +15,52 @@ pub const DB_PATH: &str = "hole.db";
pub type SignKey = String;
pub type InsertKey = SSK;
#[derive(Debug, Deserialize, Serialize)]
pub struct Id(pub uuid::Uuid);
#[derive(Debug, Deserialize, Serialize)]
pub struct User {
pub id: u32,
pub id: Id,
pub name: String,
pub sign_key: SignKey,
pub insert_key: InsertKey,
pub messages_count: u32,
}
impl User{
pub fn to_jsonable(self) -> JsonableUser{
JsonableUser{
id: self.id,
/// converting SSK to rusqlite type
impl ToSql for Id {
fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
Ok(ToSqlOutput::from(self.0.to_string()))
}
}
/// converting from rusqlite type to SSK
impl FromSql for Id {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Id> {
let id = Uuid::parse_str(&(value.as_str()?)[..]).unwrap();
Ok(Id(id))
}
}
impl User {
pub fn to_jsonable(self) -> JsonableUser {
JsonableUser {
id: self.id.0.to_string(),
name: self.name,
sign_key: self.sign_key,
insert_key: SSK::convert(&self.insert_key),
messages_count: self.messages_count
messages_count: self.messages_count,
}
}
pub fn from_jsonable(json: JsonableUser) -> io::Result<User> {
Ok(User {
id: Id(Uuid::parse_str(&json.id[..]).unwrap()),
name: json.name,
sign_key: json.sign_key,
insert_key: SSK::parse(&json.insert_key[..]).unwrap(),
messages_count: json.messages_count,
})
}
}
#[derive(Debug, Deserialize, Serialize)]