diff --git a/src/main.rs b/src/main.rs index a1bd966..49ab8a6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -28,7 +28,7 @@ async fn main() -> Result<(), Box> { println!("Access token: {}", token.access_token); - let mut svc = catapult::service::Service { + let mut svc = catapult::service::core::Service { app: app.clone(), token, }; diff --git a/src/service/core.rs b/src/service/core.rs new file mode 100644 index 0000000..b17f2e7 --- /dev/null +++ b/src/service/core.rs @@ -0,0 +1,30 @@ +pub struct Service { + pub app: crate::app::App, + pub token: textsender_models::token::Login, +} + +impl Service { + pub async fn do_the_work(&mut self) { + println!("Do some work"); + todo!( + r#" + Need to finish this + + This function should fetch a token, check if the token is valid, and obtain a refresh token if + it has expired. + + Then do the real work. + + 1. Check the queue + 2. If there is an item, get the data, + 3. Evaluate if it is schedulable + 4. Get the events and iterate each one + 5. starting with the message + 6. Get the contact + 7. Send the message + 8. Record the message event response + "# + ); + } +} + diff --git a/src/service/mod.rs b/src/service/mod.rs index 41d02f8..bc71d8a 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -1,54 +1,13 @@ -pub struct Service { - pub app: crate::app::App, - pub token: textsender_models::token::Login, -} +pub mod core; -impl Service { - pub async fn do_the_work(&mut self) { - println!("Do some work"); - todo!( - r#" - Need to finish this - - This function should fetch a token, check if the token is valid, and obtain a refresh token if - it has expired. - - Then do the real work. - - 1. Check the queue - 2. If there is an item, get the data, - 3. Evaluate if it is schedulable - 4. Get the events and iterate each one - 5. starting with the message - 6. Get the contact - 7. Send the message - 8. Record the message event response - "# - ); - } -} pub mod auth { pub struct Auth { pub app: crate::app::App, } - /* - #[derive(serde::Deserialize, serde::Serialize)] - struct ServiceRequest { - pub username: String, - pub passphrase: String - } - */ - impl Auth { pub async fn get_token(&self) -> Result { - /* - let svcRequest = ServiceRequest { - username: self.app.service_username, - passphrase: self.app.service_passphrase, - }; - */ let client = reqwest::Client::new(); let endpoint = String::from("api/v1/service/login"); let api_url = format!("{}/{endpoint}", self.app.auth_url); @@ -69,37 +28,42 @@ pub mod auth { println!("Response: {response:?}"); match response.text().await { Ok(val) => { - match serde_json::from_str::(&val) { - Ok(j) => { - println!("Good"); - let message = &j["message"]; - let data = &j["data"]; + match parse_token_response(&val).await { + Ok(login_result) => Ok(login_result), + Err(err) => Err(err) + } + } + Err(err) => Err(std::io::Error::other(err)), + } + } + _ => Err(std::io::Error::other("Error getting token")), + } + } + Err(err) => Err(std::io::Error::other(err.to_string())), + } + } - println!("Message: {message:?}"); - println!("Data: {data:?}"); - match j.get("data") { - Some(serde_json::Value::Array(lrs)) => { - if lrs.is_empty() { - Err(std::io::Error::other( - "Error response is empty", - )) - } else { - let lr = lrs[0].clone(); - let ll: textsender_models::token::LoginResult = match serde_json::from_value(lr) { Ok(lr) => lr, - Err(err) => { - return Err(std::io::Error::other(err.to_string())); - } - }; - Ok(ll) - // Ok(textsender_models::token::LoginResult::default()) - } - } - _ => Err(std::io::Error::other( - "Error parsing response", - )), - } - } - Err(err) => Err(std::io::Error::other(err.to_string())), + pub async fn get_refresh_token(&self, login_result: &textsender_models::token::Login) -> Result { + let client = reqwest::Client::new(); + let endpoint = String::from("api/v1/token/refresh"); + let api_url = format!("{}/{endpoint}", self.app.auth_url); + + println!("Url: {api_url:?}"); + + let payload = serde_json::json!({ + "access_token": login_result.access_token + }); + + match client.post(api_url).json(&payload).send().await { + Ok(response) => { + match response.status() { + reqwest::StatusCode::OK => { + println!("Response: {response:?}"); + match response.text().await { + Ok(val) => { + match parse_token_response(&val).await { + Ok(login_result) => Ok(login_result), + Err(err) => Err(err) } } Err(err) => Err(std::io::Error::other(err)), @@ -112,73 +76,44 @@ pub mod auth { } } } + + async fn parse_token_response(response: &String) -> Result { + match serde_json::from_str::(response) { + Ok(j) => { + println!("Good"); + let message = &j["message"]; + let data = &j["data"]; + + println!("Message: {message:?}"); + println!("Data: {data:?}"); + match j.get("data") { + Some(serde_json::Value::Array(lrs)) => { + if lrs.is_empty() { + Err(std::io::Error::other( + "Error response is empty", + )) + } else { + let lr = lrs[0].clone(); + let ll: textsender_models::token::LoginResult = match serde_json::from_value(lr) { Ok(lr) => lr, + Err(err) => { + return Err(std::io::Error::other(err.to_string())); + } + }; + Ok(ll) + } + } + _ => Err(std::io::Error::other( + "Error parsing response", + )), + } + } + Err(err) => Err(std::io::Error::other(err.to_string())), + } + } } + /* -* - let client = reqwest::Client::new(); - let endpoint = String::from("api/v2/service/login"); - let api_url = format!("{}/{endpoint}", app.auth_uri); - - let payload = serde_json::json!({ - "passphrase": icarus_envy::environment::get_service_passphrase().await.value, - }); - - match client.post(api_url).json(&payload).send().await { - Ok(response) => match response - .json::() - .await - { - Ok(resp) => { - if resp.data.is_empty() { - Err(std::io::Error::other(String::from("No token returned"))) - } else { - Ok(resp.data[0].clone()) - } - } - Err(err) => Err(std::io::Error::other(err.to_string())), - }, - Err(err) => Err(std::io::Error::other(err.to_string())), - } -* -*/ - -/* - * -type tokenResponse struct { - Message string `json:"message"` - Data []*token.Login `json:"data"` -} - -func (a *Auth) GetToken() (*token.Login, error) { - serv := service{ - Username: a.Application.ServiceUsername, - Passphrase: a.Application.ServicePassphrase, - } - - jsonData, err := json.Marshal(serv) - if err != nil { - return nil, err - } - resp, err := http.Post( - fmt.Sprintf("%s/api/v1/service/login", a.Application.AuthUrl), - "application/json", - bytes.NewBuffer(jsonData), - ) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var r tokenResponse - err = json.NewDecoder(resp.Body).Decode(&r) - if err != nil { - return nil, err - } - - return r.Data[0], nil -} - type refreshTokenRequest struct { AccessToken string `json:"access_token"` }