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")); let id = Id(uuid::Uuid::parse_str(identifier).expect("failed to parse user ID"));
log::debug!("Reading .hole.toml"); 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"); 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 my_id = parsed.id.0.to_string();
let date = chrono::offset::Local::now();
let db_message = db::types::Message { let db_message = db::types::Message {
id: message_id, id: message_id,
date: chrono::offset::Local::now(), date: date.clone(),
user_id: id.clone(), user_id: id.clone(),
message: message.clone(), message: message.clone(),
from_me: true, from_me: true,
}; };
log::debug!("Adding sended message to DB"); log::debug!("Adding sended message to DB");
match db::messages::add_my_message(db_message, conn) { match db::messages::add_my_message(db_message, conn) {
Ok(_) => {}, Ok(_) => {}
Err(e) => {log::error!("Failed to add message to DB");}, 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..."); log::debug!("Sending new message to freent...");
let fcp_req: String = let fcp_req: String = ClientPut::new_default_direct(
ClientPut::new_default_direct(fcpv2::types::USK{ ssk: key, path: format!("{}/{}", &my_id, message_id)}, &format!("new-messge-{}/{}", &identifier, &message_id )[..], &message[..]).convert(); 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 server_sender
.send(PackedMessage::ToFreenet(fcp_req)) .send(PackedMessage::ToFreenet(fcp_req))
.unwrap(); .unwrap();
@ -149,20 +169,26 @@ pub fn load_messages(
server_sender: SP, server_sender: SP,
) -> Result<()> { ) -> Result<()> {
log::debug!("Loading {} messages from user {:?}...", &count, &user_id); 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 messages: Vec<DbMessage> =
let jsoned = json!( db::messages::select_n_last_messages(user_id.clone(), start_index, count, conn).unwrap();
ResponseType::MessageList{ let jsoned = json!(ResponseType::MessageList {
messages: messages.into_iter().map(|msg| -> FrontMessage {return FrontMessage{ messages: messages
.into_iter()
.map(|msg| -> FrontMessage {
return FrontMessage {
message: msg.message, message: msg.message,
date: msg.date, date: msg.date,
id: user_id.0, id: user_id.0,
from_me: msg.from_me, from_me: msg.from_me,
}}).collect(), };
})
.collect(),
id: user_id.0 id: user_id.0
} });
);
log::debug!("Sending loaded messages to client..."); 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(()) Ok(())
//sending *JSON* //sending *JSON*
@ -191,7 +217,7 @@ pub fn add_user(
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 my_messages_count: 0,
}; };
log::debug!("Adding new user to DB..."); log::debug!("Adding new user to DB...");
db::users::add_user(user, &conn).unwrap(); db::users::add_user(user, &conn).unwrap();

View file

@ -4,20 +4,25 @@ use serde_derive::{Deserialize, Serialize};
use tungstenite::http::Response; use tungstenite::http::Response;
pub type InsertKey = String; pub type InsertKey = String;
use crate::db::types::Id; use crate::db::types::{Id, Time};
use crate::api::types::Message; use crate::api::types::Message;
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
#[serde(tag = "type")] #[serde(tag = "type")]
pub enum ResponseType { pub enum ResponseType {
Error, Error,
NewMessage, #[serde(rename_all = "camelCase")]
UserAdded(User),
NewMessage {
date: Time,
from_me: bool,
id: uuid::Uuid,
message: String,
},
NewUser, NewUser,
FetchedMessages, FetchedMessages,
InstanceCreated, InstanceCreated,
InstanceAccepted, InstanceAccepted,
#[serde(rename_all = "camelCase")]
UserAdded(User),
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
InitialConfig { InitialConfig {
id: crate::db::types::Id, id: crate::db::types::Id,
@ -62,3 +67,11 @@ pub struct User {
pub my_messages_count: u32, 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 super::serv_handler::to_server_sender;
use crate::chat::types::{PackedMessage, RP, SP}; use crate::chat::types::{PackedMessage, RP, SP};
use async_std::task; use async_std::task;
@ -90,17 +91,46 @@ async fn server_responce_getter(mut receiver: OwnedReadHalf, client_sender: SP)
} }
_ => {} _ => {}
} }
}, }
"aDataFound" => { "DataFound" => {
log::debug!("Receive a new message!!! {:?}", &received); log::debug!("Receive a new message!!! {:?}", &received.trim());
let message = fcpv2::node::fcp_response::AllData::parse(&received[..]).unwrap(); 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); log::debug!("Parse new message!!!! {:?}", &message);
}, }
"AllData" => { "AllData" => {
log::debug!("Receive a new message!!! {:?}", &received); 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); log::debug!("Parse new message!!!! {:?}", &message);
}, let mut lines = &received.clone().lines();
//while (&lines.next() != &Some("AllData")){
// &lines.next();
//}
}
_ => { _ => {
log::debug!("unhandled: {}", &req); log::debug!("unhandled: {}", &req);
client_sender client_sender

View file

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