From 8a9da6e8da3694466a49cf1c39a5d078019b3140 Mon Sep 17 00:00:00 2001 From: Love Billenius Date: Sun, 14 Jul 2024 16:24:25 +0200 Subject: [PATCH] cloudflareresponse --- src/cloudflare.rs | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/src/cloudflare.rs b/src/cloudflare.rs index 5b1b45a..75839f4 100644 --- a/src/cloudflare.rs +++ b/src/cloudflare.rs @@ -34,6 +34,14 @@ struct DnsRecord { meta: HashMap, serde_json::Value>, } +#[derive(Serialize, Deserialize, Debug)] +struct CloudflareResponse { + success: bool, + errors: Vec>, + messages: Vec>, + result: Option>, +} + impl CloudflareClient { pub async fn new(api_key: Box, zone_id: Box, domains: Vec>) -> Result { let force_ipv4 = IpAddr::from([0, 0, 0, 0]); @@ -60,7 +68,7 @@ impl CloudflareClient { return Ok(()); } info!( - "Ip has changed from '{}' -> '{}'", + "IP has changed from '{}' -> '{}'", &self.current_ip, &new_ip ); self.update_dns_records(new_ip).await?; @@ -75,7 +83,7 @@ impl CloudflareClient { Ok(r) => r, Err(e) => { error!( - "Could not getch dns records for domain '{}': {:?}", + "Could not fetch DNS records for domain '{}': {:?}", &domain, &e ); continue; @@ -109,7 +117,8 @@ impl CloudflareClient { "https://api.cloudflare.com/client/v4/zones/{}/dns_records?type=A&name={}", self.zone_id, domain ); - let mut response = self + + let response = self .client .get(&url) .header("Authorization", format!("Bearer {}", self.api_key)) @@ -117,12 +126,23 @@ impl CloudflareClient { .send() .await? .error_for_status()? - .json::>>() + .text() .await?; - response - .remove("result") - .context("Key result not in return") + let cloudflare_response: CloudflareResponse = + serde_json::from_str(&response).context("Failed to deserialize Cloudflare response")?; + + if !cloudflare_response.success { + error!( + "Cloudflare API returned errors: {:?}", + cloudflare_response.errors + ); + return Err(anyhow::anyhow!("Cloudflare API returned errors")); + } + + cloudflare_response + .result + .context("Key 'result' not found in response") } async fn update_dns_record(&self, record: &mut DnsRecord, ip_content: Box) -> Result<()> {