Added get_albums and refactoring to make code more usable and less coupled

Signed-off-by: Louis Vallat <louis@louis-vallat.xyz>
This commit is contained in:
Louis Vallat 2021-10-17 23:36:18 +02:00
parent 6ef99ec389
commit c3882de838
No known key found for this signature in database
GPG Key ID: 0C87282F76E61283

View File

@ -1,27 +1,56 @@
use hyper_tls::HttpsConnector;
use hyper::{Body, Client, Method, Request};
use std::str;
use hyper::{Body, Client, Method, Request, Response, client::HttpConnector, header::{AUTHORIZATION, CONTENT_TYPE, COOKIE, HeaderValue, SET_COOKIE}};
use json::{JsonValue, object};
use dotenv::dotenv;
async fn body_to_str<'a>(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 req = Request::builder()
.method(Method::POST)
.uri(dotenv::var("LYCHEE_ENDPOINT").unwrap() + "/api/Session::init")
.body(Body::empty())
.expect("error");
let res = client.request(req).await?;
println!("{}", res.status().as_u16());
let buf = hyper::body::to_bytes(res).await?;
let s = str::from_utf8(&buf).unwrap();
println!("{:?}", s);
let lychee_session = login(&client).await;
let albums = get_albums(&client, lychee_session).await;
println!("{}", albums["albums"].pretty(4));
Ok(())
}