Skip to content

Commit

Permalink
app v-0.7.6:
Browse files Browse the repository at this point in the history
remove dead and depreciated codes
  • Loading branch information
opeolluwa committed May 19, 2024
1 parent e0e13e7 commit b94c06f
Show file tree
Hide file tree
Showing 18 changed files with 337 additions and 533 deletions.
2 changes: 1 addition & 1 deletion desktop/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ serde_json = "1.0"
sqlx = {version = "0.6.2", features = ["sqlite", "runtime-tokio-native-tls"] }
sys-info = "0.9.1"
sysinfo = "0.29.2"
tauri = {version = "1.2", features = [ "window-all", "app-all", "dialog-all", "fs-all", "path-all", "shell-open"] }
tauri = {version = "1.2", features = [ "clipboard-write-text", "window-all", "app-all", "dialog-all", "fs-all", "path-all", "shell-open"] }
tokio = {version = "1.26.0", features = ["full"] }
tokio-util = {version = "0.7", features = ["io"] }
tower = {version = "0.4", features = ["util"] }
Expand Down
40 changes: 39 additions & 1 deletion desktop/core/src/file_manager/file.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use crate::utils::fs::compute_file_size;
use filesize::PathExt;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
Expand All @@ -8,6 +7,44 @@ use walkdir::DirEntry;
extern crate dirs;
use path_absolutize::*;




/// a function to compute file size
/// accept files size in byte and parse it to human readable KB, MB, TB, GB e.t.
pub fn compute_file_size(size: u128) -> String {
if size > (1024 * 1024 * 1024 * 1024) {
format!("{:.2} TB", size / (1024 * 1024 * 1024 * 1024))
} else if size > (1024 * 1024 * 1024) {
format!("{:.2} GB", size / (1024 * 1024 * 1024))
} else if size > (1024 * 1024) {
format!("{:.2} MB", size / (1024 * 1024))
} else if size > 1024 {
format!("{:.2} KB", size / (1024))
} else {
format!("{:.2} B", size)
}
}



#[derive(serde::Serialize, Debug)]
pub struct DriveInformation {
name: String,
mount_point: String,
total_space: u64,
available_space: u64,
is_removable: bool,
disk_type: String,
file_system: String,
}

#[derive(serde::Serialize)]
pub struct Drives {
array_of_drives: Vec<DriveInformation>,
}


// the file structure
#[derive(Debug, Default, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
Expand All @@ -21,6 +58,7 @@ pub struct File {
pub is_folder: bool,
}

#[allow(unused)]
impl File {
// convert a DirEntry to a File
pub fn from(entry: DirEntry) -> Self {
Expand Down
234 changes: 233 additions & 1 deletion desktop/core/src/file_manager/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,234 @@
pub mod file;
pub mod search;

use std::net::Ipv4Addr;
use std::path::PathBuf;
use crate::UPLOAD_PATH;
use crate::{
file_manager::file::{get_files_in_directory, File},
utils::{ApiResponse, CommandData},
};
use dirs;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use ts_rs::TS;

use crate::database::{self, TransferHistory, TransferHistoryBuilder};
use crate::network_manager::ip_manager;
use tokio::io::AsyncReadExt;

/// the dir enum, reads, $HOME, $PICTURES, $VIDEOS, $DOCUMENTS, $DOWNLOADS, and // Other
/// the other is a unit struct that contains a path of the directory to be red
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[ts(export)]
pub(crate) enum Dir {
/// the device home directory
Home,
Pictures,
Videos,
Documents,
Downloads,
Audio,
Desktop,
/// the location the files received are saved
FileSync,
Other(String),
}

impl Dir {
/// to string
pub fn _to_string(&self) -> String {
match self {
Dir::Home => dirs::home_dir().unwrap().to_str().unwrap().to_string(),
Dir::Pictures => dirs::picture_dir().unwrap().to_str().unwrap().to_string(),
Dir::Videos => dirs::video_dir().unwrap().to_str().unwrap().to_string(),
Dir::Documents => dirs::document_dir().unwrap().to_str().unwrap().to_string(),
Dir::Downloads => dirs::download_dir().unwrap().to_str().unwrap().to_string(),
Dir::Audio => dirs::audio_dir().unwrap().to_str().unwrap().to_string(),
Dir::Desktop => dirs::desktop_dir().unwrap().to_str().unwrap().to_string(),
Dir::FileSync => UPLOAD_PATH.to_string(),
Dir::Other(path) => path.to_string(),
}
}

// convert to path
pub fn to_path(&self) -> std::path::PathBuf {
match self {
Dir::Home => dirs::home_dir().unwrap(),
Dir::Pictures => dirs::picture_dir().unwrap(),
Dir::Videos => dirs::video_dir().unwrap(),
Dir::Documents => dirs::document_dir().unwrap(),
Dir::Downloads => dirs::download_dir().unwrap(),
Dir::Audio => dirs::audio_dir().unwrap(),
Dir::Desktop => dirs::desktop_dir().unwrap(),
Dir::FileSync => PathBuf::from(UPLOAD_PATH.to_string()),
Dir::Other(path) => PathBuf::from(path),
}
}

// from string
pub fn from_string(path: &str) -> Self {
match path {
"home" => Dir::Home,
"pictures" => Dir::Pictures,
"videos" => Dir::Videos,
"documents" => Dir::Documents,
"downloads" => Dir::Downloads,
"audio" => Dir::Audio,
"desktop" => Dir::Desktop,
"filesync" => Dir::FileSync,
_ => Dir::Other(path.to_string()),
}
}
}

/// read directory
#[tauri::command]
pub async fn read_dir(path: &str) -> ApiResponse<Vec<File>, ()> {
println!("reading from {path}");
let path = Dir::from_string(path).to_path();
let files = get_files_in_directory(&path).await;
if files.is_err() {
return Err(CommandData::err("Error fetching files", ()));
}

// convert to file type
let mut entries: Vec<File> = Vec::new();
for entry in files.unwrap() {
let file_path = PathBuf::from(entry);
let file = File::from_path(&file_path);
entries.push(file)
}

Ok(CommandData::ok("Successfully fetch the data", entries))
}

// send file from this server to another
// accept path to file as argument
// validate the file existence
// use streams to upload
// the server id is the port on which the peer node run eg -> 23345
#[tauri::command(async)]
pub async fn _share_file_with_peer(
file_path: String,
server_id: u16,
) -> Result<CommandData<Value>, CommandData<()>> {
let mut file = tokio::fs::File::open(file_path).await.unwrap();
let mut vec = Vec::new();
println!("file content {vec:?}");
let _ = file.read_to_end(&mut vec).await.unwrap();
// println!("file content {vec:?}");

// file.read_to_end(&mut vec).await.unwrap();
let client = reqwest::Client::new();

// get the IP address of the share network
let my_local_ip = ip_manager::autodetect_ip_address()
.ok()
.unwrap()
// .expect("Invalid Ip address detected")
.parse::<Ipv4Addr>()
.unwrap();
let ip_address = format!("http://{:?}:{:?}/upload", my_local_ip, server_id);

println!("my client id is {ip_address}");
let _res = client
.post(&ip_address)
.header("content-type", "application/octet-stream")
.body(vec)
.send()
.await
.unwrap();

println!("the response here {_res:?}");

// return an instance of the command data
// Ok(CommandData::new("file successfully sent", true, res))
Ok(CommandData::ok(
"file successfully sent",
json!({
"success":true,
// data:r
}),
))
// todo!()
}

// save file transfer to the database
//TODO: test this
#[tauri::command(async)]
pub async fn _save_file_transfer(
file_path: String,
server_id: u16,
) -> Result<CommandData<Value>, CommandData<()>> {
let mut file = tokio::fs::File::open(file_path).await.unwrap();
let mut vec = Vec::new();
println!("file content {vec:?}");
let _ = file.read_to_end(&mut vec).await.unwrap();
// println!("file content {vec:?}");

// file.read_to_end(&mut vec).await.unwrap();
let client = reqwest::Client::new();

// get the IP address of the share network
let my_local_ip = ip_manager::autodetect_ip_address()
.ok()
.unwrap()
// .expect("Invalid Ip address detected")
.parse::<Ipv4Addr>()
.unwrap();
let ip_address = format!("http://{:?}:{:?}/upload", my_local_ip, server_id);

println!("my client id is {ip_address}");
let _res = client
.post(&ip_address)
.header("content-type", "application/octet-stream")
.body(vec)
.send()
.await
.unwrap();

println!("the response here {_res:?}");

// return an instance of the command data
// Ok(CommandData::new("file successfully sent", true, res))
Ok(CommandData::ok(
"file successfully sent",
json!({
"success":true,
// data:r
}),
))
// todo!()
}

// save file transfer history
#[tauri::command(async)]
pub async fn _persist_transfer_history(
file: TransferHistoryBuilder,
) -> Result<CommandData<TransferHistory>, CommandData<()>> {
// save the file data in the database
let status = database::TransferHistory::new(file).save().await;
if status.is_err() {
return Err(CommandData::err("error saving file transfer history", ()));
}

Ok(CommandData::ok(
"file transfer history successfully saved",
status.unwrap(),
))
}

// get the file transfer history
#[tauri::command(async)]
pub async fn get_transfer_history() -> Result<CommandData<Vec<TransferHistory>>, CommandData<()>> {
// save the file data in the database
let data = database::TransferHistory::fetch().await;
if data.is_err() {
return Err(CommandData::err("error fetching file transfer history", ()));
}

Ok(CommandData::ok(
"file transfer history successfully fetched",
data.unwrap(),
))
}
Loading

0 comments on commit b94c06f

Please sign in to comment.