use std::str::FromStr;
use serde::{Serialize, Deserialize};
use url::Url;
use reqwest::header::HeaderValue;
use reqwest::Proxy;
use crate::glue::*;
use crate::util::*;
#[expect(unused_imports, reason = "Used in a doc comment.")]
use crate::glue::HttpClientConfig;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Suitability)]
#[serde(deny_unknown_fields)]
#[serde(remote = "Self")]
pub struct ProxyConfig {
pub url: Url,
#[serde(default, skip_serializing_if = "is_default")]
pub mode: ProxyMode,
#[serde(default, skip_serializing_if = "is_default")]
pub auth: Option<ProxyAuth>
}
crate::util::string_or_struct_magic!(ProxyConfig);
impl FromStr for ProxyConfig {
type Err = <Url as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Url::from_str(s)?.into())
}
}
impl TryFrom<&str> for ProxyConfig {
type Error = <Self as FromStr>::Err;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::from_str(value)
}
}
impl From<Url> for ProxyConfig {
fn from(url: Url) -> Self {
Self {
url,
mode: ProxyMode::default(),
auth: None
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Eq, Serialize, Deserialize, Suitability)]
#[serde(deny_unknown_fields)]
pub enum ProxyMode {
Http,
Https,
#[default]
All
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Suitability)]
#[serde(deny_unknown_fields)]
pub enum ProxyAuth {
Basic {
username: String,
password: String
},
Custom(#[serde(with = "serde_headervalue")] HeaderValue)
}
impl TryFrom<ProxyConfig> for reqwest::Proxy {
type Error = reqwest::Error;
fn try_from(value: ProxyConfig) -> reqwest::Result<Self> {
let temp = match value.mode {
ProxyMode::Http => Proxy::http (value.url),
ProxyMode::Https => Proxy::https(value.url),
ProxyMode::All => Proxy::all (value.url)
}?;
Ok(match &value.auth {
None => temp,
Some(ProxyAuth::Basic {username, password}) => temp.basic_auth(username, password),
Some(ProxyAuth::Custom(value)) => temp.custom_http_auth(value.clone())
})
}
}
impl ProxyConfig {
pub fn make(self) -> reqwest::Result<Proxy> {
self.try_into()
}
}