use std::sync::Arc;
use serde_json::Value;
use crate::auth::{rest_error, Auth};
use crate::error::{Error, Result};
use crate::transport::{Body, HttpRequest, HttpResponse};
#[derive(Clone)]
pub(crate) struct Api {
pub auth: Arc<Auth>,
pub wait: bool,
}
pub(crate) fn seg(s: &str) -> String {
form_urlencoded::byte_serialize(s.as_bytes()).collect::<String>().replace('+', "%20")
}
impl Api {
pub fn waiting(&self, wait: bool) -> Api {
Api { auth: self.auth.clone(), wait }
}
pub fn base(&self) -> &str {
&self.auth.base
}
pub async fn send(&self, method: &str, path: &str, json: Option<&Value>) -> Result<HttpResponse> {
for attempt in 0..2 {
let creds = if self.wait { self.auth.credentials().await? } else { self.auth.try_credentials().await? };
let mut headers = vec![
("authorization".to_string(), format!("Bearer {}", creds.token)),
("accept".to_string(), "application/json".to_string()),
];
if let Some(p) = creds.proof()? {
headers.push(("kovlet-device-proof".into(), p));
}
let body = match json {
Some(v) => {
headers.push(("content-type".into(), "application/json".into()));
Body::Bytes(serde_json::to_vec(v)?)
}
None => Body::Empty,
};
let url = if path.starts_with("http") { path.to_string() } else { format!("{}{}", self.auth.base, path) };
let res = self
.auth
.transport()
.http(HttpRequest { method: method.into(), url, headers, body, save_to: None })
.await
.inspect_err(|_| self.auth.mark_reachable(false))?;
self.auth.mark_reachable(true);
if res.status == 401 && attempt == 0 && self.auth.unauthorized(&creds.token).await {
continue;
}
return Ok(res);
}
unreachable!()
}
pub async fn json(&self, method: &str, path: &str, body: Option<&Value>) -> Result<Value> {
let res = self.send(method, path, body).await?;
if !(200..300).contains(&res.status) {
return Err(rest_error(res.status, &res.body));
}
if res.body.is_empty() {
return Ok(Value::Null);
}
serde_json::from_slice(&res.body).map_err(|e| Error::new("invalid_response", e.to_string()))
}
}