diff --git a/Cargo.toml b/Cargo.toml index 5d1d2b9..b4e47a1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,3 +5,7 @@ edition = "2021" [dependencies] clap = { version = "4.2.7", features = ["cargo", "derive"] } +regex = "1.8.1" +reqwest = { version = "0.11.17", features = ["blocking", "json"] } +serde_json = "1.0.96" +spaceapi = "0.9.0" diff --git a/src/client.rs b/src/client.rs new file mode 100644 index 0000000..1663566 --- /dev/null +++ b/src/client.rs @@ -0,0 +1,36 @@ +use regex::Regex; +use spaceapi::Status; + +fn get_spaceapi(url: String) -> Status { + let user_agent = "spaceapi2prometheus"; + let status: Status; + loop { + let client = reqwest::blocking::Client::builder() + .user_agent(user_agent) + .build(); + if let Ok(c) = client { + let res = c.get(url).send().unwrap().text().unwrap(); + status = serde_json::from_str(&res).unwrap(); + break; + } + eprintln!("Failed to connect to endpoint, trying again!"); + std::thread::sleep(std::time::Duration::from_millis(10 * 1000)); + } + + status +} + +fn parse_capacity(msg: &str) -> i8 { + let regex = Regex::new(r"\d*").unwrap(); + let captures = regex.captures(msg).unwrap(); + + captures[0].parse::().unwrap() +} + +pub fn get_prometheus_string(url: String) -> String { + let status = get_spaceapi(url); + let capacity = parse_capacity(&status.clone().state.unwrap().message.unwrap()); + let lastchange = status.state.unwrap().lastchange.unwrap(); + + format!("people {} {}000\n", capacity, lastchange) +} diff --git a/src/main.rs b/src/main.rs index 8890ab9..89c3827 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,7 @@ use clap::Parser; +mod client; + #[derive(Parser)] #[command(version, about)] struct Cli {