finish request_handler function

This commit is contained in:
Horhik 2021-04-06 13:03:57 +03:00
parent 9ef832a332
commit f46404eb7e
5 changed files with 85 additions and 43 deletions

View file

@ -1,6 +1,5 @@
use super::response::User; use super::response::User;
use super::response::UserList; use super::response::UserList;
use std::time::{SystemTime};
use super::{ use super::{
request::*, request::*,
response::{AppStatus, ResponseType}, response::{AppStatus, ResponseType},
@ -9,27 +8,29 @@ 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; use fcpv2::client::fcp_types::{ClientPut, ClientHello};
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::time::SystemTime;
use uuid::Uuid; use uuid::Uuid;
use crate::db::types::Id; use crate::db::types::Id;
pub fn start_app(request: StartAppReq, server_sender: &SP) -> Result<()> { pub fn start_app(request: StartAppReq, server_sender: SP) -> Result<()> {
server_sender.send(PackedMessage::ToFreenet(ClientHello::new("start_app_request".to_string(), 2.0).convert())).unwrap();
Ok(()) Ok(())
//sending *JSON*, what everything is OK //sending *JSON*, what everything is OK
} }
pub fn stop_app(request: StopAppReq, conn: &Connection, server_sender: &SP) -> Result<()> { pub fn stop_app(request: StopAppReq, conn: &Connection, server_sender: SP) -> Result<()> {
std::process::exit(0) std::process::exit(0)
} }
pub fn load_users(request: LoadUsersReq, conn: &Connection, server_sender: &SP) -> Result<()> { pub fn load_users(request: LoadUsersReq, 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()
@ -42,13 +43,13 @@ pub fn load_users(request: LoadUsersReq, conn: &Connection, server_sender: &SP)
let _ = server_sender.send(PackedMessage::ToClient(users)).unwrap(); let _ = server_sender.send(PackedMessage::ToClient(users)).unwrap();
Ok(()) Ok(())
} }
pub fn send_message(request: SendMessageReq, conn: &Connection, server_sender: &SP) -> Result<()> { pub fn send_message(request: SendMessageReq, conn: &Connection, server_sender: SP) -> Result<()> {
if let Ok(user_data) = db::users::get_user_by_id(request.user_id, conn) { if let Ok(user_data) = db::users::get_user_by_id(request.user_id, conn) {
// Add message to DB // Add message to DB
let key = user_data.insert_key; let key = user_data.insert_key;
let identifier = &user_data.id.0.to_string()[..]; let identifier = &user_data.id.0.to_string()[..];
let message_id :u32 = user_data.messages_count; let message_id: u32 = user_data.messages_count;
let db_message = db::types::Message{ let db_message = db::types::Message {
id: message_id, id: message_id,
date: chrono::offset::Local::now(), date: chrono::offset::Local::now(),
user_id: Id(uuid::Uuid::parse_str(identifier).unwrap()), user_id: Id(uuid::Uuid::parse_str(identifier).unwrap()),
@ -77,11 +78,7 @@ pub fn send_message(request: SendMessageReq, conn: &Connection, server_sender: &
//sending FCP request //sending FCP request
} }
pub fn load_messages( pub fn load_messages(request: LoadMessagesReq, conn: &Connection, server_sender: SP) -> Result<()> {
request: LoadMessagesReq,
conn: &Connection,
server_sender: &SP,
) -> Result<()> {
let messages = db::messages::select_n_last_messages( let messages = db::messages::select_n_last_messages(
request.user_id, request.user_id,
request.start_index, request.start_index,
@ -96,7 +93,7 @@ pub fn load_messages(
//sending *JSON* //sending *JSON*
} }
// Adding user to DB // Adding user to DB
pub fn add_user(request: AddUserReq, conn: &Connection, server_sender: &SP) -> Result<()> { pub fn add_user(request: AddUserReq, 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: request.name, name: request.name,

View file

@ -6,48 +6,60 @@ use serde_json::Result;
type Id = crate::db::types::Id; type Id = crate::db::types::Id;
#[derive(Serialize, Deserialize, Debug, PartialEq)] #[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CreateInstance; pub struct CreateInstance;
#[derive(Serialize, Deserialize, Debug, PartialEq)] #[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SendMessage; pub struct SendMessage;
#[derive(Serialize, Deserialize, Debug, PartialEq)] #[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LoadUsers; pub struct LoadUsers;
#[derive(Serialize, Deserialize, Debug, PartialEq)] #[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LoadMessages; pub struct LoadMessages;
#[derive(Serialize, Deserialize, Debug, PartialEq)] #[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AddUser; pub struct AddUser;
#[derive(Serialize, Deserialize, Debug, PartialEq)] #[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct StartApp; pub struct StartApp;
#[derive(Serialize, Deserialize, Debug, PartialEq)] #[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct StopApp; pub struct StopApp;
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CreateInstanceReq { pub struct CreateInstanceReq {
pub req_type: CreateInstance, pub req_type: CreateInstance,
pub name: String, pub name: String,
} }
#[derive(Deserialize, Debug, PartialEq)] #[derive(Deserialize, Serialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct StartAppReq { pub struct StartAppReq {
pub req_type: StartApp, pub req_type: StartApp,
} }
#[derive(Deserialize, Debug, PartialEq)] #[derive(Deserialize,Serialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct StopAppReq { pub struct StopAppReq {
pub(crate) req_type: StopApp, pub(crate) req_type: StopApp,
} }
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct LoadUsersReq { pub struct LoadUsersReq {
pub req_type: LoadUsers, pub req_type: LoadUsers,
} }
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SendMessageReq { pub struct SendMessageReq {
pub req_type: SendMessage, pub req_type: SendMessage,
pub user_id: Id, pub user_id: Id,
@ -55,6 +67,7 @@ pub struct SendMessageReq {
} }
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct LoadMessagesReq { pub struct LoadMessagesReq {
pub req_type: LoadMessages, pub req_type: LoadMessages,
pub user_id: Id, pub user_id: Id,
@ -63,9 +76,28 @@ pub struct LoadMessagesReq {
} }
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct AddUserReq { pub struct AddUserReq {
pub req_type: AddUser, pub req_type: AddUser,
pub name: String, pub name: String,
pub sign_key: String, pub sign_key: String,
pub insert_key: String, pub insert_key: String,
} }
#[test]
fn request_StoppApp_are_correct() {
let json: &str = "{'reqType':'StopApp'}";
//log::info!("{} and {}", json, tjsn);
//assert_eq!(jsoned, StopAppReq{req_type: StopApp});
//assert_eq!(json,tjsn);
}
#[test]
fn request_StartApp_are_correct() {}
#[test]
fn request_LoadUsers_are_correct() {}
#[test]
fn request_SendMessage_are_correct() {}
#[test]
fn request_LoadMessages_are_correct() {}
#[test]
fn request_AddUser_are_correct() {}

View file

@ -11,32 +11,29 @@ use rusqlite::Connection;
use serde_json::from_str; use serde_json::from_str;
use serde_json::json; use serde_json::json;
// server_sender sending data to server thread; // server_sender sending data to server thread;
pub async fn request_selector(json: String, server_sender: &SP, conn: &Connection) -> Result<()> { pub fn request_selector(json: String, server_sender: SP, conn: &Connection) -> Result<()> {
// if let Ok(res) = from_str::<CreateInstanceReq>(&json) { // if let Ok(res) = from_str::<CreateInstanceReq>(&json) {
//TODO v0.3 Add Instances return Ok(()); //TODO v0.3 Add Instances return Ok(());
// } // }
log::info!("matching request...");
if let Ok(res) = from_str::<StartAppReq>(&json) { if let Ok(res) = from_str::<StartAppReq>(&json) {
handlers::start_app(res, server_sender)? handlers::start_app(res, server_sender.clone())?
} } else if let Ok(res) = from_str::<StopAppReq>(&json) {
if let Ok(res) = from_str::<StopAppReq>(&json) { handlers::stop_app(res, conn, server_sender.clone())?
handlers::stop_app(res, conn, server_sender)? } else if let Ok(res) = from_str::<LoadUsersReq>(&json) {
} handlers::load_users(res, conn, server_sender.clone())?
if let Ok(res) = from_str::<LoadUsersReq>(&json) { } else if let Ok(res) = from_str::<SendMessageReq>(&json) {
handlers::load_users(res, conn, server_sender)? handlers::send_message(res, conn, server_sender.clone())?
} } else if let Ok(res) = from_str::<LoadMessagesReq>(&json) {
if let Ok(res) = from_str::<SendMessageReq>(&json) { handlers::load_messages(res, conn, server_sender.clone())?
handlers::send_message(res, conn, server_sender)? } else if let Ok(res) = from_str::<AddUserReq>(&json) {
} match handlers::add_user(res, conn, server_sender.clone()) {
if let Ok(res) = from_str::<LoadMessagesReq>(&json) { Ok(_) => return Ok(()),
handlers::load_messages(res, conn, server_sender)?
}
if let Ok(res) = from_str::<AddUserReq>(&json) {
match handlers::add_user(res, conn, server_sender) {
Ok(_) => {},
Err(e) => { Err(e) => {
// Sending error to user, because failed to add user // Sending error to user, because failed to add user
let _ = server_sender let _ = server_sender
.clone()
.send(PackedMessage::ToClient( .send(PackedMessage::ToClient(
json!(AppError { json!(AppError {
res_type: ErrorType::FailedToAddUser res_type: ErrorType::FailedToAddUser
@ -44,11 +41,15 @@ pub async fn request_selector(json: String, server_sender: &SP, conn: &Connectio
.to_string(), .to_string(),
)) ))
.unwrap(); .unwrap();
return Ok(());
} }
} }
} else {
log::error!("{}\n is wrong formatted", json)
} }
Err(async_std::io::Error::new( Err(async_std::io::Error::new(
async_std::io::ErrorKind::InvalidData, async_std::io::ErrorKind::InvalidData,
"Wrong request", serde_json::to_string(&StartAppReq{req_type: StartApp}).unwrap(),
)) ))
} }

View file

@ -91,13 +91,14 @@ async fn connection_for_receiving(
.await .await
.expect("Couldn't send message"); .expect("Couldn't send message");
} }
PackedMessage::FromFreenet(response) => {sender PackedMessage::FromFreenet(response) => {
// TODO freenet_response_handler sender
.send(Message::Text(response)) // TODO freenet_response_handler
.await .send(Message::Text(response))
.expect("Couldn't send messge"); .await
.expect("Couldn't send messge");
} }
_ => {}, _ => {}
} }
} }
Ok(()) Ok(())
@ -113,7 +114,14 @@ async fn connection_for_sending(
loop { loop {
if let Some(msg) = new_msg.await { if let Some(msg) = new_msg.await {
let jsoned = msg.expect("Falied to unwrap gotted message"); let jsoned = msg.expect("Falied to unwrap gotted message");
request_selector(jsoned.to_string(), &server_sender, &conn); log::info!("new request");
match request_selector(jsoned.to_string(), server_sender.clone(), &conn) {
Ok(_) => {}
Err(e) => {
log::error!("{}", e);
}
};
/* /*
let res: serde_json::Result<FrontMsg> = let res: serde_json::Result<FrontMsg> =
serde_json::from_str(jsoned.to_text().expect("Falied to parse JSON")); serde_json::from_str(jsoned.to_text().expect("Falied to parse JSON"));
@ -139,7 +147,10 @@ async fn connection_for_sending(
new_msg = receiver.next(); new_msg = receiver.next();
} else { } else {
{ {
break; return Err(async_std::io::Error::new(
async_std::io::ErrorKind::InvalidData,
"failed to unwrap message",
));
} }
} }
} }

View file

@ -32,6 +32,7 @@ use std::sync::mpsc::{Receiver, Sender};
// } // }
//} //}
pub enum PackedMessage { pub enum PackedMessage {
ToFreenet(String), ToFreenet(String),
FromFreenet(String), FromFreenet(String),