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 // 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.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 { 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).expect("failed to parse user ID")), user_id: id.clone(),
message: message.clone(), message: message.clone(),
from_me: true, from_me: true,
}; };
let _ = db::messages::add_my_message(db_message, conn).unwrap(); let _ = db::messages::add_my_message(db_message, conn).unwrap();
log::debug!("sending new message to freent");
let fcp_req: String = 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 server_sender
.send(PackedMessage::ToFreenet(fcp_req)) .send(PackedMessage::ToFreenet(fcp_req))
.unwrap(); .unwrap();
log::debug!("Increasing messages count");
let _ = db::users::increase_my_messages_count(id.clone(), &conn);
Ok(()) Ok(())
} else { } else {
// create error types // create error types
@ -135,7 +140,7 @@ pub fn load_messages(
) -> Result<()> { ) -> Result<()> {
let messages = db::messages::select_n_last_messages(user_id, start_index, count, conn).unwrap(); let messages = db::messages::select_n_last_messages(user_id, start_index, count, conn).unwrap();
let jsoned = json!(messages); let jsoned = json!(messages);
let _ = server_sender.send(PackedMessage::ToClient(jsoned.to_string())); let _ = server_sender.send(PackedMessage::ToClient(jsoned.to_string())).unwrap();
Ok(()) Ok(())
//sending *JSON* //sending *JSON*
@ -155,18 +160,20 @@ pub fn add_user(
sign_key: sign_key.clone(), sign_key: sign_key.clone(),
insert_key: SSK::parse(&insert_key[..]).unwrap(), insert_key: SSK::parse(&insert_key[..]).unwrap(),
messages_count: 0, messages_count: 0,
my_messages_count: 0,
}; };
let user_jsoned = crate::api::response::User{ let user_jsoned = crate::api::response::User{
id: new_id.clone().to_string(), id: new_id.clone().to_string(),
name: name.clone(), name: name.clone(),
sign_key: sign_key.clone(), sign_key: sign_key.clone(),
insert_key: insert_key, insert_key: insert_key,
messages_count: 0 messages_count: 0,
my_messages_count: 0
}; };
db::users::add_user(user, &conn).unwrap(); db::users::add_user(user, &conn).unwrap();
// Sending "Ok" response to client // Sending "Ok" response to client
// //
//loading all users to frontend
load_users(conn, server_sender).unwrap(); load_users(conn, server_sender).unwrap();
// TODO senging only one user to client{ // TODO senging only one user to client{

View file

@ -51,5 +51,6 @@ pub struct User {
pub sign_key: SignKey, pub sign_key: SignKey,
pub insert_key: InsertKey, pub insert_key: InsertKey,
pub messages_count: u32, 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::{ use super::{
handlers, handlers,
request::Request, request::Request,
response::{AppError, ErrorType, ResponseType}, response::{AppError, ErrorType, ResponseType},
}; };
use crate::chat::types::{PackedMessage, SP};
use async_std::io::Result; use async_std::io::Result;
use rusqlite;
use rusqlite::Connection; use rusqlite::Connection;
use serde_json::from_str; use serde_json::from_str;
use serde_json::json; use serde_json::json;
@ -19,8 +20,7 @@ pub fn request_selector(json: &str, server_sender: SP, conn: &Connection) -> Res
Request::StartApp => { Request::StartApp => {
match handlers::start_app(server_sender.clone()) { match handlers::start_app(server_sender.clone()) {
Ok(_) => return Ok(()), Ok(_) => return Ok(()),
Err(_) => {} Err(_) => {} // 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() // .clone()
// .send(PackedMessage::ToClient( // .send(PackedMessage::ToClient(
@ -32,29 +32,48 @@ pub fn request_selector(json: &str, server_sender: SP, conn: &Connection) -> Res
// .unwrap(); // .unwrap();
// return Ok(()); // 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 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) 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>> { pub fn select_all_user_message(id: u32, conn: &Connection) -> Result<Vec<Message>> {
let mut selected = 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 message_iter = selected.query_map(params![id], |row| ret_mes(row))?;
let mut messages: Vec<Message> = Vec::new(); let mut messages: Vec<Message> = Vec::new();
for message in message_iter { for message in message_iter {
@ -41,15 +41,16 @@ pub fn select_n_last_messages(
conn: &Connection, conn: &Connection,
) -> Result<Vec<Message>> { ) -> Result<Vec<Message>> {
let mut selected = conn.prepare( 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(); let mut messages: Vec<Message> = Vec::new();
for message in message_iter { for message in message_iter {
log::info!("Message: {:?}", (&message)); log::info!("Message: {:?}", (&message));
messages.push(message?); messages.push(message?);
} }
log::info!("All messages loaded to memory"); log::info!("All messages loaded to memory");
log::debug!("{:?}", messages);
Ok(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<()> { pub fn add_my_message(message: Message, conn: &Connection) -> Result<()> {
match conn.execute( match conn.execute(
"INSERT INTO messages ( "INSERT INTO my_messages (
id, id,
user_id, user_id,
date, date,
message, message,
from_me from_me
) VALUES (?1, ?2, ?3, ?4)", ) VALUES (?1, ?2, ?3, ?4, ?5)",
params![message.id, message.user_id, message.date, message.message], params![message.id, message.user_id, message.date, message.message, true],
) { ) {
Ok(_) => log::info!("message {:} added succsessfully!", message.id), Ok(_) => log::info!("message {:} added succsessfully!", message.id),
Err(e) => { Err(e) => {

View file

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

View file

@ -26,6 +26,7 @@ pub struct User {
pub sign_key: SignKey, pub sign_key: SignKey,
pub insert_key: InsertKey, pub insert_key: InsertKey,
pub messages_count: u32, pub messages_count: u32,
pub my_messages_count: u32,
} }
/// converting SSK to rusqlite type /// converting SSK to rusqlite type
@ -51,6 +52,7 @@ impl User {
sign_key: self.sign_key, sign_key: self.sign_key,
insert_key: SSK::convert(&self.insert_key), insert_key: SSK::convert(&self.insert_key),
messages_count: self.messages_count, messages_count: self.messages_count,
my_messages_count: self.my_messages_count,
} }
} }
pub fn from_jsonable(json: JsonableUser) -> io::Result<User> { pub fn from_jsonable(json: JsonableUser) -> io::Result<User> {
@ -60,6 +62,7 @@ impl User {
sign_key: json.sign_key, sign_key: json.sign_key,
insert_key: SSK::parse(&json.insert_key[..]).unwrap(), insert_key: SSK::parse(&json.insert_key[..]).unwrap(),
messages_count: json.messages_count, 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)?, sign_key: row.get(2)?,
insert_key: row.get(3)?, insert_key: row.get(3)?,
messages_count: row.get(4)?, messages_count: row.get(4)?,
my_messages_count: row.get(5)?,
}) })
})?; })?;
let user = user_iter.next().unwrap(); 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 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>> { pub fn load_all_users(conn: &Connection) -> Result<Vec<User>> {
let mut selected = conn.prepare("SELECT * FROM users")?; let mut selected = conn.prepare("SELECT * FROM users")?;
let user_iter = selected.query_map(params![], |row| { 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)?, sign_key: row.get(2)?,
insert_key: row.get(3)?, insert_key: row.get(3)?,
messages_count: row.get(4)?, messages_count: row.get(4)?,
my_messages_count: row.get(5)?,
}) })
})?; })?;
let mut users: Vec<User> = Vec::new(); let mut users: Vec<User> = Vec::new();
@ -47,14 +63,17 @@ pub fn add_user(user: User, conn: &Connection) -> Result<()> {
name, name,
sign_key, sign_key,
insert_key, insert_key,
messages_count messages_count,
) VALUES (?1, ?2, ?3, ?4, ?5)", my_messages_count
) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![ params![
user.id, user.id,
user.name, user.name,
user.sign_key, user.sign_key,
user.insert_key, user.insert_key,
user.messages_count user.messages_count,
user.my_messages_count
], ],
) { ) {
Ok(_) => log::info!("add user to USERS successfully!"), Ok(_) => log::info!("add user to USERS successfully!"),