rewite json request matching

This commit is contained in:
Horhik 2021-04-12 17:05:11 +03:00
parent 724d7ef154
commit f876588add
4 changed files with 51 additions and 101 deletions

View file

@ -1,9 +1,9 @@
use super::response::User; use super::response::User;
use super::response::UserList; use super::response::UserList;
use super::{ use super::{
request::*,
response::{AppStatus, ResponseType}, response::{AppStatus, ResponseType},
}; };
use crate::api::request::Request;
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};
@ -20,17 +20,17 @@ 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(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(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(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( 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()
@ -43,8 +43,8 @@ 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(user_id: Id, message: String, 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(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()[..];
@ -53,12 +53,12 @@ pub fn send_message(request: SendMessageReq, conn: &Connection, server_sender: S
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()),
message: request.message.clone(), message: message.clone(),
from_me: false, from_me: false,
}; };
let _ = db::messages::add_my_message(db_message, conn).unwrap(); let _ = db::messages::add_my_message(db_message, conn).unwrap();
let fcp_req: String = let fcp_req: String =
ClientPut::new_default_direct(key, identifier, &request.message[..]).convert(); ClientPut::new_default_direct(key, identifier, &message[..]).convert();
server_sender server_sender
.send(PackedMessage::ToFreenet(fcp_req)) .send(PackedMessage::ToFreenet(fcp_req))
.unwrap(); .unwrap();
@ -78,11 +78,11 @@ pub fn send_message(request: SendMessageReq, conn: &Connection, server_sender: S
//sending FCP request //sending FCP request
} }
pub fn load_messages(request: LoadMessagesReq, conn: &Connection, server_sender: SP) -> Result<()> { 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( let messages = db::messages::select_n_last_messages(
request.user_id, user_id,
request.start_index, start_index,
request.count, count,
conn, conn,
) )
.unwrap(); .unwrap();
@ -93,12 +93,12 @@ pub fn load_messages(request: LoadMessagesReq, conn: &Connection, server_sender:
//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(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: request.name, name: name,
sign_key: request.sign_key, sign_key: sign_key,
insert_key: SSK::parse(&request.insert_key[..]).unwrap(), insert_key: SSK::parse(&insert_key[..]).unwrap(),
messages_count: 0, messages_count: 0,
}; };
db::users::add_user(user, &conn).unwrap(); db::users::add_user(user, &conn).unwrap();

View file

@ -8,7 +8,7 @@ use crate::db::types::Id;
#[derive(Serialize, Deserialize, Debug, PartialEq)] #[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
#[serde(tag = "type")] #[serde(tag = "type")]
enum Request { pub enum Request {
StartApp, StartApp,
StopApp, StopApp,
LoadUsers, LoadUsers,
@ -31,85 +31,6 @@ enum Request {
}, // CreateInstance TODO v0.3 }, // CreateInstance TODO v0.3
} }
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CreateInstance;
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SendMessage;
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LoadUsers;
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LoadMessages;
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AddUser;
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct StartApp;
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct StopApp;
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CreateInstanceReq {
pub req_type: CreateInstance,
pub name: String,
}
#[derive(Deserialize, Serialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct StartAppReq {
pub req_type: StartApp,
}
#[derive(Deserialize, Serialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct StopAppReq {
pub(crate) req_type: StopApp,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct LoadUsersReq {
pub req_type: LoadUsers,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SendMessageReq {
pub req_type: SendMessage,
pub user_id: Id,
pub message: String,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct LoadMessagesReq {
pub req_type: LoadMessages,
pub user_id: Id,
pub count: u32,
pub start_index: u32,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct AddUserReq {
pub req_type: AddUser,
pub name: String,
pub sign_key: String,
pub insert_key: String,
}
#[test] #[test]
fn request_StoppApp_are_correct() { fn request_StoppApp_are_correct() {
let json = "{\"type\":\"stopApp\"}"; let json = "{\"type\":\"stopApp\"}";

View file

@ -1,7 +1,7 @@
use crate::chat::types::{PackedMessage, SP}; use rusqlite; use crate::chat::types::{PackedMessage, SP}; use rusqlite;
use super::{ use super::{
handlers, handlers,
request::*, request::Request,
response::{AppError, ErrorType, ResponseType}, response::{AppError, ErrorType, ResponseType},
}; };
use async_std::io::Result; use async_std::io::Result;
@ -9,13 +9,41 @@ 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 fn request_selector(json: String, server_sender: SP, conn: &Connection) -> Result<()> { pub fn request_selector(json: &str, 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..."); log::info!("matching request...");
let parsed: Request = serde_json::from_str(json).unwrap();
match parsed{
Request::StartApp => {
handlers::start_app(server_sender.clone())?
},
Request::StopApp => {
handlers::stop_app(&conn, server_sender.clone())?
},
Request::LoadUsers => {
handlers::load_users(&conn, server_sender.clone())?
},
Request::SendMessage {
user_id, message
} => {
handlers::send_message(user_id, message, &conn, server_sender.clone())?
},
Request::LoadMessages{
user_id, count, start_index
} => {
handlers::load_messages(user_id, start_index, count, &conn, server_sender.clone())?
},
Request::AddUser{
name, sign_key, insert_key
} => {
handlers::add_user(name, insert_key, sign_key, &conn, server_sender.clone())?
},
}
if let Ok(res) = from_str::<StartAppReq>(&json) { /*
if let Ok(res) = from_str::<StartAppReq>(&json) {kk
handlers::start_app(res, server_sender.clone())? handlers::start_app(res, server_sender.clone())?
} else if let Ok(res) = from_str::<StopAppReq>(&json) { } else if let Ok(res) = from_str::<StopAppReq>(&json) {
handlers::stop_app(res, conn, server_sender.clone())? handlers::stop_app(res, conn, server_sender.clone())?
@ -45,9 +73,10 @@ pub fn request_selector(json: String, server_sender: SP, conn: &Connection) -> R
} else { } else {
log::error!("{}\n is wrong formatted", json) 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,
serde_json::to_string(&StartAppReq{req_type: StartApp}).unwrap(), serde_json::to_string(&Request::StartApp).unwrap(),
)) ))
} }

View file

@ -115,7 +115,7 @@ async fn connection_for_sending(
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");
log::info!("new request"); log::info!("new request");
match request_selector(jsoned.to_string(), server_sender.clone(), &conn) { match request_selector(&jsoned.to_string()[..], server_sender.clone(), &conn) {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
log::error!("{}", e); log::error!("{}", e);