use crate::errors::ConfigError;
use dotenv::dotenv;
use log::debug;
use std::env;
#[derive(Debug, Clone)]
pub struct Config {
pub client_id: String,
pub client_secret: String,
pub refresh_token: String,
pub access_token: Option<String>,
pub token_refresh_threshold: u64,
pub token_expiry_buffer: u64,
}
impl Config {
pub fn from_env() -> Result<Self, ConfigError> {
if let Ok(path) = std::env::var("DOTENV_PATH") {
let _ = dotenv::from_path(path);
} else {
let _ = dotenv();
}
debug!("Loading Gmail OAuth configuration from environment");
let client_id = env::var("GMAIL_CLIENT_ID")
.map_err(|_| ConfigError::MissingEnvVar("GMAIL_CLIENT_ID".to_string()))?;
let client_secret = env::var("GMAIL_CLIENT_SECRET")
.map_err(|_| ConfigError::MissingEnvVar("GMAIL_CLIENT_SECRET".to_string()))?;
let refresh_token = env::var("GMAIL_REFRESH_TOKEN")
.map_err(|_| ConfigError::MissingEnvVar("GMAIL_REFRESH_TOKEN".to_string()))?;
let access_token = env::var("GMAIL_ACCESS_TOKEN").ok();
let token_refresh_threshold = get_token_refresh_threshold_seconds();
let token_expiry_buffer = get_token_expiry_buffer_seconds();
debug!("OAuth configuration loaded successfully");
debug!("Token refresh threshold: {} seconds", token_refresh_threshold);
debug!("Token expiry buffer: {} seconds", token_expiry_buffer);
Ok(Config {
client_id,
client_secret,
refresh_token,
access_token,
token_refresh_threshold,
token_expiry_buffer,
})
}
}
pub const GMAIL_API_BASE_URL: &str = "https://gmail.googleapis.com/gmail/v1";
pub const OAUTH_TOKEN_URL: &str = "https://oauth2.googleapis.com/token";
pub fn get_token_expiry_seconds() -> u64 {
std::env::var("TOKEN_EXPIRY_SECONDS")
.ok()
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(3540) }
pub fn get_token_expiry_buffer_seconds() -> u64 {
std::env::var("TOKEN_EXPIRY_BUFFER_SECONDS")
.ok()
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(60) }
pub fn get_token_refresh_threshold_seconds() -> u64 {
std::env::var("TOKEN_REFRESH_THRESHOLD_SECONDS")
.ok()
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(300) }