use std::time::Duration; use anyhow::Result; use reqwest::blocking::Client; use crate::{ api::endpoints::UptimeKumaEndpoints, data::{self, heartbeat::HeartbeatResponse, status_page::model::StatusPageResponse}, i18n::t, }; #[derive(Debug, Clone)] pub struct UptimeKumaClient { client: Client, } impl UptimeKumaClient { pub fn new() -> Self { let client = Client::builder().connect_timeout(Duration::from_secs(10)).timeout(Duration::from_secs(30)).build().unwrap_or_else(|_| panic!("{}", t("http-build-error"))); Self { client, } } pub fn fetch_heartbeat(&self, endpoints: &UptimeKumaEndpoints) -> Result { self.fetch_and_parse(endpoints.heartbeat_url(), data::heartbeat::parse_response) } pub fn fetch_status_page(&self, endpoints: &UptimeKumaEndpoints) -> Result { self.fetch_and_parse( endpoints.status_page_url(), data::status_page::parse_response, ) } fn fetch_and_parse(&self, url: String, parser: F) -> Result where F: FnOnce(&str) -> Result, { let response = self.client.get(url.clone()).send()?; if response.status().is_success() { let json_text = response.text()?; parser(&json_text) } else { Err(anyhow::anyhow!( "URL: {}, Error: {}", url, response.status() )) } } }