Rewrite in Rust
This commit is contained in:
parent
331f0c092c
commit
e76c82492f
5 changed files with 1402 additions and 0 deletions
src/cloudflare
191
src/cloudflare/mod.rs
Normal file
191
src/cloudflare/mod.rs
Normal file
|
@ -0,0 +1,191 @@
|
|||
use reqwest::{blocking::{Response, Client}, Url};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use reqwest::header::{HeaderMap, HeaderValue};
|
||||
use std::{string::String, collections::HashMap};
|
||||
use strum_macros::{Display, IntoStaticStr};
|
||||
|
||||
const API_BASE: &str = "https://api.cloudflare.com/client/v4/";
|
||||
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct CloudflareDnsZone {
|
||||
result: Vec<CloudflareDnsEntry>,
|
||||
success: bool
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone, Copy)]
|
||||
#[derive(Display, IntoStaticStr)]
|
||||
pub enum CloudflareDnsType {
|
||||
#[strum(serialize = "A")]
|
||||
A,
|
||||
#[strum(serialize = "AAAA")]
|
||||
AAAA,
|
||||
TXT,
|
||||
MX
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct CloudflareDnsEntry {
|
||||
id: String,
|
||||
zone_id: String,
|
||||
pub name: String,
|
||||
pub r#type: CloudflareDnsType,
|
||||
content: String,
|
||||
proxied: bool
|
||||
}
|
||||
|
||||
impl CloudflareDnsEntry {
|
||||
pub fn is_equal(&self, other_entry: &String) -> bool {
|
||||
return if &self.name == other_entry { true } else { false };
|
||||
}
|
||||
|
||||
pub fn is_ip_new(&self, other_entry: &String) -> bool {
|
||||
return if &self.content == other_entry { false } else { true };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub(crate) struct Instance {
|
||||
api_key: String,
|
||||
pub dns_entries: Vec<CloudflareDnsEntry>,
|
||||
dns_email: String
|
||||
}
|
||||
|
||||
impl Instance {
|
||||
pub fn new(key: &String) -> Instance {
|
||||
Instance {
|
||||
api_key: key.clone(),
|
||||
dns_entries: Vec::new(),
|
||||
dns_email: "".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads all DNS entires in a Zone as a [`CloudflareDnsEntry`] Vector
|
||||
///
|
||||
/// * `email` : E-Mail Address associated with the Zone, required for [`generate_headers()`]
|
||||
/// * `zone_id` : Zone to be used for the Request
|
||||
pub fn load_entries(&mut self, email: &String, zone_id: &String) {
|
||||
self.dns_email = email.clone();
|
||||
let endpoint = format!("{}zones/{}/dns_records", API_BASE, zone_id);
|
||||
|
||||
let api_response = self.get(&endpoint);
|
||||
let entries = match api_response.json::<CloudflareDnsZone>() {
|
||||
Ok(data) => {data},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
|
||||
for entry in entries.result {
|
||||
self.dns_entries.append(&mut vec!(entry));
|
||||
}
|
||||
}
|
||||
|
||||
/// Shorthand for Cloudflare API Requests
|
||||
///
|
||||
/// Automatically appends Auth Headers and parses the URL
|
||||
///
|
||||
/// * `url` : URL for the request, will be parsed to [`Url`]
|
||||
/// * `email` : E-Mail Address associated with the Zone, required for [`generate_headers()`]
|
||||
fn get(&self, url: &str) -> Response {
|
||||
let url_parsed = match Url::parse(url) {
|
||||
Ok(url) => {url},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
|
||||
let client = Client::new();
|
||||
let res = client.get(url_parsed)
|
||||
.headers(self.generate_headers())
|
||||
.send();
|
||||
|
||||
let response = match res {
|
||||
Ok(res) => {res},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
fn put(&self, url: &str, data: &HashMap<&str, &str>) -> Response {
|
||||
let url_parsed = match Url::parse(url) {
|
||||
Ok(url) => {url},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
|
||||
let client = Client::new();
|
||||
let res = client.put(url_parsed)
|
||||
.headers(self.generate_headers())
|
||||
.json(data)
|
||||
.send();
|
||||
|
||||
let response = match res {
|
||||
Ok(res) => {res},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
fn post(&self, url: &str, data: &HashMap<&str, &str>) -> Response {
|
||||
let url_parsed = match Url::parse(url) {
|
||||
Ok(url) => {url},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
|
||||
let client = Client::new();
|
||||
let res = client.post(url_parsed)
|
||||
.headers(self.generate_headers())
|
||||
.json(data)
|
||||
.send();
|
||||
|
||||
let response = match res {
|
||||
Ok(res) => {res},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
pub fn update_entry(&self, entry: &CloudflareDnsEntry, new_ip: &String) -> bool {
|
||||
let endpoint = format!("{}zones/{}/dns_records/{}", API_BASE, entry.zone_id, entry.id);
|
||||
|
||||
let mut json_body = HashMap::new();
|
||||
json_body.insert("type", entry.r#type.clone().into());
|
||||
json_body.insert("name", entry.name.as_ref());
|
||||
json_body.insert("content", new_ip);
|
||||
json_body.insert("ttl", "1");
|
||||
|
||||
let api_response = self.put(&endpoint, &json_body);
|
||||
|
||||
let data = api_response.json::<serde_json::Value>().unwrap();
|
||||
|
||||
let ret = data["success"].as_bool().unwrap();
|
||||
|
||||
ret
|
||||
}
|
||||
|
||||
pub fn create_entry(&self, zone_id: &String, r#type: &str, name: &str, ip: &String) -> bool {
|
||||
let endpoint = format!("{}zones/{}/dns_records", API_BASE, zone_id);
|
||||
|
||||
let mut json_body = HashMap::new();
|
||||
json_body.insert("type", r#type);
|
||||
json_body.insert("name", name);
|
||||
json_body.insert("content", ip);
|
||||
json_body.insert("ttl", "1");
|
||||
|
||||
let api_response = self.post(&endpoint, &json_body);
|
||||
|
||||
let data = api_response.json::<serde_json::Value>().unwrap();
|
||||
|
||||
let ret = data["success"].as_bool().unwrap();
|
||||
|
||||
ret
|
||||
}
|
||||
|
||||
/// Generate Cloudflare API v4 Auth Headers
|
||||
fn generate_headers(&self) -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("X-Auth-Key", HeaderValue::from_str(self.api_key.as_ref()).unwrap());
|
||||
headers.insert("X-Auth-Email", HeaderValue::from_str(self.dns_email.as_ref()).unwrap());
|
||||
headers
|
||||
}
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue