nextcloud-cooking-schedule/src/api_client.rs

53 lines
1.8 KiB
Rust
Raw Normal View History

// 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 username: String,
pub rest: 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 rest_client = reqwest::Client::builder()
.user_agent(constants::USER_AGENT)
.default_headers(default_headers)
.build()?;
Ok(ApiClient {
base_url: Url::parse(&server.url)?,
username: server.login_name.clone(),
rest: rest_client,
})
}
}