refactor(sender, receiver, relay): changed use of .env file to a config file

added support for a config file. under linux this will be under
XDG_HOME/.config/caesar with name caesar.toml
This commit is contained in:
Patryk Hegenberg 2024-05-09 15:22:48 +02:00
parent bb492aa962
commit aa183a30bd
5 changed files with 226 additions and 46 deletions

View file

@ -17,7 +17,9 @@ serde_json = { version = "1.0" }
serde = { version = "1.0", features = ["derive"] }
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
dotenv = { version = "0.15.0", features = ["clap", "cli"] }
clap = { version = "4.5.4", features = ["derive"] }
axum = { version = "0.7.5", features = ["ws"] }
axum-client-ip = "0.6.0"
confy = "0.6.1"
dotenvy = { version = "0.15.7", features = ["clap", "cli"] }
lazy_static = "1.4.0"

View file

@ -5,6 +5,8 @@ use clap::{Parser, Subcommand};
use std::{env, sync::Arc};
use tracing::debug;
use crate::GLOBAL_CONFIG;
#[derive(Parser, Debug)]
#[command(version = env!("CARGO_PKG_VERSION"), about = "Send and receive files securely")]
#[command(long_about = None)]
@ -61,16 +63,11 @@ impl Args {
}
pub async fn run(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let cfg = &GLOBAL_CONFIG;
debug!("args: {:#?}", self);
match &self.command {
Some(Commands::Send { relay, files }) => {
let relay_string: String = relay
.as_deref()
.unwrap_or(
&env::var("APP_ORIGIN")
.unwrap_or("wss://caesar-transfer-iu.shuttleapp.rs/ws".to_string()),
)
.to_string();
let relay_string: String = relay.as_deref().unwrap_or(&cfg.app_origin).to_string();
let relay_arc = Arc::new(relay_string);
let files_arc = Arc::new(files.to_vec());
sender::start_sender(relay_arc, files_arc).await;
@ -81,22 +78,20 @@ impl Args {
name,
}) => {
println!("Receive for {name:?}");
receiver::start_receiver(
relay.as_deref().unwrap_or(
env::var("APP_ORIGIN")
.unwrap_or("ws://0.0.0.0:8000/ws".to_string())
.as_str(),
),
name,
)
.await;
receiver::start_receiver(relay.as_deref().unwrap_or(&cfg.app_origin), name).await;
}
Some(Commands::Serve {
port,
listen_address,
}) => {
println!("Serve with address '{listen_address:?}' and '{port:?}'");
relay::server::start_ws(port.as_ref(), listen_address.as_ref()).await;
let address: String = listen_address
.as_deref()
.unwrap_or(&cfg.app_host)
.to_string();
let port_value = port.unwrap_or(cfg.app_port.parse::<i32>().unwrap_or(0));
let port: i32 = port_value;
relay::server::start_ws(&port, &address).await;
}
None => {}
}

View file

@ -1,33 +1,39 @@
use crate::cli::args::Args;
use dotenv::dotenv;
use dotenvy::dotenv;
use lazy_static::lazy_static;
use serde::{self, Deserialize, Serialize};
use tracing::error;
use tracing_subscriber::filter::EnvFilter;
mod cli;
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
struct CaesarConfig {
app_environment: String,
app_host: String,
app_port: String,
app_origin: String,
app_relay: String,
rust_log: String,
}
lazy_static! {
static ref GLOBAL_CONFIG: CaesarConfig = {
let cfg: CaesarConfig = confy::load("caesar", "caesar")
.expect("Konfigurationsdatei konnte nicht geladen werden");
cfg
};
}
#[tokio::main]
// This is the entrypoint of caesar.
// The #[tokio::main] attribute is required for any async code, and it
// sets up the tokio runtime.
// The async fn main() is the entrypoint of the application, and it's where
// we kick off our program.
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Load environment variables from a .env file if one is present.
dotenv().ok();
// Set up our logging subscriber.
// TheEnvFilter::from_default_env reads the env variable RUST_LOG
// and sets up the logging accordingly.
// The default is INFO level logging.
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.init();
// Parse the command line arguments.
let args = Args::new();
// Run the commands based on the parsed arguments.
// If there is an error, print it to the console with the error! macro.
if let Err(e) = args.run().await {
error!("{e}");
}
// Return an Ok result, which just means that our program exited successfully.
Ok(())
}