refactor(core,gui): make all needed changes to send and receive files on linux and android

This commit is contained in:
Patryk Hegenberg 2024-05-27 21:09:24 +02:00
parent 351b7b9323
commit 0416ab6dab
12 changed files with 108 additions and 193 deletions

View file

@ -22,9 +22,6 @@ use tracing::error;
const DESTINATION: u8 = 0;
const NONCE_SIZE: usize = 12;
#[cfg(target_os = "android")]
const FILE_PATH_PREFIX: &str = "/storage/emulated/0/Documents";
struct File {
name: String,
size: u64,
@ -69,28 +66,18 @@ fn on_leave_room(context: &mut Context, _: usize) -> Status {
}
}
fn on_list(context: &mut Context, list: ListPacket) -> Status {
fn on_list(filepath: String, context: &mut Context, list: ListPacket) -> Status {
if context.shared_key.is_none() {
return Status::Err("Invalid list packet: no shared key established".into());
}
#[cfg(target_os = "android")]
let mut prefix = std::path::PathBuf::from(std::env::current_exe().unwrap());
// #[cfg(target_os = "android")]
// prefix.pop();
// #[cfg(target_os = "android")]
// println!("prefix: {:?}", prefix);
for entry in list.entries {
let path = sanitize_filename::sanitize(entry.name.clone());
#[cfg(target_os = "android")]
let file_path = format!("{}/{}", FILE_PATH_PREFIX, path);
// let file_path = format!("{}/{}", prefix.display(), path);
let file_path = format!("{}/{}", filepath, path);
#[cfg(target_os = "android")]
if Path::new(&file_path).exists() {
return Status::Err(format!("The file '{}' already exists.", path));
}
#[cfg(target_os = "android")]
let handle = match fs::File::create(&file_path) {
Ok(handle) => handle,
Err(error) => {
@ -100,21 +87,6 @@ fn on_list(context: &mut Context, list: ListPacket) -> Status {
));
}
};
#[cfg(not(target_os = "android"))]
if Path::new(&path).exists() {
return Status::Err(format!("The file '{}' already exists.", path));
}
#[cfg(not(target_os = "android"))]
let handle = match fs::File::create(&path) {
Ok(handle) => handle,
Err(error) => {
return Status::Err(format!(
"Error: Failed to create file '{}': {}",
path, error
));
}
};
let file = File {
name: entry.name,
@ -232,7 +204,7 @@ fn on_handshake(context: &mut Context, handshake: HandshakePacket) -> Status {
Status::Continue()
}
fn on_message(context: &mut Context, message: WebSocketMessage) -> Status {
fn on_message(filepath: String, context: &mut Context, message: WebSocketMessage) -> Status {
match message.clone() {
WebSocketMessage::Text(text) => {
let packet = match serde_json::from_str(&text) {
@ -263,7 +235,7 @@ fn on_message(context: &mut Context, message: WebSocketMessage) -> Status {
let packet = Packet::decode(data.as_ref()).unwrap();
let value = packet.value.unwrap();
return match value {
Value::List(list) => on_list(context, list),
Value::List(list) => on_list(filepath, context, list),
Value::Chunk(chunk) => on_chunk(context, chunk),
Value::Handshake(handshake) => on_handshake(context, handshake),
_ => Status::Err(format!("Unexpected packet: {:?}", value)),
@ -275,7 +247,7 @@ fn on_message(context: &mut Context, message: WebSocketMessage) -> Status {
Status::Err("Invalid message type".into())
}
pub async fn start(socket: Socket, fragment: &str) {
pub async fn start(filepath: String, socket: Socket, fragment: &str) {
let Some(index) = fragment.rfind('-') else {
println!("Error: The invite code '{}' is not valid.", fragment);
return;
@ -316,7 +288,7 @@ pub async fn start(socket: Socket, fragment: &str) {
let outgoing_handler = receiver.stream().map(Ok).forward(outgoing);
let incoming_handler = incoming.try_for_each(|message| {
match on_message(&mut context, message) {
match on_message(filepath.clone(), &mut context, message) {
Status::Exit() => {
context.sender.send_json_packet(JsonPacket::Leave);
println!("Transfer has completed.");
@ -338,6 +310,7 @@ pub async fn start(socket: Socket, fragment: &str) {
future::select(incoming_handler, outgoing_handler).await;
}
#[cfg(test)]
mod tests {
use super::*;
@ -412,58 +385,15 @@ mod tests {
};
let text_message = WebSocketMessage::Text(r#"{"type":"join","size":10}"#.to_string());
assert_eq!(on_message(&mut context, text_message), Status::Continue());
assert_eq!(
on_message("".to_string(), &mut context, text_message),
Status::Continue()
);
}
#[test]
fn test_on_chunk() {
let (sender, _) = flume::bounded(1000);
// let mut context = Context {
// hmac: vec![],
// sender: sender.clone(),
// key: EphemeralSecret::random(&mut OsRng),
// shared_key: Some(Aes128Gcm::new(Key::<Aes128Gcm>::from_slice(&[0u8; 16]))),
// files: vec![File {
// name: "file1.txt".to_string(),
// size: 100,
// progress: 0,
// handle: fs::File::create("file1.txt").unwrap(),
// }],
// sequence: 0,
// index: 0,
// progress: 0,
// length: 0,
// };
// let chunk_packet = ChunkPacket {
// sequence: 0,
// chunk: b"Hello, world!".to_vec(),
// };
// assert_eq!(on_chunk(&mut context, chunk_packet), Status::Continue());
// assert_eq!(context.sequence, 1);
// assert_eq!(context.length, 14);
// assert_eq!(context.progress, 14);
// let chunk_packet = ChunkPacket {
// sequence: 1,
// chunk: b"Hello, world!".to_vec(),
// };
// assert_eq!(
// on_chunk(&mut context, chunk_packet),
// Status::Err("Expected sequence 1, but got 1.".into())
// );
// context.files.clear();
// let chunk_packet = ChunkPacket {
// sequence: 0,
// chunk: b"Hello, world!".to_vec(),
// };
// assert_eq!(
// on_chunk(&mut context, chunk_packet),
// Status::Err("Invalid file index.".into())
// );
// Test a chunk packet with no shared key
let mut context = Context {
hmac: vec![],
sender,

View file

@ -10,7 +10,7 @@ use tokio_tungstenite::{
};
use tracing::{debug, error};
pub async fn start_receiver(relay: &str, name: &str) -> Result<()> {
pub async fn start_receiver(filepath: String, relay: &str, name: &str) -> Result<()> {
let http_url = replace_protocol(relay);
let res = http_client::download_info(http_url.as_str(), name)
.await
@ -18,12 +18,24 @@ pub async fn start_receiver(relay: &str, name: &str) -> Result<()> {
debug!("Got room_id from Server: {:?}", res);
let res_ip = String::from("ws://") + res.ip.as_str() + ":9000";
if let Err(local_err) = start_ws_com(res_ip.as_str(), res.local_room_id.as_str()).await {
#[cfg(not(target_os = "android"))]
if let Err(local_err) = start_ws_com(
filepath.clone(),
res_ip.as_str(),
res.local_room_id.as_str(),
)
.await
{
debug!("Failed to connect local: {local_err}");
if let Err(relay_err) = start_ws_com(relay, res.relay_room_id.as_str()).await {
if let Err(relay_err) = start_ws_com(filepath, relay, res.relay_room_id.as_str()).await {
debug!("Failed to connect remote: {relay_err}");
}
}
#[cfg(target_os = "android")]
if let Err(relay_err) = start_ws_com(filepath, relay, res.relay_room_id.as_str()).await {
debug!("Failed to connect remote: {relay_err}");
}
let _success = http_client::download_success(http_url.as_str(), name)
.await
.map_err(|e| anyhow!("Failed to download success: {}", e))?;
@ -32,7 +44,7 @@ pub async fn start_receiver(relay: &str, name: &str) -> Result<()> {
Ok(())
}
pub async fn start_ws_com(relay: &str, name: &str) -> Result<()> {
pub async fn start_ws_com(filepath: String, relay: &str, name: &str) -> Result<()> {
let url = String::from(relay) + "/ws";
let mut request = url
.into_client_request()
@ -48,7 +60,7 @@ pub async fn start_ws_com(relay: &str, name: &str) -> Result<()> {
.await
{
Ok(Ok((socket, _))) => {
receiver::start(socket, name).await;
receiver::start(filepath, socket, name).await;
Ok(())
}
Ok(Err(e)) => {