Sending and receiving messages

This commit is contained in:
horhik 2021-04-28 18:26:57 +03:00
parent 2655d8da4b
commit 9a8deb4c98
4 changed files with 112 additions and 43 deletions

View file

@ -101,25 +101,45 @@ pub fn send_message(
let id = Id(uuid::Uuid::parse_str(identifier).expect("failed to parse user ID"));
log::debug!("Reading .hole.toml");
let config: String = String::from_utf8_lossy(&std::fs::read(".hole.toml")?).parse().unwrap();
let config: String = String::from_utf8_lossy(&std::fs::read(".hole.toml")?)
.parse()
.unwrap();
log::debug!("Parsing .hole.toml");
let parsed: crate::chat::Config = toml::from_str(&config[..]).unwrap();
let parsed: crate::chat::Config = toml::from_str(&config[..]).unwrap();
let my_id = parsed.id.0.to_string();
let date = chrono::offset::Local::now();
let db_message = db::types::Message {
id: message_id,
date: chrono::offset::Local::now(),
date: date.clone(),
user_id: id.clone(),
message: message.clone(),
from_me: true,
};
log::debug!("Adding sended message to DB");
match db::messages::add_my_message(db_message, conn) {
Ok(_) => {},
Err(e) => {log::error!("Failed to add message to DB");},
match db::messages::add_my_message(db_message, conn) {
Ok(_) => {}
Err(e) => {
log::error!("Failed to add message to DB");
}
}
let freenet_message = crate::api::response::FreenetMessage {
id: id.clone().0,
message: message.clone(),
date: date.clone(),
};
log::debug!("Sending new message to freent...");
let fcp_req: String =
ClientPut::new_default_direct(fcpv2::types::USK{ ssk: key, path: format!("{}/{}", &my_id, message_id)}, &format!("new-messge-{}/{}", &identifier, &message_id )[..], &message[..]).convert();
let fcp_req: String = ClientPut::new_default_direct(
fcpv2::types::USK {
ssk: key,
path: format!("{}/{}", &my_id, message_id),
},
&format!("new-messge-{}/{}", &identifier, &message_id)[..],
&serde_json::to_string(&freenet_message).unwrap()[..],
)
.convert();
server_sender
.send(PackedMessage::ToFreenet(fcp_req))
.unwrap();
@ -149,20 +169,26 @@ pub fn load_messages(
server_sender: SP,
) -> Result<()> {
log::debug!("Loading {} messages from user {:?}...", &count, &user_id);
let messages: Vec<DbMessage> = db::messages::select_n_last_messages(user_id.clone(), start_index, count, conn).unwrap();
let jsoned = json!(
ResponseType::MessageList{
messages: messages.into_iter().map(|msg| -> FrontMessage {return FrontMessage{
message: msg.message,
date: msg.date,
id: user_id.0,
from_me: msg.from_me,
}}).collect(),
id: user_id.0
}
);
let messages: Vec<DbMessage> =
db::messages::select_n_last_messages(user_id.clone(), start_index, count, conn).unwrap();
let jsoned = json!(ResponseType::MessageList {
messages: messages
.into_iter()
.map(|msg| -> FrontMessage {
return FrontMessage {
message: msg.message,
date: msg.date,
id: user_id.0,
from_me: msg.from_me,
};
})
.collect(),
id: user_id.0
});
log::debug!("Sending loaded messages to client...");
let _ = server_sender.send(PackedMessage::ToClient(jsoned.to_string())).unwrap();
let _ = server_sender
.send(PackedMessage::ToClient(jsoned.to_string()))
.unwrap();
Ok(())
//sending *JSON*
@ -185,13 +211,13 @@ pub fn add_user(
messages_count: 0,
my_messages_count: 0,
};
let user_jsoned = crate::api::response::User{
let user_jsoned = crate::api::response::User {
id: id.clone().to_string(),
name: name.clone(),
sign_key: sign_key.clone(),
insert_key: insert_key,
messages_count: 0,
my_messages_count: 0
my_messages_count: 0,
};
log::debug!("Adding new user to DB...");
db::users::add_user(user, &conn).unwrap();
@ -203,12 +229,12 @@ pub fn add_user(
// TODO senging only one user to client{
/*
server_sender
.send(PackedMessage::ToClient(
json!(ResponseType::UserAdded(user_jsoned))
.to_string(),
))
.unwrap();
*/
server_sender
.send(PackedMessage::ToClient(
json!(ResponseType::UserAdded(user_jsoned))
.to_string(),
))
.unwrap();
*/
Ok(())
}

View file

@ -4,20 +4,25 @@ use serde_derive::{Deserialize, Serialize};
use tungstenite::http::Response;
pub type InsertKey = String;
use crate::db::types::Id;
use crate::db::types::{Id, Time};
use crate::api::types::Message;
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
#[serde(tag = "type")]
pub enum ResponseType {
Error,
NewMessage,
#[serde(rename_all = "camelCase")]
UserAdded(User),
NewMessage {
date: Time,
from_me: bool,
id: uuid::Uuid,
message: String,
},
NewUser,
FetchedMessages,
InstanceCreated,
InstanceAccepted,
#[serde(rename_all = "camelCase")]
UserAdded(User),
#[serde(rename_all = "camelCase")]
InitialConfig {
id: crate::db::types::Id,
@ -62,3 +67,11 @@ pub struct User {
pub my_messages_count: u32,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct FreenetMessage {
pub id: uuid::Uuid,
pub message: String,
pub date: Time,
}

View file

@ -1,3 +1,4 @@
use crate::api::types::Message as FrontMessage;
use super::serv_handler::to_server_sender;
use crate::chat::types::{PackedMessage, RP, SP};
use async_std::task;
@ -90,17 +91,46 @@ async fn server_responce_getter(mut receiver: OwnedReadHalf, client_sender: SP)
}
_ => {}
}
},
"aDataFound" => {
log::debug!("Receive a new message!!! {:?}", &received);
let message = fcpv2::node::fcp_response::AllData::parse(&received[..]).unwrap();
}
"DataFound" => {
log::debug!("Receive a new message!!! {:?}", &received.trim());
let rec = received.clone();
let splitted: Vec<&str> = rec.split_inclusive("AllDatan").collect();
log::debug!("\n\n\n\n\n AAAAAAAAA \n\n\n\n");
let reg = Regex::new("AllData\nIdentifier=(.*)\nCompletionTime=(.*)\nStartupTime=(.*)\nDataLength=(.*)\nGlobal=(.*)\nMetadata.ContentType=(.*)\nData\n((.|\n)*)").unwrap();
let captured = reg.captures(&received[..]).unwrap();
log::debug!("\n\n\n\n\n AAAAAAAAA {:?} \n\n\n\n", captured);
let data_length: usize = usize::from_str_radix(&captured[4], 10).unwrap();
let message = &captured[7][0..data_length].to_string();
let parsed_message =
serde_json::from_str::<crate::api::response::FreenetMessage>(&message[..]);
match parsed_message {
Ok(json) => {
let front_message = FrontMessage{
date: json.date,
from_me: false,
id: json.id,
message: json.message,
};
client_sender.send(PackedMessage::ToClient(serde_json::to_string(&front_message).unwrap())).unwrap();
}
Err(_) => {
log::error!("Failed to parse gotted message");
}
}
log::debug!("Parse new message!!!! {:?}", &message);
},
}
"AllData" => {
log::debug!("Receive a new message!!! {:?}", &received);
let message = fcpv2::node::fcp_response::AllData::parse(&received[..]).unwrap();
let message =
fcpv2::node::fcp_response::AllData::parse(&received[..]).unwrap();
log::debug!("Parse new message!!!! {:?}", &message);
},
let mut lines = &received.clone().lines();
//while (&lines.next() != &Some("AllData")){
// &lines.next();
//}
}
_ => {
log::debug!("unhandled: {}", &req);
client_sender

View file

@ -31,7 +31,7 @@ pub async fn request_repeater(ss: SP, conn: Pool<SqliteConnectionManager>) -> io
let key = USK {
ssk: parsed.private_key.clone(),
path: format!("{}/{}", &id, &index),
path: format!("{}/{}", &id, &index + 2),
};
log::debug!("sending {:?}", &key.convert());
match ss.send(PackedMessage::ToFreenet(
@ -39,7 +39,7 @@ pub async fn request_repeater(ss: SP, conn: Pool<SqliteConnectionManager>) -> io
KEY::USK(
key
),
&format!("new-message-{}/{}", &id, &index)[..], // TODO create Identifier type
&format!("new-message-{}/{}", &id, &index + 2)[..], // TODO create Identifier type
ReturnType::Direct,
)
.convert(),