lychee-client/src/main.rs
Louis Vallat 43750ab47a
Added test draft
Signed-off-by: Louis Vallat <louis@louis-vallat.xyz>
2021-10-18 10:21:47 +02:00

70 lines
2.3 KiB
Rust

use hyper_tls::HttpsConnector;
use hyper::{Body, Client, Method, Request, Response, client::HttpConnector, header::{AUTHORIZATION, CONTENT_TYPE, COOKIE, HeaderValue, SET_COOKIE}};
use json::{JsonValue, object};
use dotenv::dotenv;
pub async fn body_to_str(res: Response<Body>) -> String {
let body = hyper::body::to_bytes(res).await.unwrap();
let body_str = std::str::from_utf8(&body).unwrap().clone();
return body_str.to_string();
}
async fn login(client: &Client<HttpsConnector<HttpConnector>>) -> HeaderValue {
let login_data = object! {
"username": dotenv::var("USERNAME").unwrap(),
"password": dotenv::var("PASSWORD").unwrap()
};
let req = Request::builder()
.method(Method::POST)
.uri(dotenv::var("LYCHEE_ENDPOINT").unwrap() + "/api/Session::login")
.header(AUTHORIZATION, dotenv::var("API_KEY").unwrap())
.header(CONTENT_TYPE, "application/json")
.body(Body::from(login_data.dump()))
.expect("error");
let res = client.request(req).await.unwrap();
let lychee_session = res.headers().get(SET_COOKIE.as_str()).unwrap().clone();
assert_eq!(json::parse(body_to_str(res).await.as_str()).unwrap(), true);
return lychee_session;
}
async fn get_albums(client: &Client<HttpsConnector<HttpConnector>>, lychee_session: HeaderValue) -> JsonValue {
let req = Request::builder()
.method(Method::POST)
.uri(dotenv::var("LYCHEE_ENDPOINT").unwrap() + "/api/Albums::get")
.header(COOKIE, lychee_session)
.header(AUTHORIZATION, dotenv::var("API_KEY").unwrap())
.body(Body::empty())
.expect("error");
let _res = client.request(req).await.unwrap();
return json::parse(body_to_str(_res).await.as_str()).unwrap();
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
dotenv().ok();
let https = HttpsConnector::new();
let client = Client::builder().build::<_, hyper::Body>(https);
let lychee_session = login(&client).await;
let albums = get_albums(&client, lychee_session).await;
println!("{}", albums["albums"].pretty(4));
Ok(())
}
#[cfg(test)]
mod tests {
use hyper::{Body, Response};
use crate::body_to_str;
#[test]
fn body_to_str_empty() {
let res = Response::new(Body::empty());
assert_eq!("", tokio_test::block_on(body_to_str(res)));
}
}