caesar: cleaned up unneeded files and added better project structure

This commit is contained in:
Patryk Hegenberg 2024-04-19 17:17:34 +02:00
parent 6f1f927915
commit 518e9416b7
14 changed files with 78 additions and 89 deletions

View file

@ -1,6 +1,6 @@
use crate::http_server;
use crate::receiver;
use crate::sender;
use crate::receiver::receiver;
use crate::sender::sender;
use clap::{Parser, Subcommand};
use log::debug;
@ -33,7 +33,7 @@ pub enum Commands {
overwrite: bool,
/// Name of Transfer to download files
#[arg(short, long, value_name = "Transfer_Name")]
#[arg(value_name = "Transfer_Name")]
name: Option<String>,
},
/// Start a relay server
@ -76,23 +76,25 @@ impl Args {
Self::parse()
}
pub async fn run(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
env_logger::init();
debug!("args: {:?}", self);
debug!("args: {:#?}", self);
match &self.command {
Some(Commands::Send { relay, file }) => {
sender::send_info(
relay.as_deref().unwrap_or("http://192.168.178.43:1323"),
relay.as_deref().unwrap_or("http://0.0.0.0:1323"),
file.as_deref().unwrap_or("test.txt"),
)
.await?;
}
Some(Commands::Receive {
relay: _,
relay,
overwrite: _,
name,
}) => {
let transfer_name = name.as_deref().unwrap_or("None");
receiver::download_info(transfer_name).await?
receiver::download_info(
relay.as_deref().unwrap_or("http://0.0.0.0:1323"),
name.as_deref().unwrap_or("None"),
)
.await?
}
Some(Commands::Serve {
port,

1
src/cli/mod.rs Normal file
View file

@ -0,0 +1 @@
pub mod args;

View file

@ -1,3 +1,4 @@
use crate::transfer_info::transfer_info::{TransferInfoBody, TransferInfoRequest};
use axum::{
extract::{connect_info::ConnectInfo, Json, Path, State},
http::StatusCode,
@ -7,7 +8,6 @@ use axum::{
};
use axum_client_ip::SecureClientIpSource;
use rand::{seq::SliceRandom, thread_rng};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{
env,
@ -15,37 +15,11 @@ use std::{
sync::{Arc, Mutex},
};
use tokio::signal;
use tracing::{debug, error, info, trace, warn};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TransferRequest {
pub ip: String,
pub name: String,
pub body: TransferBody,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TransferBody {
pub keyword: String,
pub files: String,
}
impl TransferRequest {
pub fn new() -> Self {
Self {
ip: "".to_string(),
name: "".to_string(),
body: TransferBody {
keyword: "".to_string(),
files: "".to_string(),
},
}
}
}
use tracing::{debug, info, warn};
#[derive(Debug, Clone)]
struct AppState {
data: Arc<Mutex<Vec<TransferRequest>>>,
data: Arc<Mutex<Vec<TransferInfoRequest>>>,
}
pub async fn start_server(port: Option<&i32>, listen_addr: Option<&String>) {
@ -110,7 +84,7 @@ async fn download_info(
}
None => {
warn!("couldn't find transfer-name: {}", name);
(StatusCode::NOT_FOUND, Json(TransferRequest::new()))
(StatusCode::NOT_FOUND, Json(TransferInfoRequest::new()))
}
}
}
@ -118,14 +92,14 @@ async fn download_info(
async fn upload_info(
State(shared_state): State<AppState>,
ConnectInfo(addr): ConnectInfo<SocketAddr>,
Json(payload): Json<TransferBody>,
Json(payload): Json<TransferInfoBody>,
) -> impl IntoResponse {
debug!("Got upload request from {}", addr.ip().to_string());
let mut data = shared_state.data.lock().unwrap();
let t_request = TransferRequest {
let t_request = TransferInfoRequest {
ip: addr.ip().to_string(),
name: generate_random_name(),
body: TransferBody {
body: TransferInfoBody {
keyword: payload.keyword,
files: payload.files,
},

View file

@ -1,16 +1,20 @@
pub mod args;
pub mod http_client;
pub mod http_server;
pub mod receiver;
pub mod sender;
mod cli;
mod http_client;
mod http_server;
mod receiver;
mod sender;
mod transfer_info;
use crate::cli::args::Args;
use dotenv::dotenv;
use tracing::error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
dotenv().ok();
let args = args::Args::new();
env_logger::init();
let args = Args::new();
if let Err(e) = args.run().await {
eprintln!("Error {e}");
error!("{e}");
}
Ok(())
}

View file

@ -1,28 +0,0 @@
use serde::{Deserialize, Serialize};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
#[derive(Debug, Serialize, Deserialize)]
struct TransferInfo {
ip: String,
name: String,
body: TransferInfoBody,
}
#[derive(Debug, Serialize, Deserialize)]
struct TransferInfoBody {
keyword: String,
files: String,
}
pub async fn download_info(filename: &str) -> Result<()> {
match reqwest::get(format!("http://192.168.178.43:1323/download/{}", filename)).await {
Ok(resp) => {
let json = resp.json::<TransferInfo>().await?;
println!("Json Response: {:#?}", json);
}
Err(err) => {
println!("Error: {err}");
}
}
Ok(())
}

1
src/receiver/mod.rs Normal file
View file

@ -0,0 +1 @@
pub mod receiver;

16
src/receiver/receiver.rs Normal file
View file

@ -0,0 +1,16 @@
use crate::transfer_info::transfer_info::TransferInfoRequest;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
pub async fn download_info(relay: &str, filename: &str) -> Result<()> {
match reqwest::get(format!("{}/download/{}", relay.to_string(), filename)).await {
Ok(resp) => {
let json = resp.json::<TransferInfoRequest>().await?;
println!("Json Response: {:#?}", json);
}
Err(err) => {
println!("Error: {err}");
}
}
Ok(())
}

0
src/relay/mod.rs Normal file
View file

1
src/sender/mod.rs Normal file
View file

@ -0,0 +1 @@
pub mod sender;

View file

@ -1,4 +1,4 @@
use crate::http_server::TransferRequest;
use crate::transfer_info::transfer_info::TransferInfoRequest;
use log::{debug, error};
use reqwest::{Client, StatusCode};
use std::collections::HashMap;
@ -18,7 +18,7 @@ pub async fn send_info(relay: &str, file: &str) -> Result<()> {
.send()
.await?;
if res.status() == StatusCode::CREATED {
let transfer_info: TransferRequest = res.json().await?;
let transfer_info: TransferInfoRequest = res.json().await?;
debug!("Json Response: {:#?}", transfer_info);
println!("Transfer name: {}", transfer_info.name);
} else {

View file

@ -1,10 +0,0 @@
use std::convert::Infallible;
use std::net::SocketAddr;
use http_body_util::Full;
use hyper::body::Bytes;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Request, Response};
use hyper_util::rt::TokioIo;
use tokio::net::TcpListener;

1
src/transfer_info/mod.rs Normal file
View file

@ -0,0 +1 @@
pub mod transfer_info;

View file

@ -0,0 +1,27 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TransferInfoRequest {
pub ip: String,
pub name: String,
pub body: TransferInfoBody,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TransferInfoBody {
pub keyword: String,
pub files: String,
}
impl TransferInfoRequest {
pub fn new() -> Self {
Self {
ip: "".to_string(),
name: "".to_string(),
body: TransferInfoBody {
keyword: "".to_string(),
files: "".to_string(),
},
}
}
}