cloudflareresponse

This commit is contained in:
Love 2024-07-14 16:24:25 +02:00
parent bb8a83cb62
commit c74361bb56

View File

@ -34,6 +34,14 @@ struct DnsRecord {
meta: HashMap<Box<str>, serde_json::Value>,
}
#[derive(Serialize, Deserialize, Debug)]
struct CloudflareResponse {
success: bool,
errors: Vec<HashMap<String, serde_json::Value>>,
messages: Vec<HashMap<String, serde_json::Value>>,
result: Option<Vec<DnsRecord>>,
}
impl CloudflareClient {
pub async fn new(api_key: Box<str>, zone_id: Box<str>, domains: Vec<Box<str>>) -> Result<Self> {
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::<HashMap<String, Vec<DnsRecord>>>()
.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<str>) -> Result<()> {