Added ability to perform API requests
Some checks failed
Continuous integration / Check (push) Failing after 1m55s
Continuous integration / Test Suite (push) Failing after 2m30s
Continuous integration / Rustfmt (push) Failing after 36s
Continuous integration / Clippy (push) Failing after 2m2s
Continuous integration / build (push) Failing after 2m34s

This commit is contained in:
Luke Else 2025-02-21 14:46:46 +00:00
parent bb051eec61
commit 253b7ce9a9
5 changed files with 62 additions and 33 deletions

View File

@ -14,3 +14,4 @@ tokio = { version = "1.39.2", features = ["full"] }
tokio-macros = { version = "2.4.0" } tokio-macros = { version = "2.4.0" }
async-trait = "0.1.86" async-trait = "0.1.86"
futures = "0.3.31" futures = "0.3.31"
reqwest = "0.12.12"

View File

@ -1,12 +1,12 @@
use super::req::Requests; use super::req::Requests;
#[derive(PartialEq, Eq, Debug)] #[derive(PartialEq, Eq, Debug, Clone)]
pub struct Metar { pub struct Metar {
pub api: Requests, pub api: Requests,
} }
impl Default for Metar { impl Default for Metar {
fn default() -> Self { fn default() -> Self {
Metar { api: Requests{} } Metar { api: Requests::new() }
} }
} }

View File

@ -1,28 +1,35 @@
use std::error::Error; use std::error::Error;
use crate::error::AvBagError;
use reqwest::Client;
use tokio::{io::AsyncReadExt, net::TcpStream}; #[derive(Debug, Clone)]
pub struct Requests {
client: Client,
}
#[derive(PartialEq, Eq, Debug)] impl PartialEq for Requests {
pub struct Requests {} fn eq(&self, _: &Self) -> bool {
return true;
impl Requests {
pub async fn make_request(&self, target: String) -> Result<String, Box<dyn Error>> {
let tasks = tokio::spawn(async {
let mut buf: String = String::from("");
let mut stream = match TcpStream::connect(target).await {
Ok(stream) => stream,
Err(err) => return Err(Box::new(err)),
};
// Buffer to read HTTP request into
let _ = stream.read_to_string(&mut buf);
Ok(buf)
});
let buf = tasks.await??;
Ok(buf)
} }
} }
impl Eq for Requests {}
impl Requests {
pub fn new() -> Self {
Requests {
client: Client::new(),
}
}
pub async fn make_request(&self, target: String) -> Result<String, Box<dyn Error>> {
let response = self.client.get(&target).send().await?;
if response.status().is_success() {
let body = response.text().await?;
Ok(body)
} else {
Err(Box::new(AvBagError::RequestNotAvailable))
}
}
}

View File

@ -13,13 +13,12 @@ impl<'a> eframe::App for App<'a> {
// Display tabs for main UI // Display tabs for main UI
match self.tab_state.get_current_tab() { match self.tab_state.get_current_tab() {
Some(tab) => { Some(tab) => {
println!("Displaying tab");
block_on(tab.display_tab(ctx, &frame)); block_on(tab.display_tab(ctx, &frame));
}, },
// What to do if the tab is not available // TODO: What to do if the tab is not available
None => { None => {
println!("No tab available"); eprintln!("Tab not available");
}, },
}; };

View File

@ -1,15 +1,19 @@
use egui::Key; use egui::Key;
use async_trait::async_trait; use async_trait::async_trait;
use tokio::task;
use std::sync::Arc;
use tokio::sync::Mutex;
use crate::app::metar::Metar; use crate::app::metar::Metar;
use super::Tab; use super::Tab;
#[derive(Debug, PartialEq, Eq)] #[derive(Debug)]
pub struct MetarTab { pub struct MetarTab {
pub icaos: Vec<String>, pub icaos: Vec<String>,
pub metars: Vec<String>, pub metars: Vec<String>,
pub metar: Metar pub metar: Arc<Mutex<Metar>>
} }
impl Default for MetarTab { impl Default for MetarTab {
@ -17,16 +21,23 @@ impl Default for MetarTab {
Self { Self {
icaos: vec!["".to_string()], icaos: vec!["".to_string()],
metars: vec![], metars: vec![],
metar: Metar::default() metar: Arc::new(Mutex::new(Metar::default())),
} }
} }
} }
impl PartialEq for MetarTab {
fn eq(&self, other: &Self) -> bool {
self.icaos == other.icaos && self.metars == other.metars
}
}
impl Eq for MetarTab {}
#[async_trait] #[async_trait]
impl Tab for MetarTab { impl Tab for MetarTab {
async fn display_tab(&mut self, ctx: &egui::Context, frame: &egui::Frame) { async fn display_tab(&mut self, ctx: &egui::Context, frame: &egui::Frame) {
println!("Displaying METAR Tab"); egui::CentralPanel::default().frame(*frame).show(ctx, |ui|{
egui::CentralPanel::default().frame(*frame).show(ctx, |ui| {
// Given Key pressed, place focus on next item // Given Key pressed, place focus on next item
let new_icao_focus: bool = ui.input(|i| i.key_pressed(Key::Space)); let new_icao_focus: bool = ui.input(|i| i.key_pressed(Key::Space));
@ -36,6 +47,17 @@ impl Tab for MetarTab {
if ui.button("Add More").clicked() || new_icao_focus { if ui.button("Add More").clicked() || new_icao_focus {
self.icaos.push("".to_string()); self.icaos.push("".to_string());
// TODO: Improve error handling here
// Spawn an async task to handle the async operation
let metar_clone = Arc::clone(&self.metar);
task::spawn(async move {
let metar = metar_clone.lock().await;
match metar.api.make_request(String::from("https://google.co.uk")).await {
Ok(response) => println!("{:?}", response),
Err(e) => eprintln!("Request failed: {:?}", e),
}
});
} }
}); });
} }