51 lines
1.7 KiB
Rust
51 lines
1.7 KiB
Rust
|
// SPDX-FileCopyrightText: 2022 Matteo Settenvini <matteo.settenvini@montecristosoftware.eu>
|
||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||
|
|
||
|
use {
|
||
|
crate::config::Config, crate::constants, anyhow::anyhow,
|
||
|
base64::write::EncoderWriter as Base64Encoder, reqwest::Url, std::io::Write,
|
||
|
};
|
||
|
|
||
|
pub struct ApiClient {
|
||
|
pub base_url: Url,
|
||
|
pub client: reqwest::Client,
|
||
|
}
|
||
|
|
||
|
impl ApiClient {
|
||
|
pub fn new(server_name: &str, configuration: &Config) -> anyhow::Result<Self> {
|
||
|
let server = configuration
|
||
|
.credentials
|
||
|
.servers
|
||
|
.get(server_name)
|
||
|
.ok_or_else(|| {
|
||
|
anyhow!(
|
||
|
"Unknown server {}. Did you use '{} init' first? Known servers: {:#?}",
|
||
|
server_name,
|
||
|
env!("CARGO_BIN_NAME"),
|
||
|
configuration.credentials.servers.keys().collect::<Vec<_>>()
|
||
|
)
|
||
|
})?;
|
||
|
|
||
|
use reqwest::header;
|
||
|
let mut default_headers = header::HeaderMap::new();
|
||
|
let mut auth_header = b"Basic ".to_vec();
|
||
|
{
|
||
|
let mut encoder = Base64Encoder::new(&mut auth_header, base64::STANDARD);
|
||
|
write!(encoder, "{}:{}", server.login_name, server.password).unwrap();
|
||
|
}
|
||
|
let mut auth_header = header::HeaderValue::from_bytes(&auth_header)?;
|
||
|
auth_header.set_sensitive(true);
|
||
|
default_headers.insert(header::AUTHORIZATION, auth_header);
|
||
|
|
||
|
let client = reqwest::Client::builder()
|
||
|
.user_agent(constants::USER_AGENT)
|
||
|
.default_headers(default_headers)
|
||
|
.build()?;
|
||
|
|
||
|
Ok(ApiClient {
|
||
|
base_url: Url::parse(&server.url)?,
|
||
|
client: client,
|
||
|
})
|
||
|
}
|
||
|
}
|