some updates

This commit is contained in:
Horhik 2021-04-22 18:28:07 +03:00
parent 8fee7ce9cc
commit 90d10a8102
7 changed files with 101 additions and 55 deletions

View file

@ -96,20 +96,25 @@ pub fn send_message(
// Add message to DB
let key = user_data.insert_key;
let identifier = &user_data.id.0.to_string()[..];
let message_id: u32 = user_data.messages_count;
let message_id: u32 = user_data.my_messages_count;
let id = Id(uuid::Uuid::parse_str(identifier).expect("failed to parse user ID"));
let _ = db::users::increase_my_messages_count(id.clone(), conn);
let db_message = db::types::Message {
id: message_id,
date: chrono::offset::Local::now(),
user_id: Id(uuid::Uuid::parse_str(identifier).expect("failed to parse user ID")),
user_id: id.clone(),
message: message.clone(),
from_me: true,
};
let _ = db::messages::add_my_message(db_message, conn).unwrap();
log::debug!("sending new message to freent");
let fcp_req: String =
ClientPut::new_default_direct(key, identifier, &message[..]).convert();
ClientPut::new_default_direct(fcpv2::types::USK{ ssk: key, path: format!("{}/{}", &identifier, message_id)}, &format!("{}/{}", &identifier, &message_id )[..], &message[..]).convert();
server_sender
.send(PackedMessage::ToFreenet(fcp_req))
.unwrap();
log::debug!("Increasing messages count");
let _ = db::users::increase_my_messages_count(id.clone(), &conn);
Ok(())
} else {
// create error types
@ -135,7 +140,7 @@ pub fn load_messages(
) -> 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()));
let _ = server_sender.send(PackedMessage::ToClient(jsoned.to_string())).unwrap();
Ok(())
//sending *JSON*
@ -155,18 +160,20 @@ pub fn add_user(
sign_key: sign_key.clone(),
insert_key: SSK::parse(&insert_key[..]).unwrap(),
messages_count: 0,
my_messages_count: 0,
};
let user_jsoned = crate::api::response::User{
id: new_id.clone().to_string(),
name: name.clone(),
sign_key: sign_key.clone(),
insert_key: insert_key,
messages_count: 0
messages_count: 0,
my_messages_count: 0
};
db::users::add_user(user, &conn).unwrap();
// Sending "Ok" response to client
//
//loading all users to frontend
load_users(conn, server_sender).unwrap();
// TODO senging only one user to client{

View file

@ -51,5 +51,6 @@ pub struct User {
pub sign_key: SignKey,
pub insert_key: InsertKey,
pub messages_count: u32,
pub my_messages_count: u32,
}

View file

@ -1,10 +1,11 @@
use crate::chat::types::{PackedMessage, SP}; use rusqlite;
use super::{
handlers,
request::Request,
response::{AppError, ErrorType, ResponseType},
};
use crate::chat::types::{PackedMessage, SP};
use async_std::io::Result;
use rusqlite;
use rusqlite::Connection;
use serde_json::from_str;
use serde_json::json;
@ -15,15 +16,14 @@ pub fn request_selector(json: &str, server_sender: SP, conn: &Connection) -> Res
// }
log::info!("matching request...");
let parsed: Request = serde_json::from_str(json).unwrap();
match parsed{
match parsed {
Request::StartApp => {
match handlers::start_app(server_sender.clone()) {
Ok(_) => return Ok(()),
Err(_) => {}
// Sending error to user, because failed to add user
// let _ = server_sender
// .clone()
// .send(PackedMessage::ToClient(
Err(_) => {} // Sending error to user, because failed to add user
// let _ = server_sender
// .clone()
// .send(PackedMessage::ToClient(
// json!(AppError {
// res_type: ErrorType::FailedToAddUser
// })
@ -32,29 +32,48 @@ pub fn request_selector(json: &str, server_sender: SP, conn: &Connection) -> Res
// .unwrap();
// return Ok(());
}
},
Request::StopApp => {
match handlers::stop_app(&conn, server_sender.clone()) { Ok(_) => {}, Err(_) => {} }
},
Request::LoadUsers => {
match handlers::load_users(&conn, server_sender.clone()){ Ok(_) => {}, Err(_) => {} }
},
Request::SendMessage {
user_id, message
} => {
match handlers::send_message(user_id, message, &conn, server_sender.clone()){ Ok(_) => {}, Err(_) => {} }
},
Request::LoadMessages{
user_id, count, start_index
} => {
match handlers::load_messages(user_id, start_index, count, &conn, server_sender.clone()){ Ok(_) => {}, Err(_) => {} }
},
Request::AddUser{
name, sign_key, insert_key
} => {
match handlers::add_user(name, insert_key, sign_key, &conn, server_sender.clone()){ Ok(_) => {}, Err(_) => {} }
},
}
Request::StopApp => match handlers::stop_app(&conn, server_sender.clone()) {
Ok(_) => {}
Err(_) => {}
},
Request::LoadUsers => match handlers::load_users(&conn, server_sender.clone()) {
Ok(_) => {}
Err(_) => {}
},
Request::SendMessage { user_id, message } => {
match handlers::send_message(user_id, message, &conn, server_sender.clone()) {
Ok(_) => {}
Err(_) => {}
}
}
Request::LoadMessages {
user_id,
count,
start_index,
} => {
match handlers::load_messages(user_id, start_index, count, &conn, server_sender.clone())
{
Ok(_) => {}
Err(_) => {}
}
}
Request::AddUser {
name,
sign_key,
insert_key,
} => match handlers::add_user(name, insert_key, sign_key, &conn, server_sender.clone()) {
Ok(_) => {}
Err(_) => {}
},
req => {
log::error!("{}", async_std::io::Error::new(
async_std::io::ErrorKind::InvalidData,
serde_json::to_string(&req).unwrap(),
))
}
}
Ok(())
/*
if let Ok(res) = from_str::<StartAppReq>(&json) {kk
@ -88,9 +107,4 @@ pub fn request_selector(json: &str, server_sender: SP, conn: &Connection) -> Res
log::error!("{}\n is wrong formatted", json)
}
*/
Err(async_std::io::Error::new(
async_std::io::ErrorKind::InvalidData,
serde_json::to_string(&Request::StartApp).unwrap(),
))
}

View file

@ -23,7 +23,7 @@ pub fn select_message_by_id(user_id: u32, id:u32, conn: &Connection) -> Result<M
pub fn select_all_user_message(id: u32, conn: &Connection) -> Result<Vec<Message>> {
let mut selected =
conn.prepare("SELECT * FROM messages, my_messages WHERE user_id = ?1 ORDER BY date DESC")?;
conn.prepare("SELECT * FROM messages, my_messages WHERE user_id = ? ORDER BY date DESC")?;
let message_iter = selected.query_map(params![id], |row| ret_mes(row))?;
let mut messages: Vec<Message> = Vec::new();
for message in message_iter {
@ -41,15 +41,16 @@ pub fn select_n_last_messages(
conn: &Connection,
) -> Result<Vec<Message>> {
let mut selected = conn.prepare(
"SELECT * FROM messages WHERE user_id = ?1 AND id >= ?2 LIMIT ?3 ORDER BY date DESC",
"SELECT * FROM messages CROSS JOIN my_messages WHERE messages.user_id = ?1 or my_messages.user_id = ?1 ORDER BY date DESC LIMIT ?2",
)?;
let message_iter = selected.query_map(params![user_id, start, count], |row| ret_mes(row))?;
let message_iter = selected.query_map(params![user_id, count], |row| ret_mes(row))?;
let mut messages: Vec<Message> = Vec::new();
for message in message_iter {
log::info!("Message: {:?}", (&message));
messages.push(message?);
}
log::info!("All messages loaded to memory");
log::debug!("{:?}", messages);
Ok(messages)
}
@ -75,14 +76,14 @@ pub fn add_message(message: Message, conn: &Connection) -> Result<()> {
pub fn add_my_message(message: Message, conn: &Connection) -> Result<()> {
match conn.execute(
"INSERT INTO messages (
"INSERT INTO my_messages (
id,
user_id,
date,
message,
from_me
) VALUES (?1, ?2, ?3, ?4)",
params![message.id, message.user_id, message.date, message.message],
) VALUES (?1, ?2, ?3, ?4, ?5)",
params![message.id, message.user_id, message.date, message.message, true],
) {
Ok(_) => log::info!("message {:} added succsessfully!", message.id),
Err(e) => {

View file

@ -12,7 +12,8 @@ fn create_db(conn: &Connection) -> Result<()> {
name TEXT UNIQUE NOT NULL,
sign_key BLOB UNIQUE NOT NULL,
insert_key BLOB UNIQUE NOT NULL,
messages_count INTEGER
messages_count INTEGER,
my_messages_count INTEGER
)",
params![],
) {
@ -35,7 +36,7 @@ fn create_db(conn: &Connection) -> Result<()> {
match conn.execute(
"CREATE TABLE my_messages (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL,
user_id BLOB NOT NULL,
date datetime NOT NULL,
message TEXT NOT NULL,
from_me BOOL

View file

@ -26,6 +26,7 @@ pub struct User {
pub sign_key: SignKey,
pub insert_key: InsertKey,
pub messages_count: u32,
pub my_messages_count: u32,
}
/// converting SSK to rusqlite type
@ -51,6 +52,7 @@ impl User {
sign_key: self.sign_key,
insert_key: SSK::convert(&self.insert_key),
messages_count: self.messages_count,
my_messages_count: self.my_messages_count,
}
}
pub fn from_jsonable(json: JsonableUser) -> io::Result<User> {
@ -60,6 +62,7 @@ impl User {
sign_key: json.sign_key,
insert_key: SSK::parse(&json.insert_key[..]).unwrap(),
messages_count: json.messages_count,
my_messages_count: json.my_messages_count,
})
}
}

View file

@ -12,6 +12,7 @@ pub fn get_user_by_id(id: crate::db::types::Id, conn: &Connection) -> Result<Use
sign_key: row.get(2)?,
insert_key: row.get(3)?,
messages_count: row.get(4)?,
my_messages_count: row.get(5)?,
})
})?;
let user = user_iter.next().unwrap();
@ -19,6 +20,20 @@ pub fn get_user_by_id(id: crate::db::types::Id, conn: &Connection) -> Result<Use
user
}
pub fn increase_messages_count(id: crate::db::types::Id, conn: &Connection) -> Result<()> {
conn.execute("UPDATE users
SET messages_count = messages_count + 1
WHERE id = ?", params![id]).unwrap();
Ok(())
}
pub fn increase_my_messages_count(id: crate::db::types::Id, conn: &Connection) -> Result<()> {
conn.execute("UPDATE users
SET my_messages_count = my_messages_count + 1
WHERE id = ?", params![id]).unwrap();
Ok(())
}
pub fn load_all_users(conn: &Connection) -> Result<Vec<User>> {
let mut selected = conn.prepare("SELECT * FROM users")?;
let user_iter = selected.query_map(params![], |row| {
@ -28,6 +43,7 @@ pub fn load_all_users(conn: &Connection) -> Result<Vec<User>> {
sign_key: row.get(2)?,
insert_key: row.get(3)?,
messages_count: row.get(4)?,
my_messages_count: row.get(5)?,
})
})?;
let mut users: Vec<User> = Vec::new();
@ -47,14 +63,17 @@ pub fn add_user(user: User, conn: &Connection) -> Result<()> {
name,
sign_key,
insert_key,
messages_count
) VALUES (?1, ?2, ?3, ?4, ?5)",
messages_count,
my_messages_count
) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![
user.id,
user.name,
user.sign_key,
user.insert_key,
user.messages_count
user.messages_count,
user.my_messages_count
],
) {
Ok(_) => log::info!("add user to USERS successfully!"),