From 60f5aaf69315ba0b3e4c47a8307955edc2963166 Mon Sep 17 00:00:00 2001 From: Allan Jorge Date: Thu, 14 May 2020 00:30:57 -0300 Subject: [PATCH] refactor --- src/commands.rs | 14 +++++++++----- src/process.rs | 51 +++++++++++++++++++++++++++++++++---------------- 2 files changed, 44 insertions(+), 21 deletions(-) diff --git a/src/commands.rs b/src/commands.rs index 09487b6..2e0b5ae 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -35,11 +35,15 @@ pub async fn process_code(api: &Api, message: &Message, code: &str) -> Result<() let process = process::start(message.from.id.to_string(), code) .await .unwrap(); - let reply = format!( - "Status: {}\n\ - Mensagem: {}", - process.status, process.info - ); + let reply = if let Some(process) = process { + format!( + "Status: {}\n\ + Mensagem: {}", + process.status, process.info + ) + } else { + "Processo não encontrado ou com status desconhecido.".to_owned() + }; api.send(message.text_reply(reply)).await?; diff --git a/src/process.rs b/src/process.rs index 57a4889..ea66ec5 100644 --- a/src/process.rs +++ b/src/process.rs @@ -18,16 +18,18 @@ pub struct ProcessResponse { pub async fn start( telegram_id: String, process_code: &str, -) -> Result> { +) -> Result, Box> { let p = fetch_for_one(&process_code).await?; - if p.status != "unknown" { - save(&telegram_id, &process_code, &p.status).await; + if let Some(process) = &p { + save(&telegram_id, &process_code, &process.status).await; } Ok(p) } -async fn fetch_for_one(process_code: &str) -> Result> { +async fn fetch_for_one( + process_code: &str, +) -> Result, Box> { Ok(fetch_citizenship_status(&process_code).await?) } @@ -56,29 +58,42 @@ pub async fn fetch_for_all() -> Result, Box Result { +async fn fetch_citizenship_status( + process_code: &str, +) -> Result, reqwest::Error> { + let process_body = fetch_process(process_code).await?; + let process_status = process_status(process_body); + Ok(process_status) +} + +async fn fetch_process(process_code: &str) -> Result { let res = reqwest::Client::new() .post("https://nacionalidade.justica.gov.pt/Home/GetEstadoProcessoAjax") .form(&[("SenhaAcesso", process_code)]) .send() .await?; - let body = res.text().await?; - let document = Document::from(body.as_str()); + Ok(res.text().await?) +} + +fn process_status(html: String) -> Option { + let document = Document::from(html.as_str()); let mut p = ProcessResponse { status: String::from("unknown"), @@ -103,5 +118,9 @@ async fn fetch_citizenship_status(process_code: &str) -> Result