From c3882de83816b50f6130419ae64ee22507b12506 Mon Sep 17 00:00:00 2001 From: Louis Vallat Date: Sun, 17 Oct 2021 23:36:18 +0200 Subject: [PATCH] Added get_albums and refactoring to make code more usable and less coupled Signed-off-by: Louis Vallat --- src/main.rs | 61 +++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 45 insertions(+), 16 deletions(-) diff --git a/src/main.rs b/src/main.rs index 716002f..c754050 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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) -> 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>) -> 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>, 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> { 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(()) } -