Skip to content

Commit

Permalink
recoded client - server connections
Browse files Browse the repository at this point in the history
  • Loading branch information
marci1175 committed Jan 14, 2024
1 parent 01f12d0 commit c44d7a0
Show file tree
Hide file tree
Showing 13 changed files with 192 additions and 71 deletions.
2 changes: 1 addition & 1 deletion build_info.matthias_build
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2024.01.13. 22:39
2024.01.14. 14:10
57 changes: 54 additions & 3 deletions src/app.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use egui::{vec2, Align, Color32, Layout, RichText};
use std::fs::{self};
use windows_sys::w;
use windows_sys::Win32::UI::WindowsAndMessaging::{MessageBoxW, MB_ICONERROR};

mod account_manager;
pub mod backend;
Expand All @@ -11,10 +13,10 @@ mod server;
mod ui;

use self::account_manager::{
append_to_file, decrypt_lines_from_vec, delete_line_from_file, read_from_file, generate_uuid,
append_to_file, decrypt_lines_from_vec, delete_line_from_file, generate_uuid, read_from_file,
};

use self::backend::ServerMaster;
use self::backend::{ClientConnection, ServerMaster};
use self::input::keymap;

impl eframe::App for backend::TemplateApp {
Expand All @@ -40,6 +42,8 @@ impl eframe::App for backend::TemplateApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
let input_keys = keymap(self.main.keymap.clone());

//dbg!(generate_uuid());

/* NOTES:
- file_tray_main.rs contains reply_tray
Expand Down Expand Up @@ -101,7 +105,54 @@ impl eframe::App for backend::TemplateApp {

// //format two text inputs, so because im too lazy
// self.send_on_ip = format!("[{}]:{}", self.send_on_address, self.send_on_port);
ui.text_edit_singleline(&mut self.client_ui.send_on_ip);

//Check if there already is a connection
ui.add_enabled_ui(self.client_connection.client.is_none(), |ui| {
ui.text_edit_singleline(&mut self.client_ui.send_on_ip);
});

match self.client_connection.client.is_none() {
true => {
if ui.button("Connect").clicked() {
let ip = self.client_ui.send_on_ip.clone();
match ClientConnection::connect(format!("http://{}", ip)) {
Ok(ok) => {
self.client_connection = ok;
}
Err(err) => {
std::thread::spawn(move || unsafe {
MessageBoxW(
0,
str::encode_utf16(err.to_string().as_str())
.chain(std::iter::once(0))
.collect::<Vec<_>>()
.as_ptr(),
w!("Error"),
MB_ICONERROR,
);
});
}
};
self.autosync_should_run
.store(true, std::sync::atomic::Ordering::Relaxed);

//reset autosync
self.autosync_sender = None;
}
}
false => {
if ui
.button(RichText::from("Disconnect").color(Color32::RED))
.clicked()
{
//Reset client
self.client_connection.client = None;
self.client_ui.incoming_msg = ServerMaster::default();
self.autosync_should_run
.store(false, std::sync::atomic::Ordering::Relaxed);
}
}
}

ui.allocate_ui(vec2(25., 25.), |ui| {
if ui
Expand Down
3 changes: 1 addition & 2 deletions src/app/account_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use aes_gcm::{
use anyhow::{ensure, Context, Result};
use base64::engine::general_purpose;
use base64::Engine;
use chrono::Utc;
use rfd::FileDialog;
use std::env;
use std::fs;
Expand Down Expand Up @@ -263,4 +262,4 @@ pub fn generate_uuid() -> String {
let uuid = uuid::Uuid::new_v4().to_string();

uuid
}
}
98 changes: 76 additions & 22 deletions src/app/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@ use chrono::{DateTime, Utc};
use egui::Color32;
use rand::rngs::ThreadRng;

use crate::app::input::Input;
use rodio::{OutputStream, OutputStreamHandle, Sink};
use tonic::transport::Channel;
use std::collections::BTreeMap;
use std::fmt::Display;
use std::io;
use std::io::{Read, Seek, SeekFrom};
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{mpsc, Arc, Mutex};

use crate::app::input::Input;
use tonic::transport::{Channel, Endpoint};
use windows_sys::w;
use windows_sys::Win32::UI::WindowsAndMessaging::MessageBoxW;
use windows_sys::Win32::UI::WindowsAndMessaging::MB_ICONERROR;

#[derive(serde::Deserialize, serde::Serialize)]
#[serde(default)]
Expand Down Expand Up @@ -222,15 +224,15 @@ pub struct Client {
///Search parameters set by user, to chose what to search for obviously
pub search_parameters: SearchParameters,

///Check if search panel settings panel (xd) is open
///Check if search panel settings panel (xd) is open
#[serde(skip)]
pub search_settings_panel: bool,

///Search buffer
#[serde(skip)]
pub search_buffer: String,

///Check if search panel is open
///Check if search panel is open
#[serde(skip)]
pub search_mode: bool,

Expand Down Expand Up @@ -284,7 +286,7 @@ pub struct Client {
///This is the full address of the destionation a message is supposed to be sent to
pub send_on_ip: String,

///self.send_on_ip encoded into base64, this is supposedly for ease of use, I dont know why its even here
///self.send_on_ip encoded into base64, this is supposedly for ease of use, I dont know why its even here
pub send_on_ip_base64_encoded: String,

///Does client have the password required checkbox ticked
Expand Down Expand Up @@ -487,7 +489,6 @@ pub struct ClientMessage {
pub Password: String,
pub Author: String,
pub MessageDate: String,
pub Destination: String,
}

impl ClientMessage {
Expand All @@ -499,7 +500,6 @@ impl ClientMessage {
///this is used when sending a normal message
pub fn construct_normal_msg(
msg: &str,
ip: String,
password: String,
author: String,
replying_to: Option<usize>,
Expand All @@ -512,14 +512,12 @@ impl ClientMessage {
Password: password,
Author: author,
MessageDate: { Utc::now().format("%Y.%m.%d. %H:%M").to_string() },
Destination: ip,
}
}

///this is used when you want to send a file, this contains name, bytes
pub fn construct_file_msg(
file_path: PathBuf,
ip: String,
password: String,
author: String,
replying_to: Option<usize>,
Expand All @@ -545,7 +543,6 @@ impl ClientMessage {
Password: password,
Author: author,
MessageDate: { Utc::now().format("%Y.%m.%d. %H:%M").to_string() },
Destination: ip,
}
}

Expand All @@ -554,7 +551,6 @@ impl ClientMessage {
index: usize,
author: String,
password: String,
ip: String,
) -> ClientMessage {
ClientMessage {
replying_to: None,
Expand All @@ -565,7 +561,6 @@ impl ClientMessage {
Password: password,
Author: author,
MessageDate: { Utc::now().format("%Y.%m.%d. %H:%M").to_string() },
Destination: ip,
}
}

Expand All @@ -577,7 +572,6 @@ impl ClientMessage {
Password: password,
Author: author,
MessageDate: { Utc::now().format("%Y.%m.%d. %H:%M").to_string() },
Destination: ip,
}
}

Expand All @@ -586,7 +580,6 @@ impl ClientMessage {
index: i32,
password: String,
author: String,
ip: String,
) -> ClientMessage {
ClientMessage {
replying_to: None,
Expand All @@ -596,7 +589,6 @@ impl ClientMessage {
Password: password,
Author: author,
MessageDate: { Utc::now().format("%Y.%m.%d. %H:%M").to_string() },
Destination: ip,
}
}

Expand All @@ -605,7 +597,6 @@ impl ClientMessage {
index: i32,
password: String,
author: String,
ip: String,
) -> ClientMessage {
ClientMessage {
replying_to: None,
Expand All @@ -615,7 +606,6 @@ impl ClientMessage {
Password: password,
Author: author,
MessageDate: { Utc::now().format("%Y.%m.%d. %H:%M").to_string() },
Destination: ip,
}
}

Expand All @@ -624,7 +614,6 @@ impl ClientMessage {
index: i32,
password: String,
author: String,
ip: String,
) -> ClientMessage {
ClientMessage {
replying_to: None,
Expand All @@ -634,7 +623,6 @@ impl ClientMessage {
Password: password,
Author: author,
MessageDate: { Utc::now().format("%Y.%m.%d. %H:%M").to_string() },
Destination: ip,
}
}

Expand All @@ -645,9 +633,72 @@ impl ClientMessage {
///This manages all the settings and variables for maintaining a connection with the server (from client)
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Default)]
pub struct ClientConnection {

#[serde(skip)]
pub channel : Option<Channel>,
pub client: Option<MessageClient<Channel>>,
}

impl ClientConnection {
pub fn connect(ip: String) -> anyhow::Result<Self> {
Ok(Self {
client: {
//Ping server to recive custom uuid, and to also get if server ip is valid
let client = MessageClient::new(Endpoint::from_shared(ip.clone())?.connect_lazy());

let mut client_clone = client.clone();
let (sender, reciver) = mpsc::channel::<Option<MessageClient<Channel>>>();

tokio::spawn(async move {
//ignore is_err_and
let _ = sender
.send(
match client_clone
.message_main(tonic::Request::new(MessageRequest {
message: ClientMessage::construct_sync_msg(
ip.clone(),
"".to_string(),
"Anyád".to_string(),
)
.struct_into_string(),
}))
.await
{
Ok(message_reply) => {
dbg!(message_reply.into_inner().message);
Some(client_clone)
}
Err(error) => {
std::thread::spawn(move || unsafe {
MessageBoxW(
0,
str::encode_utf16(error.to_string().as_str())
.chain(std::iter::once(0))
.collect::<Vec<_>>()
.as_ptr(),
w!("Error"),
MB_ICONERROR,
);
});
None
}
},
)
.is_err_and(|err| {
dbg!(err);
false
});
});

//Is the client valid?
reciver.recv().unwrap()
},
})
}
}

///Used to decide what type fo file i want to send client_actions/actions.rs
pub enum ClientSendType {
File,
Message,
}

/*
Expand Down Expand Up @@ -718,6 +769,9 @@ pub struct ServerAudioReply {
use strum::{EnumDiscriminants, EnumMessage};
use strum_macros::EnumString;

use super::client::messages::message_client::MessageClient;
use super::client::messages::MessageRequest;

///This is what server replies can be
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, EnumDiscriminants)]
#[strum_discriminants(derive(EnumString, EnumMessage))]
Expand Down
25 changes: 15 additions & 10 deletions src/app/client.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
use messages::{message_client::MessageClient, MessageRequest};
use tonic::transport::{Endpoint, Channel};
use messages::MessageRequest;

use super::backend::{ClientMessage, TemplateApp};
pub mod messages {
tonic::include_proto!("messages");
}

use crate::app::backend::ClientConnection;

//main is for sending
#[inline]
pub async fn send_msg(message: ClientMessage) -> Result<String, Box<dyn std::error::Error>> {

let mut client = MessageClient::new(todo!());

pub async fn send_msg(
connection: ClientConnection,
message: ClientMessage,
) -> anyhow::Result<String> {
if let Some(mut client) = connection.client.clone() {
let request = tonic::Request::new(MessageRequest {
message: message.struct_into_string(),
});

let response = client.message_main(request).await?.into_inner().clone();

let message = response.message;

Ok(message)
}
} else {
Err(anyhow::Error::msg("Request failed, see logs"))
}
}
Loading

0 comments on commit c44d7a0

Please sign in to comment.