add functions for adding users/messages and getting it from DB

This commit is contained in:
Horhik 2021-03-18 07:44:53 +03:00
parent 311e273b1a
commit 25f73f6a36
8 changed files with 126 additions and 17 deletions

1
Cargo.lock generated
View file

@ -1209,6 +1209,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5f38ee71cbab2c827ec0ac24e76f82eca723cee92c509a65f67dee393c25112" checksum = "d5f38ee71cbab2c827ec0ac24e76f82eca723cee92c509a65f67dee393c25112"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"chrono",
"fallible-iterator", "fallible-iterator",
"fallible-streaming-iterator", "fallible-streaming-iterator",
"hashlink", "hashlink",

View file

@ -8,7 +8,7 @@ edition = "2018"
[dependencies] [dependencies]
ntru = "0.5.6" ntru = "0.5.6"
rusqlite = "0.24.2" rusqlite = {version = "0.24.2", features = ["chrono"]}
toml = "0.5.6" toml = "0.5.6"
tungstenite = "0.12.0" tungstenite = "0.12.0"
tokio = { version = "0.3.3", features = ["full"] } tokio = { version = "0.3.3", features = ["full"] }

27
public/Group 1.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 62 KiB

View file

@ -1,4 +1,5 @@
use super::types::Message; use super::types::Message;
use rusqlite::{params, Connection, Result}; use rusqlite::{params, Connection, Result};
pub fn select_message_by_id(id: u64, conn: &Connection) -> Result<Message> { pub fn select_message_by_id(id: u64, conn: &Connection) -> Result<Message> {
@ -9,10 +10,40 @@ pub fn select_all_user_message(id: u64, conn: &Connection) -> Result<Vec<Message
unimplemented!(); unimplemented!();
} }
pub fn select_n_last_messages(user_id: u64, count: u32, conn: &Connection) -> Result<Vec<Message>> { pub fn select_n_last_messages(user_id: u32, start: u32, count: u32, conn: &Connection) -> Result<Vec<Message>> {
unimplemented!(); let mut selected = conn.prepare("SELECT * FROM messages WHERE user_id = ?1 AND id > ?2 LIMIT ?3")?;
let message_iter = selected.query_map(params![user_id, start, count], |row| {
Ok(Message {
id: row.get(0)?,
date: row.get(1)?,
user_id: row.get(2)?,
message: row.get(3)?,
})
})?;
let mut users: Vec<Message> = Vec::new();
for message in message_iter {
log::info!("User: {:?}", (&message));
users.push(message?);
}
log::info!("All users loaded to memory");
Ok(users)
} }
pub fn add_message(message: Message, conn: &Connection) -> Result<()>{ pub fn add_message(message: Message, conn: &Connection) -> Result<()> {
unimplemented!(); match conn.execute(
"INSERT INTO messages (
id,
user_id,
date,
message
) VALUES (?1, ?2, ?3, ?4)",
params![message.id,message.user_id, message.date, message.message],
) {
Ok(_) => log::info!("message {:} added succsessfully!", message.id),
Err(e) => {
log::error!("failed to insert message {:?}", e);
return Err(e);
}
}
Ok(())
} }

View file

@ -23,6 +23,7 @@ fn create_db(conn: &Connection) -> Result<()> {
"CREATE TABLE messages ( "CREATE TABLE messages (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
user_id TEXT NOT NULL, user_id TEXT NOT NULL,
date datetime NOT NULL,
message TEXT NOT NULL message TEXT NOT NULL
)", )",
params![], params![],

View file

@ -4,8 +4,8 @@ use fcpv2::types::{traits::FcpRequest, SSK};
pub const DB_PATH: &str = "hole.db"; pub const DB_PATH: &str = "hole.db";
pub type SignKey = SSK; pub type SignKey = String;
pub type InsertKey = String; pub type InsertKey = SSK;
#[derive(Debug)] #[derive(Debug)]
pub struct User { pub struct User {
@ -19,7 +19,7 @@ pub struct User {
#[derive(Debug)] #[derive(Debug)]
pub struct Message { pub struct Message {
pub id: u32, pub id: u32,
pub date: DateTime<Local>, pub date: NaiveDateTime,
pub user_id: u32, pub user_id: u32,
pub message: String, pub message: String,
} }

View file

@ -4,16 +4,23 @@ use fcpv2::types::{SSK, traits::FcpParser};
use rusqlite::{params, Connection, Result, NO_PARAMS}; use rusqlite::{params, Connection, Result, NO_PARAMS};
pub fn get_user_by_id(id: u32, conn: &Connection) -> Result<User> { pub fn get_user_by_id(id: u32, conn: &Connection) -> Result<User> {
unimplemented!(); let mut selected = conn.prepare("SELECT * FROM users WHERE id = ?")?;
} let mut user_iter = selected.query_map(params![id], |row| {
Ok(User {
pub fn get_user_by_name(String: u32, conn: &Connection) -> Result<User> { id: row.get(0)?,
unimplemented!(); name: row.get(1)?,
sign_key: row.get(2)?,
insert_key: row.get(3)?,
messages_count: row.get(4)?,
})
})?;
let user = user_iter.next().unwrap();
log::info!("User {:} founded", id);
user
} }
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")?;
log::info!("add user to USERS successfully!");
let user_iter = selected.query_map(params![], |row| { let user_iter = selected.query_map(params![], |row| {
Ok(User { Ok(User {
id: row.get(0)?, id: row.get(0)?,
@ -28,6 +35,7 @@ pub fn load_all_users(conn: &Connection) -> Result<Vec<User>> {
log::info!("User: {:?}", (&user)); log::info!("User: {:?}", (&user));
users.push(user?); users.push(user?);
} }
log::info!("All users loaded to memory");
Ok(users) Ok(users)
} }

View file

@ -1,12 +1,15 @@
mod chat; mod chat;
mod db; mod db;
mod encrypting; mod encrypting;
mod fcpv2;
use async_std::io; use async_std::io;
use chat::front_conn::listen_client; use chat::front_conn::listen_client;
use chat::serv_conn::listen_server; use chat::serv_conn::listen_server;
use chat::types::PackedMessage; use chat::types::PackedMessage;
use chrono::Utc;
use db::users;
use fcpv2::types::{traits::FcpParser, SSK};
use log; use log;
use simple_logger::SimpleLogger;
use std::{ use std::{
sync::{ sync::{
mpsc, mpsc,
@ -14,7 +17,6 @@ use std::{
}, },
thread, thread,
}; };
use simple_logger::SimpleLogger;
/* /*
+-----------------------------------------------------------------------------------+ +-----------------------------------------------------------------------------------+
| Client | | Client |
@ -45,7 +47,46 @@ use simple_logger::SimpleLogger;
fn main() -> io::Result<()> { fn main() -> io::Result<()> {
SimpleLogger::new().init().unwrap(); SimpleLogger::new().init().unwrap();
db::start_db().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: 1,
date: time.naive_utc(),
message: "hey duude".to_string(),
},
&conn,
)
.unwrap();
db::messages::add_message(
db::types::Message {
user_id: 9349,
id: 2,
date: time.naive_utc(),
message: "what do you think".to_string(),
},
&conn,
)
.unwrap();
db::messages::add_message(
db::types::Message {
user_id: 9349,
id: 3,
date: time.naive_utc(),
message: "about that".to_string(),
},
&conn,
)
.unwrap();
let (to_server_sender, server_receiver): (Sender<PackedMessage>, Receiver<PackedMessage>) = let (to_server_sender, server_receiver): (Sender<PackedMessage>, Receiver<PackedMessage>) =
mpsc::channel(); mpsc::channel();