create api structures

This commit is contained in:
Horhik 2021-03-24 10:32:31 +03:00
parent 3146d1364b
commit 0a34a0b210
12 changed files with 123 additions and 62 deletions

1
src/api/handler.rs Normal file
View file

@ -0,0 +1 @@
use rusqlite;

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

@ -0,0 +1,3 @@
pub mod request;
pub mod response;

63
src/api/request.rs Normal file
View file

@ -0,0 +1,63 @@
use fcpv2::types::SSK;
use serde_json::Result;
use serde_derive::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct Address {
street: String,
city: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum RequestType {
CreateInstance,
StartApp,
StopApp,
SendMessage,
LoadUsers,
LoadMessages,
AddUser,
}
#[derive(Deserialize, Debug)]
struct CreateInstance {
req_type: RequestType,
name: String,
}
#[derive(Deserialize, Debug)]
struct StartApp {
req_type: RequestType,
}
#[derive(Deserialize, Debug)]
struct StopApp {
req_type: RequestType,
}
#[derive(Deserialize, Debug)]
struct SendMessage {
req_type: RequestType,
user_id: u32,
message: String,
}
#[derive(Deserialize, Debug)]
struct LoadUsers {
req_type: RequestType,
}
#[derive(Deserialize, Debug)]
struct LoadMessages {
req_type: RequestType,
user_id: u32,
count: u8,
start_index: u8,
}
#[derive(Deserialize, Debug)]
struct AddUser {
req_type: RequestType,
sign_key: String,
insert_key: String,
}

View file

@ -0,0 +1 @@
use

27
src/api/response.rs Normal file
View file

@ -0,0 +1,27 @@
use serde_derive::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
enum ResponseType{
Error,
NewMessage,
UserList,
NewUser,
FetchedMessages,
InstanceCreated,
InstanceAccepted,
}
#[derive(Serialize, Deserialize)]
enum ErrorType{
WrongKey
}
#[derive(Serialize, Deserialize)]
struct AppError{
res_type: ResponseType,
}
// Status of last requested action. Like `Create Instance` or `LoadUsers`
struct ActionStatus{
}

1
src/api/types.rs Normal file
View file

@ -0,0 +1 @@
pub use super::request_types;

View file

@ -44,13 +44,14 @@ async fn connect_to_client(server_sender: SP, client_receiver: RP) -> io::Result
let addr = stream
.peer_addr()
.expect("connected streams should have a peer address");
println!("Peer address: {}", addr);
log::info!("Peer address: {}", addr);
let ws = accept_async(stream)
.await
.expect("err during the ws handshake");
log::info!("connected to: {}", addr);
let (sender, receiver) = ws.split();
println!("connected to: {}", addr);
let t1 = task::spawn(connection_for_sending(receiver, server_sender));
connection_for_receiving(sender, client_receiver, client_repeater).await?;
@ -65,18 +66,19 @@ async fn connection_for_receiving(
client_receiver: RP,
server_sender: SP,
) -> io::Result<()> {
log::info!("Connection for receiving launched");
while let Ok(res) = client_receiver.recv() {
//TODO call client get after receiving NodeHello
if res.message.lines().next() == Some("NodeHello") {
let server_sender = server_sender.clone();
task::spawn(request_repeater(server_sender)).await?;
println!("HEY NODE HELLO \n {}", res.message);
log::info!("Client received: \n {}", res.message);
}
sender
.send(Message::Text(String::from(res.message).to_owned()))
.await
.expect("ooops");
.expect("couldn't send Message");
}
Ok(())
}
@ -85,29 +87,32 @@ async fn connection_for_sending(
mut receiver: SplitStream<WebSocketStream<TcpStream>>,
server_sender: SP,
) -> io::Result<()> {
log::info!("Connection for sending launched");
let mut new_msg = receiver.next();
loop {
match new_msg.await {
Some(msg) => {
let jsoned = msg.unwrap();
let jsoned = msg.expect("Falied to unwrap gotted message");
log::info!("The message is: {:?}", &jsoned);
//TODO handle_request(jsoned, server_sender,);
let res: serde_json::Result<FrontMsg> =
serde_json::from_str(jsoned.to_text().unwrap());
serde_json::from_str(jsoned.to_text().expect("Falied to parse JSON"));
if let Ok(received_msg) = res {
let msg = received_msg.message;
db::start_db().unwrap();
//db::start_db().expect("Failed to start db");
server_sender.send(PackedMessage { message: msg }).unwrap();
server_sender.send(PackedMessage { message: msg }).expect("Falied to send message");
/* message example
{
"user_id": 123456789,
"receiver_id": 123456789,
"message": "hey dude",
"message": "STARTAPP!",
"time": "Tue Oct 13 2020 18:31:22 GMT+0300 (Eastern European Summer Time)"
}
*/
} else {
println!("seems, that messsage formatted wrong");
println!("{:?}", res);
log::info!("seems, that messsage formatted wrong");
log::info!("{:?}", res);
}
new_msg = receiver.next();

View file

@ -33,14 +33,15 @@ async fn server_responce_getter(mut receiver: OwnedReadHalf, client_sender: SP)
match receiver.read(&mut buffer).await {
Ok(_) => {
let received = String::from_utf8_lossy(&buffer[..]);
println!("received {}", received);
log::info!("received {}", received);
client_sender
.send(PackedMessage {
message: received.to_string(),
})
.unwrap();
.expect("Falied to send message to client thread");
log::info!("Sended to client!");
}
Err(e) => println!("Error: {} ", e),
Err(e) => log::error!("Error: {} ", e),
}
}
}

View file

@ -19,7 +19,7 @@ pub async fn to_server_sender(mut sender: OwnedWriteHalf, server_receiver: RP) -
} else if res.message.lines().next() == Some("ClientGet") {
let _ = sender.write(res.message.as_bytes()).await?;
} else {
//println!("{:?}", res.message);
//log::info!("{:?}", res.message);
let key = SSK::parse("KSK@msg23.txt").unwrap();
let cp = ClientPut::new_default(key, "msg23.txt", "hello", &res.message[..]).convert();
let _ = sender.write(cp.as_bytes()).await;

View file

@ -25,7 +25,7 @@ pub async fn request_repeater(ss: SP) -> io::Result<()> {
// ),
}) {
Ok(_) => {}
Err(e) => println!("{:?}", e),
Err(e) => log::error!("{:?}", e),
}
}
}

View file

@ -1,6 +1,6 @@
mod chat;
pub mod db;
pub mod api;
pub mod encrypting;
pub mod fcpv2;
pub use chat::front_conn;

View file

@ -1,6 +1,7 @@
mod chat;
mod db;
mod encrypting;
mod api;
use async_std::io;
use chat::front_conn::listen_client;
use chat::serv_conn::listen_server;
@ -47,50 +48,8 @@ use std::{
fn main() -> io::Result<()> {
SimpleLogger::new().init().unwrap();
let conn = db::start_db().unwrap();
/*
users::add_user(db::types::User{
id: 9349,
name: "Nick".to_string(),
sign_key: "string".to_string(),
insert_key: fcpv2::types::SSK::parse("SSK@Rgt0qM8D24DltliV2-JE9tYLcrgGAKeDwkz41I3JBPs,p~c8c7FXcJjhcf2vA-Xm0Mjyw1o~xn7L2-T8zlBA1IU").unwrap(),
messages_count: 1,
}, &conn);
let time: chrono::DateTime<chrono::offset::FixedOffset> =
chrono::DateTime::parse_from_rfc3339("2021-03-18T04:22:42.501Z").unwrap();
db::messages::add_message(
db::types::Message {
user_id: 9349,
id: 4,
date: time.naive_utc(),
message: "HI?".to_string(),
},
&conn,
)
.unwrap();
db::messages::add_message(
db::types::Message {
user_id: 9349,
id: 5,
date: time.naive_utc(),
message: "I AM NICK!".to_string(),
},
&conn,
)
.unwrap();
db::messages::add_message(
db::types::Message {
user_id: 9349,
id: 6,
date: time.naive_utc(),
message: "I'LL FIND that".to_string(),
},
&conn,
)
.unwrap();
let messages = db::messages::select_message_by_id(9349, 3, &conn).unwrap();
*/
let db = db::start_db();
let (to_server_sender, server_receiver): (Sender<PackedMessage>, Receiver<PackedMessage>) =
mpsc::channel();
@ -115,7 +74,7 @@ fn main() -> io::Result<()> {
t.join().expect("failed client thread").unwrap();
});
server_thread.join().unwrap();
client_thread.join().unwrap();
server_thread.join().expect("failed to unrap server thread");
client_thread.join().expect("failed to unrap client thread");
Ok(())
}