Skip to content

Commit

Permalink
optimising uploads
Browse files Browse the repository at this point in the history
  • Loading branch information
marci1175 committed Dec 12, 2023
1 parent 9acc228 commit 300a6b6
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 24 deletions.
26 changes: 15 additions & 11 deletions src/app/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use chrono::Utc;
use rand::rngs::ThreadRng;

use std::collections::BTreeMap;
use std::fs::{File, self};
use std::fs::{self, File};

use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
Expand Down Expand Up @@ -345,10 +345,9 @@ impl Message {
) -> Message {
Message {
replying_to: replying_to,
//Dont execute me please :3 |
// |
// V
MessageType: MessageType::Image(Image { bytes: fs::read(file_name).unwrap_or_default() }),
MessageType: MessageType::Image(Image {
bytes: fs::read(file_name).unwrap_or_default(),
}),

Password: password,
Author: author,
Expand All @@ -370,15 +369,20 @@ pub struct ServerNormalMessage {
}

#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct ServerImage {
pub struct ServerImageReply {
pub bytes: Vec<u8>,
}

#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct ServerImageRequest {
pub index: i32,
}

#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub enum ServerMessageType {
Upload(ServerFileUpload),
Normal(ServerNormalMessage),
Image(ServerImage),
Image(ServerImageRequest),
}

#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
Expand Down Expand Up @@ -409,16 +413,16 @@ impl ServerOutput {
MessageDate: normal_msg.MessageDate,
}
}
pub fn convert_picture_to_servermsg(normal_msg: Message) -> ServerOutput {
pub fn convert_picture_to_servermsg(normal_msg: Message, index: i32) -> ServerOutput {
//Convert a client output to a server output (Message -> ServerOutput), trim some useless info
ServerOutput {
replying_to: normal_msg.replying_to,
MessageType: ServerMessageType::Image(ServerImage {
bytes: match normal_msg.MessageType {
MessageType: ServerMessageType::Image(ServerImageRequest {
index: match normal_msg.MessageType {
MessageType::SyncMessage(_) => todo!(),
MessageType::FileRequest(_) => todo!(),
MessageType::FileUpload(_) => todo!(),
MessageType::Image(img) => img.bytes,
MessageType::Image(_) => index,
MessageType::NormalMessage(_) => todo!(),
},
}),
Expand Down
65 changes: 57 additions & 8 deletions src/app/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ pub struct MessageService {

//files
pub file_paths: Mutex<Vec<PathBuf>>,

//images
pub image_paths: Mutex<Vec<PathBuf>>,
}
#[tonic::async_trait]
impl ServerMessage for MessageService {
Expand All @@ -55,7 +58,8 @@ impl ServerMessage for MessageService {
if &req.Password == self.passw.trim() {
match &req.MessageType {
NormalMessage(_msg) => self.NormalMessage(req).await,
SyncMessage(_msg) => { /*Dont do anything we will always reply with the list of msgs*/}
SyncMessage(_msg) => { /*Dont do anything we will always reply with the list of msgs*/
}
Image(_) => {
self.ImageMessage(req).await;
}
Expand Down Expand Up @@ -278,14 +282,59 @@ impl MessageService {
Ok(Response::new(reply))
}
pub async fn ImageMessage(&self, req: Message) {
match self.messages.lock() {
Ok(mut ok) => {
ok.push(ServerOutput::convert_picture_to_servermsg(req));
}
Err(err) => {
println!("{err}")
if let Image(img) = &req.MessageType {
match env::var("APPDATA") {
Ok(app_data) => {

let _create_dir = fs::create_dir(format!("{}\\szeChat\\Server", app_data));

match fs::File::create(format!(
"{app_data}\\szeChat\\Server\\{}",
self.image_paths.lock().unwrap().len()
)) {
Ok(mut created_file) => {
if let Err(err) = created_file.write_all(&img.bytes) {
println!("[{err}\n{}]", err.kind());
};

created_file.flush().unwrap();
//success

match self.messages.lock() {
Ok(mut ok) => {
ok.push(ServerOutput::convert_picture_to_servermsg(
req.clone(),
self.image_paths.lock().unwrap().len() as i32,
));
}
Err(err) => println!("{err}"),
}

//Only save as last step to avoid a mismatch + correct indexing :)
match self.image_paths.lock() {
Ok(mut ok) => {
ok.push(PathBuf::from(format!(
"{app_data}\\szeChat\\Server\\{}",
self.image_paths.lock().unwrap().len()
)));
}
Err(err) => {
println!("{err}")
}
};

}
Err(err) => {
println!(" [{err} {}]", err.kind());
}
}
}
Err(err) => {
println!("{err}")
}
}
};

}
}
pub async fn recive_file(&self, request: Message) {
/*
Expand Down
8 changes: 3 additions & 5 deletions src/app/ui/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use device_query::Keycode;
use egui::epaint::RectShape;
use egui::{
vec2, Align, Align2, Area, Button, Color32, FontFamily, FontId, Id, ImageButton, Layout, Pos2,
RichText, Stroke, TextBuffer, Ui, Response,
Response, RichText, Stroke, TextBuffer, Ui,
};

use rand::Rng;
Expand Down Expand Up @@ -305,7 +305,7 @@ impl TemplateApp {
}
if let ServerMessageType::Image(picture) = &item.MessageType {
ui.allocate_ui(vec2(300., 300.), |ui|{
ui.add(egui::widgets::Image::from_bytes("bytes://", picture.bytes.clone()));
ui.label(picture.index.to_string());
});
}
ui.label(RichText::from(format!("{}", item.MessageDate)).size(self.font_size / 1.5).color(Color32::DARK_GRAY));
Expand Down Expand Up @@ -633,9 +633,8 @@ impl TemplateApp {
tokio::spawn(async move {
let _ = client::send_msg(message).await;
});

}

fn send_picture(&mut self, file: std::path::PathBuf) {
let passw = self.client_password.clone();
let ip = self.send_on_ip.clone();
Expand All @@ -647,6 +646,5 @@ impl TemplateApp {
tokio::spawn(async move {
let _ = client::send_msg(message).await;
});

}
}

0 comments on commit 300a6b6

Please sign in to comment.