mirror of
https://github.com/etiennecollin/unifi-voucher-manager.git
synced 2025-10-23 08:12:15 +00:00
refactor: cleanup of backend
This commit is contained in:
103
backend/src/environment.rs
Normal file
103
backend/src/environment.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
use std::{env, sync::OnceLock};
|
||||
|
||||
use chrono_tz::Tz;
|
||||
use tracing::{error, info};
|
||||
|
||||
const DEFAULT_BACKEND_BIND_HOST: &str = "127.0.0.1";
|
||||
const DEFAULT_BACKEND_BIND_PORT: u16 = 8080;
|
||||
const DEFAULT_UNIFI_SITE_ID: &str = "default";
|
||||
const DEEFAULT_ROLLING_VOUCHER_DURATION_MINUTES: u64 = 480;
|
||||
|
||||
pub static ENVIRONMENT: OnceLock<Environment> = OnceLock::new();
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Environment {
|
||||
pub unifi_controller_url: String,
|
||||
pub unifi_site_id: String,
|
||||
pub unifi_api_key: String,
|
||||
pub backend_bind_host: String,
|
||||
pub backend_bind_port: u16,
|
||||
pub rolling_voucher_duration_minutes: u64,
|
||||
pub unifi_has_valid_cert: bool,
|
||||
pub timezone: Tz,
|
||||
}
|
||||
|
||||
impl Environment {
|
||||
pub fn try_new() -> Result<Self, String> {
|
||||
#[cfg(feature = "dotenv")]
|
||||
dotenvy::dotenv().map_err(|e| format!("Failed to load .env file: {e}"))?;
|
||||
|
||||
let unifi_controller_url: String =
|
||||
env::var("UNIFI_CONTROLLER_URL").map_err(|e| format!("UNIFI_CONTROLLER_URL: {e}"))?;
|
||||
|
||||
if !unifi_controller_url.starts_with("http://")
|
||||
&& !unifi_controller_url.starts_with("https://")
|
||||
{
|
||||
return Err("UNIFI_CONTROLLER_URL must start with http:// or https://".to_string());
|
||||
}
|
||||
|
||||
let unifi_api_key: String =
|
||||
env::var("UNIFI_API_KEY").map_err(|e| format!("UNIFI_API_KEY: {e}"))?;
|
||||
let unifi_site_id: String =
|
||||
env::var("UNIFI_SITE_ID").unwrap_or(DEFAULT_UNIFI_SITE_ID.to_owned());
|
||||
|
||||
let backend_bind_host: String =
|
||||
env::var("BACKEND_BIND_HOST").unwrap_or(DEFAULT_BACKEND_BIND_HOST.to_owned());
|
||||
let backend_bind_port: u16 = match env::var("BACKEND_BIND_PORT") {
|
||||
Ok(port_str) => port_str
|
||||
.parse()
|
||||
.map_err(|e| format!("Invalid BACKEND_BIND_PORT: {e}"))?,
|
||||
Err(_) => DEFAULT_BACKEND_BIND_PORT,
|
||||
};
|
||||
|
||||
let rolling_voucher_duration_minutes = match env::var("ROLLING_VOUCHER_DURATION_MINUTES") {
|
||||
Ok(val) => val
|
||||
.parse()
|
||||
.map_err(|e| format!("Invalid ROLLING_VOUCHER_DURATION_MINUTES: {e}"))?,
|
||||
Err(_) => DEEFAULT_ROLLING_VOUCHER_DURATION_MINUTES,
|
||||
};
|
||||
|
||||
let unifi_has_valid_cert: bool = match env::var("UNIFI_HAS_VALID_CERT") {
|
||||
Ok(val) => {
|
||||
Self::parse_bool(&val).map_err(|e| format!("Invalid UNIFI_HAS_VALID_CERT: {e}"))?
|
||||
}
|
||||
Err(_) => true,
|
||||
};
|
||||
|
||||
let timezone: Tz = match env::var("TIMEZONE") {
|
||||
Ok(s) => match s.parse() {
|
||||
Ok(tz) => {
|
||||
info!("Using timezone: {}", s);
|
||||
tz
|
||||
}
|
||||
Err(_) => {
|
||||
error!("Using UTC, could not parse timezone: {}", s);
|
||||
Tz::UTC
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
info!("TIMEZONE environment variable not set, defaulting to UTC");
|
||||
Tz::UTC
|
||||
}
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
unifi_controller_url,
|
||||
unifi_site_id,
|
||||
unifi_api_key,
|
||||
backend_bind_host,
|
||||
backend_bind_port,
|
||||
rolling_voucher_duration_minutes,
|
||||
unifi_has_valid_cert,
|
||||
timezone,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_bool(s: &str) -> Result<bool, String> {
|
||||
match s.trim().to_lowercase().as_str() {
|
||||
"true" | "1" | "yes" => Ok(true),
|
||||
"false" | "0" | "no" => Ok(false),
|
||||
_ => Err(format!("Boolean value must be true or false, found: {s}")),
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,4 +1,3 @@
|
||||
use crate::{models::*, unifi_api::*};
|
||||
use axum::{
|
||||
extract::Query,
|
||||
http::{HeaderMap, StatusCode},
|
||||
@@ -6,6 +5,8 @@ use axum::{
|
||||
};
|
||||
use tracing::{debug, error, info};
|
||||
|
||||
use crate::{models::*, unifi_api::UNIFI_API};
|
||||
|
||||
pub async fn get_vouchers_handler() -> Result<Json<GetVouchersResponse>, StatusCode> {
|
||||
debug!("Received request to get vouchers");
|
||||
let client = UNIFI_API.get().expect("UnifiAPI not initialized");
|
||||
|
@@ -1,107 +1,5 @@
|
||||
use std::{env, sync::OnceLock};
|
||||
|
||||
use chrono_tz::Tz;
|
||||
use tracing::{error, info};
|
||||
|
||||
pub mod environment;
|
||||
pub mod handlers;
|
||||
pub mod models;
|
||||
pub mod tasks;
|
||||
pub mod unifi_api;
|
||||
|
||||
const DEFAULT_BACKEND_BIND_HOST: &str = "127.0.0.1";
|
||||
const DEFAULT_BACKEND_BIND_PORT: u16 = 8080;
|
||||
const DEFAULT_UNIFI_SITE_ID: &str = "default";
|
||||
const DEEFAULT_ROLLING_VOUCHER_DURATION_MINUTES: u64 = 480;
|
||||
|
||||
pub static ENVIRONMENT: OnceLock<Environment> = OnceLock::new();
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Environment {
|
||||
pub unifi_controller_url: String,
|
||||
pub unifi_site_id: String,
|
||||
pub unifi_api_key: String,
|
||||
pub backend_bind_host: String,
|
||||
pub backend_bind_port: u16,
|
||||
pub rolling_voucher_duration_minutes: u64,
|
||||
pub unifi_has_valid_cert: bool,
|
||||
pub timezone: Tz,
|
||||
}
|
||||
|
||||
impl Environment {
|
||||
pub fn try_new() -> Result<Self, String> {
|
||||
#[cfg(feature = "dotenv")]
|
||||
dotenvy::dotenv().map_err(|e| format!("Failed to load .env file: {e}"))?;
|
||||
|
||||
let unifi_controller_url: String =
|
||||
env::var("UNIFI_CONTROLLER_URL").map_err(|e| format!("UNIFI_CONTROLLER_URL: {e}"))?;
|
||||
|
||||
if !unifi_controller_url.starts_with("http://")
|
||||
&& !unifi_controller_url.starts_with("https://")
|
||||
{
|
||||
return Err("UNIFI_CONTROLLER_URL must start with http:// or https://".to_string());
|
||||
}
|
||||
|
||||
let unifi_api_key: String =
|
||||
env::var("UNIFI_API_KEY").map_err(|e| format!("UNIFI_API_KEY: {e}"))?;
|
||||
let unifi_site_id: String =
|
||||
env::var("UNIFI_SITE_ID").unwrap_or(DEFAULT_UNIFI_SITE_ID.to_owned());
|
||||
|
||||
let backend_bind_host: String =
|
||||
env::var("BACKEND_BIND_HOST").unwrap_or(DEFAULT_BACKEND_BIND_HOST.to_owned());
|
||||
let backend_bind_port: u16 = match env::var("BACKEND_BIND_PORT") {
|
||||
Ok(port_str) => port_str
|
||||
.parse()
|
||||
.map_err(|e| format!("Invalid BACKEND_BIND_PORT: {e}"))?,
|
||||
Err(_) => DEFAULT_BACKEND_BIND_PORT,
|
||||
};
|
||||
|
||||
let rolling_voucher_duration_minutes = match env::var("ROLLING_VOUCHER_DURATION_MINUTES") {
|
||||
Ok(val) => val
|
||||
.parse()
|
||||
.map_err(|e| format!("Invalid ROLLING_VOUCHER_DURATION_MINUTES: {e}"))?,
|
||||
Err(_) => DEEFAULT_ROLLING_VOUCHER_DURATION_MINUTES,
|
||||
};
|
||||
|
||||
let unifi_has_valid_cert: bool = match env::var("UNIFI_HAS_VALID_CERT") {
|
||||
Ok(val) => {
|
||||
Self::parse_bool(&val).map_err(|e| format!("Invalid UNIFI_HAS_VALID_CERT: {e}"))?
|
||||
}
|
||||
Err(_) => true,
|
||||
};
|
||||
|
||||
let timezone: Tz = match env::var("TIMEZONE") {
|
||||
Ok(s) => match s.parse() {
|
||||
Ok(tz) => {
|
||||
info!("Using timezone: {}", s);
|
||||
tz
|
||||
}
|
||||
Err(_) => {
|
||||
error!("Using UTC, could not parse timezone: {}", s);
|
||||
Tz::UTC
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
info!("TIMEZONE environment variable not set, defaulting to UTC");
|
||||
Tz::UTC
|
||||
}
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
unifi_controller_url,
|
||||
unifi_site_id,
|
||||
unifi_api_key,
|
||||
backend_bind_host,
|
||||
backend_bind_port,
|
||||
rolling_voucher_duration_minutes,
|
||||
unifi_has_valid_cert,
|
||||
timezone,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_bool(s: &str) -> Result<bool, String> {
|
||||
match s.trim().to_lowercase().as_str() {
|
||||
"true" | "1" | "yes" => Ok(true),
|
||||
"false" | "0" | "no" => Ok(false),
|
||||
_ => Err(format!("Boolean value must be true or false, found: {s}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -3,18 +3,21 @@ use axum::{
|
||||
http::{self, Method},
|
||||
routing::{delete, get, post},
|
||||
};
|
||||
use backend::{
|
||||
ENVIRONMENT, Environment,
|
||||
handlers::*,
|
||||
unifi_api::{UNIFI_API, UnifiAPI},
|
||||
};
|
||||
use tower_http::cors::{Any, CorsLayer};
|
||||
use tracing::{error, info, level_filters::LevelFilter, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
use backend::{
|
||||
environment::{ENVIRONMENT, Environment},
|
||||
handlers::*,
|
||||
unifi_api::{UNIFI_API, UnifiAPI},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// =================================
|
||||
// Initialize tracing
|
||||
// =================================
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
EnvFilter::builder()
|
||||
@@ -24,6 +27,9 @@ async fn main() {
|
||||
)
|
||||
.init();
|
||||
|
||||
// =================================
|
||||
// Setup environment variables manager
|
||||
// =================================
|
||||
let env = match Environment::try_new() {
|
||||
Ok(env) => env,
|
||||
Err(e) => {
|
||||
@@ -34,7 +40,11 @@ async fn main() {
|
||||
ENVIRONMENT
|
||||
.set(env)
|
||||
.expect("Failed to set environment variables");
|
||||
let environment = ENVIRONMENT.get().expect("Environment not set");
|
||||
|
||||
// =================================
|
||||
// Setup UniFi Controller API connection
|
||||
// =================================
|
||||
loop {
|
||||
match UnifiAPI::try_new().await {
|
||||
Ok(api) => {
|
||||
@@ -50,6 +60,9 @@ async fn main() {
|
||||
}
|
||||
}
|
||||
|
||||
// =================================
|
||||
// Setup Axum server
|
||||
// =================================
|
||||
let cors = CorsLayer::new()
|
||||
.allow_headers([http::header::CONTENT_TYPE])
|
||||
.allow_methods([Method::POST, Method::GET, Method::DELETE])
|
||||
@@ -74,13 +87,18 @@ async fn main() {
|
||||
.route("/api/vouchers/selected", delete(delete_selected_handler))
|
||||
.layer(cors);
|
||||
|
||||
let environment = ENVIRONMENT.get().expect("Environment not set");
|
||||
let bind_address = format!(
|
||||
"{}:{}",
|
||||
environment.backend_bind_host, environment.backend_bind_port
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind(&bind_address).await.unwrap();
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(&bind_address)
|
||||
.await
|
||||
.expect("Could not bind listener");
|
||||
|
||||
info!("Server running on http://{}", bind_address);
|
||||
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.expect("Axum server should never error");
|
||||
}
|
||||
|
@@ -1,12 +1,11 @@
|
||||
use axum::http::HeaderValue;
|
||||
use chrono::DateTime;
|
||||
use chrono_tz::Tz;
|
||||
use reqwest::{Client, ClientBuilder, StatusCode};
|
||||
use std::{sync::OnceLock, time::Duration};
|
||||
use tracing::{debug, error, info, warn};
|
||||
|
||||
use crate::{
|
||||
ENVIRONMENT, Environment,
|
||||
environment::{ENVIRONMENT, Environment},
|
||||
models::{
|
||||
CreateVoucherRequest, CreateVoucherResponse, DeleteResponse, ErrorResponse,
|
||||
GetSitesResponse, GetVouchersResponse, Voucher,
|
||||
@@ -85,6 +84,36 @@ impl<'a> UnifiAPI<'a> {
|
||||
Ok(unifi_api)
|
||||
}
|
||||
|
||||
fn format_unifi_date(&self, rfc3339_string: &str) -> String {
|
||||
match DateTime::parse_from_rfc3339(rfc3339_string) {
|
||||
Ok(dt) => {
|
||||
let local_time = dt.with_timezone(&self.environment.timezone);
|
||||
local_time.format(DATE_TIME_FORMAT).to_string()
|
||||
}
|
||||
Err(_) => {
|
||||
error!("Failed to parse RFC3339 date: {}", rfc3339_string);
|
||||
rfc3339_string.to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_voucher(&self, voucher: &mut Voucher) {
|
||||
voucher.created_at = self.format_unifi_date(&voucher.created_at);
|
||||
if let Some(activated_at) = &mut voucher.activated_at {
|
||||
*activated_at = self.format_unifi_date(activated_at);
|
||||
}
|
||||
if let Some(expires_at) = &mut voucher.expires_at {
|
||||
*expires_at = self.format_unifi_date(expires_at);
|
||||
}
|
||||
}
|
||||
|
||||
fn process_vouchers(&self, mut vouchers: Vec<Voucher>) -> Vec<Voucher> {
|
||||
vouchers.iter_mut().for_each(|voucher| {
|
||||
self.process_voucher(voucher);
|
||||
});
|
||||
vouchers
|
||||
}
|
||||
|
||||
async fn make_request<
|
||||
T: serde::ser::Serialize + Sized,
|
||||
U: serde::de::DeserializeOwned + Sized,
|
||||
@@ -160,23 +189,6 @@ impl<'a> UnifiAPI<'a> {
|
||||
})
|
||||
}
|
||||
|
||||
fn process_voucher(&self, voucher: &mut Voucher) {
|
||||
voucher.created_at = format_unifi_date(&voucher.created_at, &self.environment.timezone);
|
||||
if let Some(activated_at) = &mut voucher.activated_at {
|
||||
*activated_at = format_unifi_date(activated_at, &self.environment.timezone);
|
||||
}
|
||||
if let Some(expires_at) = &mut voucher.expires_at {
|
||||
*expires_at = format_unifi_date(expires_at, &self.environment.timezone);
|
||||
}
|
||||
}
|
||||
|
||||
fn process_vouchers(&self, mut vouchers: Vec<Voucher>) -> Vec<Voucher> {
|
||||
vouchers.iter_mut().for_each(|voucher| {
|
||||
self.process_voucher(voucher);
|
||||
});
|
||||
vouchers
|
||||
}
|
||||
|
||||
async fn get_default_site_id(&self) -> Result<String, StatusCode> {
|
||||
let url = format!(
|
||||
"{}?filter=or(internalReference.eq('default'),name.eq('Default'))",
|
||||
@@ -241,7 +253,7 @@ impl<'a> UnifiAPI<'a> {
|
||||
.unwrap_or_else(|_| DateTime::UNIX_EPOCH.fixed_offset())
|
||||
})
|
||||
.cloned()
|
||||
.expect("At least one voucher exists");
|
||||
.expect("At least one voucher should exist");
|
||||
|
||||
Ok(newest)
|
||||
}
|
||||
@@ -353,16 +365,3 @@ impl<'a> UnifiAPI<'a> {
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
fn format_unifi_date(rfc3339_string: &str, target_timezone: &Tz) -> String {
|
||||
match DateTime::parse_from_rfc3339(rfc3339_string) {
|
||||
Ok(dt) => {
|
||||
let local_time = dt.with_timezone(target_timezone);
|
||||
local_time.format(DATE_TIME_FORMAT).to_string()
|
||||
}
|
||||
Err(_) => {
|
||||
error!("Failed to parse RFC3339 date: {}", rfc3339_string);
|
||||
rfc3339_string.to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user