sender: receiver: http_server: clean up the code

This commit is contained in:
Patryk Hegenberg 2024-04-19 14:13:17 +02:00
parent 240cc45643
commit 6f1f927915
4 changed files with 30 additions and 38 deletions

View file

@ -2,15 +2,16 @@ use crate::http_server;
use crate::receiver; use crate::receiver;
use crate::sender; use crate::sender;
use clap::{Parser, Subcommand}; use clap::{Parser, Subcommand};
use log::debug;
#[derive(Parser)] #[derive(Parser, Debug)]
#[command(version, about, long_about = None)] #[command(version, about, long_about = None)]
pub struct Args { pub struct Args {
#[command(subcommand)] #[command(subcommand)]
pub command: Option<Commands>, pub command: Option<Commands>,
} }
#[derive(Subcommand)] #[derive(Subcommand, Debug)]
pub enum Commands { pub enum Commands {
/// Send files to the receiver or relay server /// Send files to the receiver or relay server
Send { Send {
@ -18,7 +19,7 @@ pub enum Commands {
#[arg(short, long)] #[arg(short, long)]
relay: Option<String>, relay: Option<String>,
/// Path to file(s) /// Path to file(s)
#[arg(short, long, value_name = "FILE")] #[arg(value_name = "FILE")]
file: Option<String>, file: Option<String>,
}, },
/// Receives Files from the sender with the matching password /// Receives Files from the sender with the matching password
@ -75,9 +76,15 @@ impl Args {
Self::parse() Self::parse()
} }
pub async fn run(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { pub async fn run(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
env_logger::init();
debug!("args: {:?}", self);
match &self.command { match &self.command {
Some(Commands::Send { relay: _, file }) => { Some(Commands::Send { relay, file }) => {
sender::send_info(file.as_deref().unwrap_or("test.txt")).await?; sender::send_info(
relay.as_deref().unwrap_or("http://192.168.178.43:1323"),
file.as_deref().unwrap_or("test.txt"),
)
.await?;
} }
Some(Commands::Receive { Some(Commands::Receive {
relay: _, relay: _,

View file

@ -18,20 +18,20 @@ use tokio::signal;
use tracing::{debug, error, info, trace, warn}; use tracing::{debug, error, info, trace, warn};
#[derive(Debug, Serialize, Deserialize, Clone)] #[derive(Debug, Serialize, Deserialize, Clone)]
struct TransferRequest { pub struct TransferRequest {
ip: String, pub ip: String,
name: String, pub name: String,
body: TransferBody, pub body: TransferBody,
} }
#[derive(Debug, Serialize, Deserialize, Clone)] #[derive(Debug, Serialize, Deserialize, Clone)]
struct TransferBody { pub struct TransferBody {
keyword: String, pub keyword: String,
files: String, pub files: String,
} }
impl TransferRequest { impl TransferRequest {
fn new() -> Self { pub fn new() -> Self {
Self { Self {
ip: "".to_string(), ip: "".to_string(),
name: "".to_string(), name: "".to_string(),
@ -49,7 +49,7 @@ struct AppState {
} }
pub async fn start_server(port: Option<&i32>, listen_addr: Option<&String>) { pub async fn start_server(port: Option<&i32>, listen_addr: Option<&String>) {
env_logger::init(); // env_logger::init();
info!("Server starting..."); info!("Server starting...");
let shared_state = AppState { let shared_state = AppState {
data: Arc::new(Mutex::new(Vec::new())), data: Arc::new(Mutex::new(Vec::new())),

View file

@ -1,7 +1,4 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
// use std::collections::HashMap;
// use crate::http_client;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
@ -27,11 +24,5 @@ pub async fn download_info(filename: &str) -> Result<()> {
println!("Error: {err}"); println!("Error: {err}");
} }
} }
// http_client::send_request(
// format!("http://192.168.178.43:1323/download/{}", filename).trim(),
// "GET",
// None,
// )
// .await?;
Ok(()) Ok(())
} }

View file

@ -1,35 +1,29 @@
// use crate::http_client; use crate::http_server::TransferRequest;
use log::{debug, error};
use reqwest::{Client, StatusCode}; use reqwest::{Client, StatusCode};
use serde_json::Value;
use std::collections::HashMap; use std::collections::HashMap;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
pub async fn send_info(file: &str) -> Result<()> { pub async fn send_info(relay: &str, file: &str) -> Result<()> {
debug!("Send Request to: {:?}", relay.to_string());
let mut map = HashMap::new(); let mut map = HashMap::new();
map.insert("keyword", "test"); map.insert("keyword", "test");
map.insert("files", file); map.insert("files", file);
// let json_data = serde_json::to_string(&map)?;
let client = Client::new(); let client = Client::new();
let res = client let res = client
.post("http://192.168.178.43:1323/upload") .post(relay.to_string() + "/upload")
.json(&map) .json(&map)
.send() .send()
.await?; .await?;
if res.status() == StatusCode::CREATED { if res.status() == StatusCode::CREATED {
let json: Value = res.json().await?; let transfer_info: TransferRequest = res.json().await?;
println!("Json Response: {:#?}", json); debug!("Json Response: {:#?}", transfer_info);
println!("Transfer name: {}", transfer_info.name);
} else { } else {
println!("Error reading response"); error!("Error reading response");
} }
// http_client::send_request(
// "http://192.168.178.43:1323/upload".trim(),
// "POST",
// Some(json_data),
// )
// .await?;
Ok(()) Ok(())
} }