2022-07-28 10:28:02 +02:00
|
|
|
// 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,
|
2022-07-28 16:38:12 +02:00
|
|
|
pub username: String,
|
|
|
|
pub rest: reqwest::Client,
|
2022-07-28 10:28:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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);
|
|
|
|
|
2022-07-28 16:38:12 +02:00
|
|
|
let rest_client = reqwest::Client::builder()
|
2022-07-28 10:28:02 +02:00
|
|
|
.user_agent(constants::USER_AGENT)
|
|
|
|
.default_headers(default_headers)
|
|
|
|
.build()?;
|
|
|
|
|
|
|
|
Ok(ApiClient {
|
|
|
|
base_url: Url::parse(&server.url)?,
|
2022-07-28 16:38:12 +02:00
|
|
|
username: server.login_name.clone(),
|
|
|
|
rest: rest_client,
|
2022-07-28 10:28:02 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|